sqlite3.c revision d86d9905ede0a2a313e349e4d0b4ba43b64cf8c3
1/******************************************************************************
2** This file is an amalgamation of many separate C source files from SQLite
3** version 3.6.22.  By combining all the individual C code files into this
4** single large file, the entire code can be compiled as a one translation
5** unit.  This allows many compilers to do optimizations that would not be
6** possible if the files were compiled separately.  Performance improvements
7** of 5% are more are commonly seen when SQLite is compiled as a single
8** translation unit.
9**
10** This file is all you need to compile SQLite.  To use SQLite in other
11** programs, you need this file and the "sqlite3.h" header file that defines
12** the programming interface to the SQLite library.  (If you do not have
13** the "sqlite3.h" header file at hand, you will find a copy embedded within
14** the text of this file.  Search for "Begin file sqlite3.h" to find the start
15** of the embedded sqlite3.h header file.) Additional code files may be needed
16** if you want a wrapper to interface SQLite with your choice of programming
17** language. The code for the "sqlite3" command-line shell is also in a
18** separate file. This file contains only code for the core SQLite library.
19*/
20#define SQLITE_CORE 1
21#define SQLITE_AMALGAMATION 1
22#ifndef SQLITE_PRIVATE
23# define SQLITE_PRIVATE static
24#endif
25#ifndef SQLITE_API
26# define SQLITE_API
27#endif
28/************** Begin file sqliteInt.h ***************************************/
29/*
30** 2001 September 15
31**
32** The author disclaims copyright to this source code.  In place of
33** a legal notice, here is a blessing:
34**
35**    May you do good and not evil.
36**    May you find forgiveness for yourself and forgive others.
37**    May you share freely, never taking more than you give.
38**
39*************************************************************************
40** Internal interface definitions for SQLite.
41**
42*/
43#ifndef _SQLITEINT_H_
44#define _SQLITEINT_H_
45
46/*
47** These #defines should enable >2GB file support on POSIX if the
48** underlying operating system supports it.  If the OS lacks
49** large file support, or if the OS is windows, these should be no-ops.
50**
51** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
52** system #includes.  Hence, this block of code must be the very first
53** code in all source files.
54**
55** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
56** on the compiler command line.  This is necessary if you are compiling
57** on a recent machine (ex: Red Hat 7.2) but you want your code to work
58** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
59** without this option, LFS is enable.  But LFS does not exist in the kernel
60** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
61** portability you should omit LFS.
62**
63** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
64*/
65#ifndef SQLITE_DISABLE_LFS
66# define _LARGE_FILE       1
67# ifndef _FILE_OFFSET_BITS
68#   define _FILE_OFFSET_BITS 64
69# endif
70# define _LARGEFILE_SOURCE 1
71#endif
72
73/*
74** Include the configuration header output by 'configure' if we're using the
75** autoconf-based build
76*/
77#ifdef _HAVE_SQLITE_CONFIG_H
78#include "config.h"
79#endif
80
81/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
82/************** Begin file sqliteLimit.h *************************************/
83/*
84** 2007 May 7
85**
86** The author disclaims copyright to this source code.  In place of
87** a legal notice, here is a blessing:
88**
89**    May you do good and not evil.
90**    May you find forgiveness for yourself and forgive others.
91**    May you share freely, never taking more than you give.
92**
93*************************************************************************
94**
95** This file defines various limits of what SQLite can process.
96*/
97
98/*
99** The maximum length of a TEXT or BLOB in bytes.   This also
100** limits the size of a row in a table or index.
101**
102** The hard limit is the ability of a 32-bit signed integer
103** to count the size: 2^31-1 or 2147483647.
104*/
105#ifndef SQLITE_MAX_LENGTH
106# define SQLITE_MAX_LENGTH 1000000000
107#endif
108
109/*
110** This is the maximum number of
111**
112**    * Columns in a table
113**    * Columns in an index
114**    * Columns in a view
115**    * Terms in the SET clause of an UPDATE statement
116**    * Terms in the result set of a SELECT statement
117**    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
118**    * Terms in the VALUES clause of an INSERT statement
119**
120** The hard upper limit here is 32676.  Most database people will
121** tell you that in a well-normalized database, you usually should
122** not have more than a dozen or so columns in any table.  And if
123** that is the case, there is no point in having more than a few
124** dozen values in any of the other situations described above.
125*/
126#ifndef SQLITE_MAX_COLUMN
127# define SQLITE_MAX_COLUMN 2000
128#endif
129
130/*
131** The maximum length of a single SQL statement in bytes.
132**
133** It used to be the case that setting this value to zero would
134** turn the limit off.  That is no longer true.  It is not possible
135** to turn this limit off.
136*/
137#ifndef SQLITE_MAX_SQL_LENGTH
138# define SQLITE_MAX_SQL_LENGTH 1000000000
139#endif
140
141/*
142** The maximum depth of an expression tree. This is limited to
143** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
144** want to place more severe limits on the complexity of an
145** expression.
146**
147** A value of 0 used to mean that the limit was not enforced.
148** But that is no longer true.  The limit is now strictly enforced
149** at all times.
150*/
151#ifndef SQLITE_MAX_EXPR_DEPTH
152# define SQLITE_MAX_EXPR_DEPTH 1000
153#endif
154
155/*
156** The maximum number of terms in a compound SELECT statement.
157** The code generator for compound SELECT statements does one
158** level of recursion for each term.  A stack overflow can result
159** if the number of terms is too large.  In practice, most SQL
160** never has more than 3 or 4 terms.  Use a value of 0 to disable
161** any limit on the number of terms in a compount SELECT.
162*/
163#ifndef SQLITE_MAX_COMPOUND_SELECT
164# define SQLITE_MAX_COMPOUND_SELECT 500
165#endif
166
167/*
168** The maximum number of opcodes in a VDBE program.
169** Not currently enforced.
170*/
171#ifndef SQLITE_MAX_VDBE_OP
172# define SQLITE_MAX_VDBE_OP 25000
173#endif
174
175/*
176** The maximum number of arguments to an SQL function.
177*/
178#ifndef SQLITE_MAX_FUNCTION_ARG
179# define SQLITE_MAX_FUNCTION_ARG 127
180#endif
181
182/*
183** The maximum number of in-memory pages to use for the main database
184** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
185*/
186#ifndef SQLITE_DEFAULT_CACHE_SIZE
187# define SQLITE_DEFAULT_CACHE_SIZE  2000
188#endif
189#ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
190# define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
191#endif
192
193/*
194** The maximum number of attached databases.  This must be between 0
195** and 30.  The upper bound on 30 is because a 32-bit integer bitmap
196** is used internally to track attached databases.
197*/
198#ifndef SQLITE_MAX_ATTACHED
199# define SQLITE_MAX_ATTACHED 10
200#endif
201
202
203/*
204** The maximum value of a ?nnn wildcard that the parser will accept.
205*/
206#ifndef SQLITE_MAX_VARIABLE_NUMBER
207# define SQLITE_MAX_VARIABLE_NUMBER 999
208#endif
209
210/* Maximum page size.  The upper bound on this value is 32768.  This a limit
211** imposed by the necessity of storing the value in a 2-byte unsigned integer
212** and the fact that the page size must be a power of 2.
213**
214** If this limit is changed, then the compiled library is technically
215** incompatible with an SQLite library compiled with a different limit. If
216** a process operating on a database with a page-size of 65536 bytes
217** crashes, then an instance of SQLite compiled with the default page-size
218** limit will not be able to rollback the aborted transaction. This could
219** lead to database corruption.
220*/
221#ifndef SQLITE_MAX_PAGE_SIZE
222# define SQLITE_MAX_PAGE_SIZE 32768
223#endif
224
225
226/*
227** The default size of a database page.
228*/
229#ifndef SQLITE_DEFAULT_PAGE_SIZE
230# define SQLITE_DEFAULT_PAGE_SIZE 1024
231#endif
232#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
233# undef SQLITE_DEFAULT_PAGE_SIZE
234# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
235#endif
236
237/*
238** Ordinarily, if no value is explicitly provided, SQLite creates databases
239** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
240** device characteristics (sector-size and atomic write() support),
241** SQLite may choose a larger value. This constant is the maximum value
242** SQLite will choose on its own.
243*/
244#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
245# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
246#endif
247#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
248# undef SQLITE_MAX_DEFAULT_PAGE_SIZE
249# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
250#endif
251
252
253/*
254** Maximum number of pages in one database file.
255**
256** This is really just the default value for the max_page_count pragma.
257** This value can be lowered (or raised) at run-time using that the
258** max_page_count macro.
259*/
260#ifndef SQLITE_MAX_PAGE_COUNT
261# define SQLITE_MAX_PAGE_COUNT 1073741823
262#endif
263
264/*
265** Maximum length (in bytes) of the pattern in a LIKE or GLOB
266** operator.
267*/
268#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
269# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
270#endif
271
272/*
273** Maximum depth of recursion for triggers.
274**
275** A value of 1 means that a trigger program will not be able to itself
276** fire any triggers. A value of 0 means that no trigger programs at all
277** may be executed.
278*/
279#ifndef SQLITE_MAX_TRIGGER_DEPTH
280# define SQLITE_MAX_TRIGGER_DEPTH 1000
281#endif
282
283/************** End of sqliteLimit.h *****************************************/
284/************** Continuing where we left off in sqliteInt.h ******************/
285
286/* Disable nuisance warnings on Borland compilers */
287#if defined(__BORLANDC__)
288#pragma warn -rch /* unreachable code */
289#pragma warn -ccc /* Condition is always true or false */
290#pragma warn -aus /* Assigned value is never used */
291#pragma warn -csu /* Comparing signed and unsigned */
292#pragma warn -spa /* Suspicious pointer arithmetic */
293#endif
294
295/* Needed for various definitions... */
296#ifndef _GNU_SOURCE
297# define _GNU_SOURCE
298#endif
299
300/*
301** Include standard header files as necessary
302*/
303#ifdef HAVE_STDINT_H
304#include <stdint.h>
305#endif
306#ifdef HAVE_INTTYPES_H
307#include <inttypes.h>
308#endif
309
310#define SQLITE_INDEX_SAMPLES 10
311
312/*
313** This macro is used to "hide" some ugliness in casting an int
314** value to a ptr value under the MSVC 64-bit compiler.   Casting
315** non 64-bit values to ptr types results in a "hard" error with
316** the MSVC 64-bit compiler which this attempts to avoid.
317**
318** A simple compiler pragma or casting sequence could not be found
319** to correct this in all situations, so this macro was introduced.
320**
321** It could be argued that the intptr_t type could be used in this
322** case, but that type is not available on all compilers, or
323** requires the #include of specific headers which differs between
324** platforms.
325**
326** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
327** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
328** So we have to define the macros in different ways depending on the
329** compiler.
330*/
331#if defined(__GNUC__)
332# if defined(HAVE_STDINT_H)
333#   define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
334#   define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
335# else
336#   define SQLITE_INT_TO_PTR(X)  ((void*)(X))
337#   define SQLITE_PTR_TO_INT(X)  ((int)(X))
338# endif
339#else
340# define SQLITE_INT_TO_PTR(X)   ((void*)&((char*)0)[X])
341# define SQLITE_PTR_TO_INT(X)   ((int)(((char*)X)-(char*)0))
342#endif
343
344
345/*
346** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
347** Older versions of SQLite used an optional THREADSAFE macro.
348** We support that for legacy
349*/
350#if !defined(SQLITE_THREADSAFE)
351#if defined(THREADSAFE)
352# define SQLITE_THREADSAFE THREADSAFE
353#else
354# define SQLITE_THREADSAFE 1
355#endif
356#endif
357
358/*
359** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
360** It determines whether or not the features related to
361** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
362** be overridden at runtime using the sqlite3_config() API.
363*/
364#if !defined(SQLITE_DEFAULT_MEMSTATUS)
365# define SQLITE_DEFAULT_MEMSTATUS 1
366#endif
367
368/*
369** Exactly one of the following macros must be defined in order to
370** specify which memory allocation subsystem to use.
371**
372**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
373**     SQLITE_MEMDEBUG               // Debugging version of system malloc()
374**     SQLITE_MEMORY_SIZE            // internal allocator #1
375**     SQLITE_MMAP_HEAP_SIZE         // internal mmap() allocator
376**     SQLITE_POW2_MEMORY_SIZE       // internal power-of-two allocator
377**
378** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
379** the default.
380*/
381#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
382    defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
383    defined(SQLITE_POW2_MEMORY_SIZE)>1
384# error "At most one of the following compile-time configuration options\
385 is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\
386 SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE"
387#endif
388#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
389    defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
390    defined(SQLITE_POW2_MEMORY_SIZE)==0
391# define SQLITE_SYSTEM_MALLOC 1
392#endif
393
394/*
395** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
396** sizes of memory allocations below this value where possible.
397*/
398#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
399# define SQLITE_MALLOC_SOFT_LIMIT 1024
400#endif
401
402/*
403** We need to define _XOPEN_SOURCE as follows in order to enable
404** recursive mutexes on most Unix systems.  But Mac OS X is different.
405** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
406** so it is omitted there.  See ticket #2673.
407**
408** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
409** implemented on some systems.  So we avoid defining it at all
410** if it is already defined or if it is unneeded because we are
411** not doing a threadsafe build.  Ticket #2681.
412**
413** See also ticket #2741.
414*/
415#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
416#  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
417#endif
418
419/*
420** The TCL headers are only needed when compiling the TCL bindings.
421*/
422#if defined(SQLITE_TCL) || defined(TCLSH)
423# include <tcl.h>
424#endif
425
426/*
427** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
428** Setting NDEBUG makes the code smaller and run faster.  So the following
429** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
430** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
431** feature.
432*/
433#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
434# define NDEBUG 1
435#endif
436
437/*
438** The testcase() macro is used to aid in coverage testing.  When
439** doing coverage testing, the condition inside the argument to
440** testcase() must be evaluated both true and false in order to
441** get full branch coverage.  The testcase() macro is inserted
442** to help ensure adequate test coverage in places where simple
443** condition/decision coverage is inadequate.  For example, testcase()
444** can be used to make sure boundary values are tested.  For
445** bitmask tests, testcase() can be used to make sure each bit
446** is significant and used at least once.  On switch statements
447** where multiple cases go to the same block of code, testcase()
448** can insure that all cases are evaluated.
449**
450*/
451#ifdef SQLITE_COVERAGE_TEST
452SQLITE_PRIVATE   void sqlite3Coverage(int);
453# define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
454#else
455# define testcase(X)
456#endif
457
458/*
459** The TESTONLY macro is used to enclose variable declarations or
460** other bits of code that are needed to support the arguments
461** within testcase() and assert() macros.
462*/
463#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
464# define TESTONLY(X)  X
465#else
466# define TESTONLY(X)
467#endif
468
469/*
470** Sometimes we need a small amount of code such as a variable initialization
471** to setup for a later assert() statement.  We do not want this code to
472** appear when assert() is disabled.  The following macro is therefore
473** used to contain that setup code.  The "VVA" acronym stands for
474** "Verification, Validation, and Accreditation".  In other words, the
475** code within VVA_ONLY() will only run during verification processes.
476*/
477#ifndef NDEBUG
478# define VVA_ONLY(X)  X
479#else
480# define VVA_ONLY(X)
481#endif
482
483/*
484** The ALWAYS and NEVER macros surround boolean expressions which
485** are intended to always be true or false, respectively.  Such
486** expressions could be omitted from the code completely.  But they
487** are included in a few cases in order to enhance the resilience
488** of SQLite to unexpected behavior - to make the code "self-healing"
489** or "ductile" rather than being "brittle" and crashing at the first
490** hint of unplanned behavior.
491**
492** In other words, ALWAYS and NEVER are added for defensive code.
493**
494** When doing coverage testing ALWAYS and NEVER are hard-coded to
495** be true and false so that the unreachable code then specify will
496** not be counted as untested code.
497*/
498#if defined(SQLITE_COVERAGE_TEST)
499# define ALWAYS(X)      (1)
500# define NEVER(X)       (0)
501#elif !defined(NDEBUG)
502# define ALWAYS(X)      ((X)?1:(assert(0),0))
503# define NEVER(X)       ((X)?(assert(0),1):0)
504#else
505# define ALWAYS(X)      (X)
506# define NEVER(X)       (X)
507#endif
508
509/*
510** The macro unlikely() is a hint that surrounds a boolean
511** expression that is usually false.  Macro likely() surrounds
512** a boolean expression that is usually true.  GCC is able to
513** use these hints to generate better code, sometimes.
514*/
515#if defined(__GNUC__) && 0
516# define likely(X)    __builtin_expect((X),1)
517# define unlikely(X)  __builtin_expect((X),0)
518#else
519# define likely(X)    !!(X)
520# define unlikely(X)  !!(X)
521#endif
522
523/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
524/************** Begin file sqlite3.h *****************************************/
525/*
526** 2001 September 15
527**
528** The author disclaims copyright to this source code.  In place of
529** a legal notice, here is a blessing:
530**
531**    May you do good and not evil.
532**    May you find forgiveness for yourself and forgive others.
533**    May you share freely, never taking more than you give.
534**
535*************************************************************************
536** This header file defines the interface that the SQLite library
537** presents to client programs.  If a C-function, structure, datatype,
538** or constant definition does not appear in this file, then it is
539** not a published API of SQLite, is subject to change without
540** notice, and should not be referenced by programs that use SQLite.
541**
542** Some of the definitions that are in this file are marked as
543** "experimental".  Experimental interfaces are normally new
544** features recently added to SQLite.  We do not anticipate changes
545** to experimental interfaces but reserve the right to make minor changes
546** if experience from use "in the wild" suggest such changes are prudent.
547**
548** The official C-language API documentation for SQLite is derived
549** from comments in this file.  This file is the authoritative source
550** on how SQLite interfaces are suppose to operate.
551**
552** The name of this file under configuration management is "sqlite.h.in".
553** The makefile makes some minor changes to this file (such as inserting
554** the version number) and changes its name to "sqlite3.h" as
555** part of the build process.
556*/
557#ifndef _SQLITE3_H_
558#define _SQLITE3_H_
559#include <stdarg.h>     /* Needed for the definition of va_list */
560
561/*
562** Make sure we can call this stuff from C++.
563*/
564#if 0
565extern "C" {
566#endif
567
568
569/*
570** Add the ability to override 'extern'
571*/
572#ifndef SQLITE_EXTERN
573# define SQLITE_EXTERN extern
574#endif
575
576#ifndef SQLITE_API
577# define SQLITE_API
578#endif
579
580
581/*
582** These no-op macros are used in front of interfaces to mark those
583** interfaces as either deprecated or experimental.  New applications
584** should not use deprecated interfaces - they are support for backwards
585** compatibility only.  Application writers should be aware that
586** experimental interfaces are subject to change in point releases.
587**
588** These macros used to resolve to various kinds of compiler magic that
589** would generate warning messages when they were used.  But that
590** compiler magic ended up generating such a flurry of bug reports
591** that we have taken it all out and gone back to using simple
592** noop macros.
593*/
594#define SQLITE_DEPRECATED
595#define SQLITE_EXPERIMENTAL
596
597/*
598** Ensure these symbols were not defined by some previous header file.
599*/
600#ifdef SQLITE_VERSION
601# undef SQLITE_VERSION
602#endif
603#ifdef SQLITE_VERSION_NUMBER
604# undef SQLITE_VERSION_NUMBER
605#endif
606
607/*
608** CAPI3REF: Compile-Time Library Version Numbers
609**
610** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
611** evaluates to a string literal that is the SQLite version in the
612** format "X.Y.Z" where X is the major version number (always 3 for
613** SQLite3) and Y is the minor version number and Z is the release number.)^
614** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
615** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
616** numbers used in [SQLITE_VERSION].)^
617** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
618** be larger than the release from which it is derived.  Either Y will
619** be held constant and Z will be incremented or else Y will be incremented
620** and Z will be reset to zero.
621**
622** Since version 3.6.18, SQLite source code has been stored in the
623** <a href="http://www.fossil-scm.org/">Fossil configuration management
624** system</a>.  ^The SQLITE_SOURCE_ID macro evalutes to
625** a string which identifies a particular check-in of SQLite
626** within its configuration management system.  ^The SQLITE_SOURCE_ID
627** string contains the date and time of the check-in (UTC) and an SHA1
628** hash of the entire source tree.
629**
630** See also: [sqlite3_libversion()],
631** [sqlite3_libversion_number()], [sqlite3_sourceid()],
632** [sqlite_version()] and [sqlite_source_id()].
633*/
634#define SQLITE_VERSION        "3.6.22"
635#define SQLITE_VERSION_NUMBER 3006022
636#define SQLITE_SOURCE_ID      "2010-03-22 23:55:10 82dd61fccff3e4c77e060e5734cd4b4e2eeb7c32"
637
638/*
639** CAPI3REF: Run-Time Library Version Numbers
640** KEYWORDS: sqlite3_version
641**
642** These interfaces provide the same information as the [SQLITE_VERSION],
643** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
644** but are associated with the library instead of the header file.  ^(Cautious
645** programmers might include assert() statements in their application to
646** verify that values returned by these interfaces match the macros in
647** the header, and thus insure that the application is
648** compiled with matching library and header files.
649**
650** <blockquote><pre>
651** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
652** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
653** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
654** </pre></blockquote>)^
655**
656** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
657** macro.  ^The sqlite3_libversion() function returns a pointer to the
658** to the sqlite3_version[] string constant.  The sqlite3_libversion()
659** function is provided for use in DLLs since DLL users usually do not have
660** direct access to string constants within the DLL.  ^The
661** sqlite3_libversion_number() function returns an integer equal to
662** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function a pointer
663** to a string constant whose value is the same as the [SQLITE_SOURCE_ID]
664** C preprocessor macro.
665**
666** See also: [sqlite_version()] and [sqlite_source_id()].
667*/
668SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
669SQLITE_API const char *sqlite3_libversion(void);
670SQLITE_API const char *sqlite3_sourceid(void);
671SQLITE_API int sqlite3_libversion_number(void);
672
673/*
674** CAPI3REF: Test To See If The Library Is Threadsafe
675**
676** ^The sqlite3_threadsafe() function returns zero if and only if
677** SQLite was compiled mutexing code omitted due to the
678** [SQLITE_THREADSAFE] compile-time option being set to 0.
679**
680** SQLite can be compiled with or without mutexes.  When
681** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
682** are enabled and SQLite is threadsafe.  When the
683** [SQLITE_THREADSAFE] macro is 0,
684** the mutexes are omitted.  Without the mutexes, it is not safe
685** to use SQLite concurrently from more than one thread.
686**
687** Enabling mutexes incurs a measurable performance penalty.
688** So if speed is of utmost importance, it makes sense to disable
689** the mutexes.  But for maximum safety, mutexes should be enabled.
690** ^The default behavior is for mutexes to be enabled.
691**
692** This interface can be used by an application to make sure that the
693** version of SQLite that it is linking against was compiled with
694** the desired setting of the [SQLITE_THREADSAFE] macro.
695**
696** This interface only reports on the compile-time mutex setting
697** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
698** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
699** can be fully or partially disabled using a call to [sqlite3_config()]
700** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
701** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
702** sqlite3_threadsafe() function shows only the compile-time setting of
703** thread safety, not any run-time changes to that setting made by
704** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
705** is unchanged by calls to sqlite3_config().)^
706**
707** See the [threading mode] documentation for additional information.
708*/
709SQLITE_API int sqlite3_threadsafe(void);
710
711/*
712** CAPI3REF: Database Connection Handle
713** KEYWORDS: {database connection} {database connections}
714**
715** Each open SQLite database is represented by a pointer to an instance of
716** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
717** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
718** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
719** is its destructor.  There are many other interfaces (such as
720** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
721** [sqlite3_busy_timeout()] to name but three) that are methods on an
722** sqlite3 object.
723*/
724typedef struct sqlite3 sqlite3;
725
726/*
727** CAPI3REF: 64-Bit Integer Types
728** KEYWORDS: sqlite_int64 sqlite_uint64
729**
730** Because there is no cross-platform way to specify 64-bit integer types
731** SQLite includes typedefs for 64-bit signed and unsigned integers.
732**
733** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
734** The sqlite_int64 and sqlite_uint64 types are supported for backwards
735** compatibility only.
736**
737** ^The sqlite3_int64 and sqlite_int64 types can store integer values
738** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
739** sqlite3_uint64 and sqlite_uint64 types can store integer values
740** between 0 and +18446744073709551615 inclusive.
741*/
742#ifdef SQLITE_INT64_TYPE
743  typedef SQLITE_INT64_TYPE sqlite_int64;
744  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
745#elif defined(_MSC_VER) || defined(__BORLANDC__)
746  typedef __int64 sqlite_int64;
747  typedef unsigned __int64 sqlite_uint64;
748#else
749  typedef long long int sqlite_int64;
750  typedef unsigned long long int sqlite_uint64;
751#endif
752typedef sqlite_int64 sqlite3_int64;
753typedef sqlite_uint64 sqlite3_uint64;
754
755/*
756** If compiling for a processor that lacks floating point support,
757** substitute integer for floating-point.
758*/
759#ifdef SQLITE_OMIT_FLOATING_POINT
760# define double sqlite3_int64
761#endif
762
763/*
764** CAPI3REF: Closing A Database Connection
765**
766** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
767** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
768** successfullly destroyed and all associated resources are deallocated.
769**
770** Applications must [sqlite3_finalize | finalize] all [prepared statements]
771** and [sqlite3_blob_close | close] all [BLOB handles] associated with
772** the [sqlite3] object prior to attempting to close the object.  ^If
773** sqlite3_close() is called on a [database connection] that still has
774** outstanding [prepared statements] or [BLOB handles], then it returns
775** SQLITE_BUSY.
776**
777** ^If [sqlite3_close()] is invoked while a transaction is open,
778** the transaction is automatically rolled back.
779**
780** The C parameter to [sqlite3_close(C)] must be either a NULL
781** pointer or an [sqlite3] object pointer obtained
782** from [sqlite3_open()], [sqlite3_open16()], or
783** [sqlite3_open_v2()], and not previously closed.
784** ^Calling sqlite3_close() with a NULL pointer argument is a
785** harmless no-op.
786*/
787SQLITE_API int sqlite3_close(sqlite3 *);
788
789/*
790** The type for a callback function.
791** This is legacy and deprecated.  It is included for historical
792** compatibility and is not documented.
793*/
794typedef int (*sqlite3_callback)(void*,int,char**, char**);
795
796/*
797** CAPI3REF: One-Step Query Execution Interface
798**
799** The sqlite3_exec() interface is a convenience wrapper around
800** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
801** that allows an application to run multiple statements of SQL
802** without having to use a lot of C code.
803**
804** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
805** semicolon-separate SQL statements passed into its 2nd argument,
806** in the context of the [database connection] passed in as its 1st
807** argument.  ^If the callback function of the 3rd argument to
808** sqlite3_exec() is not NULL, then it is invoked for each result row
809** coming out of the evaluated SQL statements.  ^The 4th argument to
810** to sqlite3_exec() is relayed through to the 1st argument of each
811** callback invocation.  ^If the callback pointer to sqlite3_exec()
812** is NULL, then no callback is ever invoked and result rows are
813** ignored.
814**
815** ^If an error occurs while evaluating the SQL statements passed into
816** sqlite3_exec(), then execution of the current statement stops and
817** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
818** is not NULL then any error message is written into memory obtained
819** from [sqlite3_malloc()] and passed back through the 5th parameter.
820** To avoid memory leaks, the application should invoke [sqlite3_free()]
821** on error message strings returned through the 5th parameter of
822** of sqlite3_exec() after the error message string is no longer needed.
823** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
824** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
825** NULL before returning.
826**
827** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
828** routine returns SQLITE_ABORT without invoking the callback again and
829** without running any subsequent SQL statements.
830**
831** ^The 2nd argument to the sqlite3_exec() callback function is the
832** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
833** callback is an array of pointers to strings obtained as if from
834** [sqlite3_column_text()], one for each column.  ^If an element of a
835** result row is NULL then the corresponding string pointer for the
836** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
837** sqlite3_exec() callback is an array of pointers to strings where each
838** entry represents the name of corresponding result column as obtained
839** from [sqlite3_column_name()].
840**
841** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
842** to an empty string, or a pointer that contains only whitespace and/or
843** SQL comments, then no SQL statements are evaluated and the database
844** is not changed.
845**
846** Restrictions:
847**
848** <ul>
849** <li> The application must insure that the 1st parameter to sqlite3_exec()
850**      is a valid and open [database connection].
851** <li> The application must not close [database connection] specified by
852**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
853** <li> The application must not modify the SQL statement text passed into
854**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
855** </ul>
856*/
857SQLITE_API int sqlite3_exec(
858  sqlite3*,                                  /* An open database */
859  const char *sql,                           /* SQL to be evaluated */
860  int (*callback)(void*,int,char**,char**),  /* Callback function */
861  void *,                                    /* 1st argument to callback */
862  char **errmsg                              /* Error msg written here */
863);
864
865/*
866** CAPI3REF: Result Codes
867** KEYWORDS: SQLITE_OK {error code} {error codes}
868** KEYWORDS: {result code} {result codes}
869**
870** Many SQLite functions return an integer result code from the set shown
871** here in order to indicates success or failure.
872**
873** New error codes may be added in future versions of SQLite.
874**
875** See also: [SQLITE_IOERR_READ | extended result codes]
876*/
877#define SQLITE_OK           0   /* Successful result */
878/* beginning-of-error-codes */
879#define SQLITE_ERROR        1   /* SQL error or missing database */
880#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
881#define SQLITE_PERM         3   /* Access permission denied */
882#define SQLITE_ABORT        4   /* Callback routine requested an abort */
883#define SQLITE_BUSY         5   /* The database file is locked */
884#define SQLITE_LOCKED       6   /* A table in the database is locked */
885#define SQLITE_NOMEM        7   /* A malloc() failed */
886#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
887#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
888#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
889#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
890#define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
891#define SQLITE_FULL        13   /* Insertion failed because database is full */
892#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
893#define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
894#define SQLITE_EMPTY       16   /* Database is empty */
895#define SQLITE_SCHEMA      17   /* The database schema changed */
896#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
897#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
898#define SQLITE_MISMATCH    20   /* Data type mismatch */
899#define SQLITE_MISUSE      21   /* Library used incorrectly */
900#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
901#define SQLITE_AUTH        23   /* Authorization denied */
902#define SQLITE_FORMAT      24   /* Auxiliary database format error */
903#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
904#define SQLITE_NOTADB      26   /* File opened that is not a database file */
905#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
906#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
907/* end-of-error-codes */
908
909/*
910** CAPI3REF: Extended Result Codes
911** KEYWORDS: {extended error code} {extended error codes}
912** KEYWORDS: {extended result code} {extended result codes}
913**
914** In its default configuration, SQLite API routines return one of 26 integer
915** [SQLITE_OK | result codes].  However, experience has shown that many of
916** these result codes are too coarse-grained.  They do not provide as
917** much information about problems as programmers might like.  In an effort to
918** address this, newer versions of SQLite (version 3.3.8 and later) include
919** support for additional result codes that provide more detailed information
920** about errors. The extended result codes are enabled or disabled
921** on a per database connection basis using the
922** [sqlite3_extended_result_codes()] API.
923**
924** Some of the available extended result codes are listed here.
925** One may expect the number of extended result codes will be expand
926** over time.  Software that uses extended result codes should expect
927** to see new result codes in future releases of SQLite.
928**
929** The SQLITE_OK result code will never be extended.  It will always
930** be exactly zero.
931*/
932#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
933#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
934#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
935#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
936#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
937#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
938#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
939#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
940#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
941#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
942#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
943#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
944#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
945#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
946#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
947#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
948#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
949#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED | (1<<8) )
950
951/*
952** CAPI3REF: Flags For File Open Operations
953**
954** These bit values are intended for use in the
955** 3rd parameter to the [sqlite3_open_v2()] interface and
956** in the 4th parameter to the xOpen method of the
957** [sqlite3_vfs] object.
958*/
959#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
960#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
961#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
962#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
963#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
964#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
965#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
966#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
967#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
968#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
969#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
970#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
971#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
972#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
973#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
974#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
975
976/*
977** CAPI3REF: Device Characteristics
978**
979** The xDeviceCapabilities method of the [sqlite3_io_methods]
980** object returns an integer which is a vector of the these
981** bit values expressing I/O characteristics of the mass storage
982** device that holds the file that the [sqlite3_io_methods]
983** refers to.
984**
985** The SQLITE_IOCAP_ATOMIC property means that all writes of
986** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
987** mean that writes of blocks that are nnn bytes in size and
988** are aligned to an address which is an integer multiple of
989** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
990** that when data is appended to a file, the data is appended
991** first then the size of the file is extended, never the other
992** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
993** information is written to disk in the same order as calls
994** to xWrite().
995*/
996#define SQLITE_IOCAP_ATOMIC          0x00000001
997#define SQLITE_IOCAP_ATOMIC512       0x00000002
998#define SQLITE_IOCAP_ATOMIC1K        0x00000004
999#define SQLITE_IOCAP_ATOMIC2K        0x00000008
1000#define SQLITE_IOCAP_ATOMIC4K        0x00000010
1001#define SQLITE_IOCAP_ATOMIC8K        0x00000020
1002#define SQLITE_IOCAP_ATOMIC16K       0x00000040
1003#define SQLITE_IOCAP_ATOMIC32K       0x00000080
1004#define SQLITE_IOCAP_ATOMIC64K       0x00000100
1005#define SQLITE_IOCAP_SAFE_APPEND     0x00000200
1006#define SQLITE_IOCAP_SEQUENTIAL      0x00000400
1007
1008/*
1009** CAPI3REF: File Locking Levels
1010**
1011** SQLite uses one of these integer values as the second
1012** argument to calls it makes to the xLock() and xUnlock() methods
1013** of an [sqlite3_io_methods] object.
1014*/
1015#define SQLITE_LOCK_NONE          0
1016#define SQLITE_LOCK_SHARED        1
1017#define SQLITE_LOCK_RESERVED      2
1018#define SQLITE_LOCK_PENDING       3
1019#define SQLITE_LOCK_EXCLUSIVE     4
1020
1021/*
1022** CAPI3REF: Synchronization Type Flags
1023**
1024** When SQLite invokes the xSync() method of an
1025** [sqlite3_io_methods] object it uses a combination of
1026** these integer values as the second argument.
1027**
1028** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1029** sync operation only needs to flush data to mass storage.  Inode
1030** information need not be flushed. If the lower four bits of the flag
1031** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1032** If the lower four bits equal SQLITE_SYNC_FULL, that means
1033** to use Mac OS X style fullsync instead of fsync().
1034*/
1035#define SQLITE_SYNC_NORMAL        0x00002
1036#define SQLITE_SYNC_FULL          0x00003
1037#define SQLITE_SYNC_DATAONLY      0x00010
1038
1039/*
1040** CAPI3REF: OS Interface Open File Handle
1041**
1042** An [sqlite3_file] object represents an open file in the
1043** [sqlite3_vfs | OS interface layer].  Individual OS interface
1044** implementations will
1045** want to subclass this object by appending additional fields
1046** for their own use.  The pMethods entry is a pointer to an
1047** [sqlite3_io_methods] object that defines methods for performing
1048** I/O operations on the open file.
1049*/
1050typedef struct sqlite3_file sqlite3_file;
1051struct sqlite3_file {
1052  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1053};
1054
1055/*
1056** CAPI3REF: OS Interface File Virtual Methods Object
1057**
1058** Every file opened by the [sqlite3_vfs] xOpen method populates an
1059** [sqlite3_file] object (or, more commonly, a subclass of the
1060** [sqlite3_file] object) with a pointer to an instance of this object.
1061** This object defines the methods used to perform various operations
1062** against the open file represented by the [sqlite3_file] object.
1063**
1064** If the xOpen method sets the sqlite3_file.pMethods element
1065** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1066** may be invoked even if the xOpen reported that it failed.  The
1067** only way to prevent a call to xClose following a failed xOpen
1068** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
1069**
1070** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1071** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1072** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1073** flag may be ORed in to indicate that only the data of the file
1074** and not its inode needs to be synced.
1075**
1076** The integer values to xLock() and xUnlock() are one of
1077** <ul>
1078** <li> [SQLITE_LOCK_NONE],
1079** <li> [SQLITE_LOCK_SHARED],
1080** <li> [SQLITE_LOCK_RESERVED],
1081** <li> [SQLITE_LOCK_PENDING], or
1082** <li> [SQLITE_LOCK_EXCLUSIVE].
1083** </ul>
1084** xLock() increases the lock. xUnlock() decreases the lock.
1085** The xCheckReservedLock() method checks whether any database connection,
1086** either in this process or in some other process, is holding a RESERVED,
1087** PENDING, or EXCLUSIVE lock on the file.  It returns true
1088** if such a lock exists and false otherwise.
1089**
1090** The xFileControl() method is a generic interface that allows custom
1091** VFS implementations to directly control an open file using the
1092** [sqlite3_file_control()] interface.  The second "op" argument is an
1093** integer opcode.  The third argument is a generic pointer intended to
1094** point to a structure that may contain arguments or space in which to
1095** write return values.  Potential uses for xFileControl() might be
1096** functions to enable blocking locks with timeouts, to change the
1097** locking strategy (for example to use dot-file locks), to inquire
1098** about the status of a lock, or to break stale locks.  The SQLite
1099** core reserves all opcodes less than 100 for its own use.
1100** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1101** Applications that define a custom xFileControl method should use opcodes
1102** greater than 100 to avoid conflicts.
1103**
1104** The xSectorSize() method returns the sector size of the
1105** device that underlies the file.  The sector size is the
1106** minimum write that can be performed without disturbing
1107** other bytes in the file.  The xDeviceCharacteristics()
1108** method returns a bit vector describing behaviors of the
1109** underlying device:
1110**
1111** <ul>
1112** <li> [SQLITE_IOCAP_ATOMIC]
1113** <li> [SQLITE_IOCAP_ATOMIC512]
1114** <li> [SQLITE_IOCAP_ATOMIC1K]
1115** <li> [SQLITE_IOCAP_ATOMIC2K]
1116** <li> [SQLITE_IOCAP_ATOMIC4K]
1117** <li> [SQLITE_IOCAP_ATOMIC8K]
1118** <li> [SQLITE_IOCAP_ATOMIC16K]
1119** <li> [SQLITE_IOCAP_ATOMIC32K]
1120** <li> [SQLITE_IOCAP_ATOMIC64K]
1121** <li> [SQLITE_IOCAP_SAFE_APPEND]
1122** <li> [SQLITE_IOCAP_SEQUENTIAL]
1123** </ul>
1124**
1125** The SQLITE_IOCAP_ATOMIC property means that all writes of
1126** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1127** mean that writes of blocks that are nnn bytes in size and
1128** are aligned to an address which is an integer multiple of
1129** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1130** that when data is appended to a file, the data is appended
1131** first then the size of the file is extended, never the other
1132** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1133** information is written to disk in the same order as calls
1134** to xWrite().
1135**
1136** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1137** in the unread portions of the buffer with zeros.  A VFS that
1138** fails to zero-fill short reads might seem to work.  However,
1139** failure to zero-fill short reads will eventually lead to
1140** database corruption.
1141*/
1142typedef struct sqlite3_io_methods sqlite3_io_methods;
1143struct sqlite3_io_methods {
1144  int iVersion;
1145  int (*xClose)(sqlite3_file*);
1146  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1147  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1148  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1149  int (*xSync)(sqlite3_file*, int flags);
1150  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1151  int (*xLock)(sqlite3_file*, int);
1152  int (*xUnlock)(sqlite3_file*, int);
1153  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1154  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1155  int (*xSectorSize)(sqlite3_file*);
1156  int (*xDeviceCharacteristics)(sqlite3_file*);
1157  /* Additional methods may be added in future releases */
1158};
1159
1160/*
1161** CAPI3REF: Standard File Control Opcodes
1162**
1163** These integer constants are opcodes for the xFileControl method
1164** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1165** interface.
1166**
1167** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1168** opcode causes the xFileControl method to write the current state of
1169** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1170** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1171** into an integer that the pArg argument points to. This capability
1172** is used during testing and only needs to be supported when SQLITE_TEST
1173** is defined.
1174*/
1175#define SQLITE_FCNTL_LOCKSTATE        1
1176#define SQLITE_GET_LOCKPROXYFILE      2
1177#define SQLITE_SET_LOCKPROXYFILE      3
1178#define SQLITE_LAST_ERRNO             4
1179
1180/*
1181** CAPI3REF: Mutex Handle
1182**
1183** The mutex module within SQLite defines [sqlite3_mutex] to be an
1184** abstract type for a mutex object.  The SQLite core never looks
1185** at the internal representation of an [sqlite3_mutex].  It only
1186** deals with pointers to the [sqlite3_mutex] object.
1187**
1188** Mutexes are created using [sqlite3_mutex_alloc()].
1189*/
1190typedef struct sqlite3_mutex sqlite3_mutex;
1191
1192/*
1193** CAPI3REF: OS Interface Object
1194**
1195** An instance of the sqlite3_vfs object defines the interface between
1196** the SQLite core and the underlying operating system.  The "vfs"
1197** in the name of the object stands for "virtual file system".
1198**
1199** The value of the iVersion field is initially 1 but may be larger in
1200** future versions of SQLite.  Additional fields may be appended to this
1201** object when the iVersion value is increased.  Note that the structure
1202** of the sqlite3_vfs object changes in the transaction between
1203** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1204** modified.
1205**
1206** The szOsFile field is the size of the subclassed [sqlite3_file]
1207** structure used by this VFS.  mxPathname is the maximum length of
1208** a pathname in this VFS.
1209**
1210** Registered sqlite3_vfs objects are kept on a linked list formed by
1211** the pNext pointer.  The [sqlite3_vfs_register()]
1212** and [sqlite3_vfs_unregister()] interfaces manage this list
1213** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1214** searches the list.  Neither the application code nor the VFS
1215** implementation should use the pNext pointer.
1216**
1217** The pNext field is the only field in the sqlite3_vfs
1218** structure that SQLite will ever modify.  SQLite will only access
1219** or modify this field while holding a particular static mutex.
1220** The application should never modify anything within the sqlite3_vfs
1221** object once the object has been registered.
1222**
1223** The zName field holds the name of the VFS module.  The name must
1224** be unique across all VFS modules.
1225**
1226** SQLite will guarantee that the zFilename parameter to xOpen
1227** is either a NULL pointer or string obtained
1228** from xFullPathname().  SQLite further guarantees that
1229** the string will be valid and unchanged until xClose() is
1230** called. Because of the previous sentence,
1231** the [sqlite3_file] can safely store a pointer to the
1232** filename if it needs to remember the filename for some reason.
1233** If the zFilename parameter is xOpen is a NULL pointer then xOpen
1234** must invent its own temporary name for the file.  Whenever the
1235** xFilename parameter is NULL it will also be the case that the
1236** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1237**
1238** The flags argument to xOpen() includes all bits set in
1239** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1240** or [sqlite3_open16()] is used, then flags includes at least
1241** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1242** If xOpen() opens a file read-only then it sets *pOutFlags to
1243** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1244**
1245** SQLite will also add one of the following flags to the xOpen()
1246** call, depending on the object being opened:
1247**
1248** <ul>
1249** <li>  [SQLITE_OPEN_MAIN_DB]
1250** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1251** <li>  [SQLITE_OPEN_TEMP_DB]
1252** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1253** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1254** <li>  [SQLITE_OPEN_SUBJOURNAL]
1255** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1256** </ul>
1257**
1258** The file I/O implementation can use the object type flags to
1259** change the way it deals with files.  For example, an application
1260** that does not care about crash recovery or rollback might make
1261** the open of a journal file a no-op.  Writes to this journal would
1262** also be no-ops, and any attempt to read the journal would return
1263** SQLITE_IOERR.  Or the implementation might recognize that a database
1264** file will be doing page-aligned sector reads and writes in a random
1265** order and set up its I/O subsystem accordingly.
1266**
1267** SQLite might also add one of the following flags to the xOpen method:
1268**
1269** <ul>
1270** <li> [SQLITE_OPEN_DELETEONCLOSE]
1271** <li> [SQLITE_OPEN_EXCLUSIVE]
1272** </ul>
1273**
1274** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1275** deleted when it is closed.  The [SQLITE_OPEN_DELETEONCLOSE]
1276** will be set for TEMP  databases, journals and for subjournals.
1277**
1278** The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1279** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1280** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1281** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1282** SQLITE_OPEN_CREATE, is used to indicate that file should always
1283** be created, and that it is an error if it already exists.
1284** It is <i>not</i> used to indicate the file should be opened
1285** for exclusive access.
1286**
1287** At least szOsFile bytes of memory are allocated by SQLite
1288** to hold the  [sqlite3_file] structure passed as the third
1289** argument to xOpen.  The xOpen method does not have to
1290** allocate the structure; it should just fill it in.  Note that
1291** the xOpen method must set the sqlite3_file.pMethods to either
1292** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1293** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1294** element will be valid after xOpen returns regardless of the success
1295** or failure of the xOpen call.
1296**
1297** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1298** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1299** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1300** to test whether a file is at least readable.   The file can be a
1301** directory.
1302**
1303** SQLite will always allocate at least mxPathname+1 bytes for the
1304** output buffer xFullPathname.  The exact size of the output buffer
1305** is also passed as a parameter to both  methods. If the output buffer
1306** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1307** handled as a fatal error by SQLite, vfs implementations should endeavor
1308** to prevent this by setting mxPathname to a sufficiently large value.
1309**
1310** The xRandomness(), xSleep(), and xCurrentTime() interfaces
1311** are not strictly a part of the filesystem, but they are
1312** included in the VFS structure for completeness.
1313** The xRandomness() function attempts to return nBytes bytes
1314** of good-quality randomness into zOut.  The return value is
1315** the actual number of bytes of randomness obtained.
1316** The xSleep() method causes the calling thread to sleep for at
1317** least the number of microseconds given.  The xCurrentTime()
1318** method returns a Julian Day Number for the current date and time.
1319**
1320*/
1321typedef struct sqlite3_vfs sqlite3_vfs;
1322struct sqlite3_vfs {
1323  int iVersion;            /* Structure version number */
1324  int szOsFile;            /* Size of subclassed sqlite3_file */
1325  int mxPathname;          /* Maximum file pathname length */
1326  sqlite3_vfs *pNext;      /* Next registered VFS */
1327  const char *zName;       /* Name of this virtual file system */
1328  void *pAppData;          /* Pointer to application-specific data */
1329  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1330               int flags, int *pOutFlags);
1331  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1332  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1333  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1334  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1335  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1336  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1337  void (*xDlClose)(sqlite3_vfs*, void*);
1338  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1339  int (*xSleep)(sqlite3_vfs*, int microseconds);
1340  int (*xCurrentTime)(sqlite3_vfs*, double*);
1341  int (*xGetLastError)(sqlite3_vfs*, int, char *);
1342  /* New fields may be appended in figure versions.  The iVersion
1343  ** value will increment whenever this happens. */
1344};
1345
1346/*
1347** CAPI3REF: Flags for the xAccess VFS method
1348**
1349** These integer constants can be used as the third parameter to
1350** the xAccess method of an [sqlite3_vfs] object.  They determine
1351** what kind of permissions the xAccess method is looking for.
1352** With SQLITE_ACCESS_EXISTS, the xAccess method
1353** simply checks whether the file exists.
1354** With SQLITE_ACCESS_READWRITE, the xAccess method
1355** checks whether the file is both readable and writable.
1356** With SQLITE_ACCESS_READ, the xAccess method
1357** checks whether the file is readable.
1358*/
1359#define SQLITE_ACCESS_EXISTS    0
1360#define SQLITE_ACCESS_READWRITE 1
1361#define SQLITE_ACCESS_READ      2
1362
1363/*
1364** CAPI3REF: Initialize The SQLite Library
1365**
1366** ^The sqlite3_initialize() routine initializes the
1367** SQLite library.  ^The sqlite3_shutdown() routine
1368** deallocates any resources that were allocated by sqlite3_initialize().
1369** These routines are designed to aid in process initialization and
1370** shutdown on embedded systems.  Workstation applications using
1371** SQLite normally do not need to invoke either of these routines.
1372**
1373** A call to sqlite3_initialize() is an "effective" call if it is
1374** the first time sqlite3_initialize() is invoked during the lifetime of
1375** the process, or if it is the first time sqlite3_initialize() is invoked
1376** following a call to sqlite3_shutdown().  ^(Only an effective call
1377** of sqlite3_initialize() does any initialization.  All other calls
1378** are harmless no-ops.)^
1379**
1380** A call to sqlite3_shutdown() is an "effective" call if it is the first
1381** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1382** an effective call to sqlite3_shutdown() does any deinitialization.
1383** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1384**
1385** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1386** is not.  The sqlite3_shutdown() interface must only be called from a
1387** single thread.  All open [database connections] must be closed and all
1388** other SQLite resources must be deallocated prior to invoking
1389** sqlite3_shutdown().
1390**
1391** Among other things, ^sqlite3_initialize() will invoke
1392** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1393** will invoke sqlite3_os_end().
1394**
1395** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1396** ^If for some reason, sqlite3_initialize() is unable to initialize
1397** the library (perhaps it is unable to allocate a needed resource such
1398** as a mutex) it returns an [error code] other than [SQLITE_OK].
1399**
1400** ^The sqlite3_initialize() routine is called internally by many other
1401** SQLite interfaces so that an application usually does not need to
1402** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1403** calls sqlite3_initialize() so the SQLite library will be automatically
1404** initialized when [sqlite3_open()] is called if it has not be initialized
1405** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1406** compile-time option, then the automatic calls to sqlite3_initialize()
1407** are omitted and the application must call sqlite3_initialize() directly
1408** prior to using any other SQLite interface.  For maximum portability,
1409** it is recommended that applications always invoke sqlite3_initialize()
1410** directly prior to using any other SQLite interface.  Future releases
1411** of SQLite may require this.  In other words, the behavior exhibited
1412** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1413** default behavior in some future release of SQLite.
1414**
1415** The sqlite3_os_init() routine does operating-system specific
1416** initialization of the SQLite library.  The sqlite3_os_end()
1417** routine undoes the effect of sqlite3_os_init().  Typical tasks
1418** performed by these routines include allocation or deallocation
1419** of static resources, initialization of global variables,
1420** setting up a default [sqlite3_vfs] module, or setting up
1421** a default configuration using [sqlite3_config()].
1422**
1423** The application should never invoke either sqlite3_os_init()
1424** or sqlite3_os_end() directly.  The application should only invoke
1425** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1426** interface is called automatically by sqlite3_initialize() and
1427** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1428** implementations for sqlite3_os_init() and sqlite3_os_end()
1429** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1430** When [custom builds | built for other platforms]
1431** (using the [SQLITE_OS_OTHER=1] compile-time
1432** option) the application must supply a suitable implementation for
1433** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1434** implementation of sqlite3_os_init() or sqlite3_os_end()
1435** must return [SQLITE_OK] on success and some other [error code] upon
1436** failure.
1437*/
1438SQLITE_API int sqlite3_initialize(void);
1439SQLITE_API int sqlite3_shutdown(void);
1440SQLITE_API int sqlite3_os_init(void);
1441SQLITE_API int sqlite3_os_end(void);
1442
1443/*
1444** CAPI3REF: Configuring The SQLite Library
1445**
1446** The sqlite3_config() interface is used to make global configuration
1447** changes to SQLite in order to tune SQLite to the specific needs of
1448** the application.  The default configuration is recommended for most
1449** applications and so this routine is usually not necessary.  It is
1450** provided to support rare applications with unusual needs.
1451**
1452** The sqlite3_config() interface is not threadsafe.  The application
1453** must insure that no other SQLite interfaces are invoked by other
1454** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1455** may only be invoked prior to library initialization using
1456** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1457** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1458** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1459** Note, however, that ^sqlite3_config() can be called as part of the
1460** implementation of an application-defined [sqlite3_os_init()].
1461**
1462** The first argument to sqlite3_config() is an integer
1463** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1464** what property of SQLite is to be configured.  Subsequent arguments
1465** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1466** in the first argument.
1467**
1468** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1469** ^If the option is unknown or SQLite is unable to set the option
1470** then this routine returns a non-zero [error code].
1471*/
1472SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_config(int, ...);
1473
1474/*
1475** CAPI3REF: Configure database connections
1476** EXPERIMENTAL
1477**
1478** The sqlite3_db_config() interface is used to make configuration
1479** changes to a [database connection].  The interface is similar to
1480** [sqlite3_config()] except that the changes apply to a single
1481** [database connection] (specified in the first argument).  The
1482** sqlite3_db_config() interface should only be used immediately after
1483** the database connection is created using [sqlite3_open()],
1484** [sqlite3_open16()], or [sqlite3_open_v2()].
1485**
1486** The second argument to sqlite3_db_config(D,V,...)  is the
1487** configuration verb - an integer code that indicates what
1488** aspect of the [database connection] is being configured.
1489** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
1490** New verbs are likely to be added in future releases of SQLite.
1491** Additional arguments depend on the verb.
1492**
1493** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1494** the call is considered successful.
1495*/
1496SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_config(sqlite3*, int op, ...);
1497
1498/*
1499** CAPI3REF: Memory Allocation Routines
1500** EXPERIMENTAL
1501**
1502** An instance of this object defines the interface between SQLite
1503** and low-level memory allocation routines.
1504**
1505** This object is used in only one place in the SQLite interface.
1506** A pointer to an instance of this object is the argument to
1507** [sqlite3_config()] when the configuration option is
1508** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1509** By creating an instance of this object
1510** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1511** during configuration, an application can specify an alternative
1512** memory allocation subsystem for SQLite to use for all of its
1513** dynamic memory needs.
1514**
1515** Note that SQLite comes with several [built-in memory allocators]
1516** that are perfectly adequate for the overwhelming majority of applications
1517** and that this object is only useful to a tiny minority of applications
1518** with specialized memory allocation requirements.  This object is
1519** also used during testing of SQLite in order to specify an alternative
1520** memory allocator that simulates memory out-of-memory conditions in
1521** order to verify that SQLite recovers gracefully from such
1522** conditions.
1523**
1524** The xMalloc and xFree methods must work like the
1525** malloc() and free() functions from the standard C library.
1526** The xRealloc method must work like realloc() from the standard C library
1527** with the exception that if the second argument to xRealloc is zero,
1528** xRealloc must be a no-op - it must not perform any allocation or
1529** deallocation.  ^SQLite guarantees that the second argument to
1530** xRealloc is always a value returned by a prior call to xRoundup.
1531** And so in cases where xRoundup always returns a positive number,
1532** xRealloc can perform exactly as the standard library realloc() and
1533** still be in compliance with this specification.
1534**
1535** xSize should return the allocated size of a memory allocation
1536** previously obtained from xMalloc or xRealloc.  The allocated size
1537** is always at least as big as the requested size but may be larger.
1538**
1539** The xRoundup method returns what would be the allocated size of
1540** a memory allocation given a particular requested size.  Most memory
1541** allocators round up memory allocations at least to the next multiple
1542** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1543** Every memory allocation request coming in through [sqlite3_malloc()]
1544** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
1545** that causes the corresponding memory allocation to fail.
1546**
1547** The xInit method initializes the memory allocator.  (For example,
1548** it might allocate any require mutexes or initialize internal data
1549** structures.  The xShutdown method is invoked (indirectly) by
1550** [sqlite3_shutdown()] and should deallocate any resources acquired
1551** by xInit.  The pAppData pointer is used as the only parameter to
1552** xInit and xShutdown.
1553**
1554** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1555** the xInit method, so the xInit method need not be threadsafe.  The
1556** xShutdown method is only called from [sqlite3_shutdown()] so it does
1557** not need to be threadsafe either.  For all other methods, SQLite
1558** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1559** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1560** it is by default) and so the methods are automatically serialized.
1561** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1562** methods must be threadsafe or else make their own arrangements for
1563** serialization.
1564**
1565** SQLite will never invoke xInit() more than once without an intervening
1566** call to xShutdown().
1567*/
1568typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1569struct sqlite3_mem_methods {
1570  void *(*xMalloc)(int);         /* Memory allocation function */
1571  void (*xFree)(void*);          /* Free a prior allocation */
1572  void *(*xRealloc)(void*,int);  /* Resize an allocation */
1573  int (*xSize)(void*);           /* Return the size of an allocation */
1574  int (*xRoundup)(int);          /* Round up request size to allocation size */
1575  int (*xInit)(void*);           /* Initialize the memory allocator */
1576  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1577  void *pAppData;                /* Argument to xInit() and xShutdown() */
1578};
1579
1580/*
1581** CAPI3REF: Configuration Options
1582** EXPERIMENTAL
1583**
1584** These constants are the available integer configuration options that
1585** can be passed as the first argument to the [sqlite3_config()] interface.
1586**
1587** New configuration options may be added in future releases of SQLite.
1588** Existing configuration options might be discontinued.  Applications
1589** should check the return code from [sqlite3_config()] to make sure that
1590** the call worked.  The [sqlite3_config()] interface will return a
1591** non-zero [error code] if a discontinued or unsupported configuration option
1592** is invoked.
1593**
1594** <dl>
1595** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1596** <dd>There are no arguments to this option.  ^This option sets the
1597** [threading mode] to Single-thread.  In other words, it disables
1598** all mutexing and puts SQLite into a mode where it can only be used
1599** by a single thread.   ^If SQLite is compiled with
1600** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1601** it is not possible to change the [threading mode] from its default
1602** value of Single-thread and so [sqlite3_config()] will return
1603** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1604** configuration option.</dd>
1605**
1606** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1607** <dd>There are no arguments to this option.  ^This option sets the
1608** [threading mode] to Multi-thread.  In other words, it disables
1609** mutexing on [database connection] and [prepared statement] objects.
1610** The application is responsible for serializing access to
1611** [database connections] and [prepared statements].  But other mutexes
1612** are enabled so that SQLite will be safe to use in a multi-threaded
1613** environment as long as no two threads attempt to use the same
1614** [database connection] at the same time.  ^If SQLite is compiled with
1615** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1616** it is not possible to set the Multi-thread [threading mode] and
1617** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1618** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1619**
1620** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1621** <dd>There are no arguments to this option.  ^This option sets the
1622** [threading mode] to Serialized. In other words, this option enables
1623** all mutexes including the recursive
1624** mutexes on [database connection] and [prepared statement] objects.
1625** In this mode (which is the default when SQLite is compiled with
1626** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1627** to [database connections] and [prepared statements] so that the
1628** application is free to use the same [database connection] or the
1629** same [prepared statement] in different threads at the same time.
1630** ^If SQLite is compiled with
1631** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1632** it is not possible to set the Serialized [threading mode] and
1633** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1634** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1635**
1636** <dt>SQLITE_CONFIG_MALLOC</dt>
1637** <dd> ^(This option takes a single argument which is a pointer to an
1638** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1639** alternative low-level memory allocation routines to be used in place of
1640** the memory allocation routines built into SQLite.)^ ^SQLite makes
1641** its own private copy of the content of the [sqlite3_mem_methods] structure
1642** before the [sqlite3_config()] call returns.</dd>
1643**
1644** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1645** <dd> ^(This option takes a single argument which is a pointer to an
1646** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1647** structure is filled with the currently defined memory allocation routines.)^
1648** This option can be used to overload the default memory allocation
1649** routines with a wrapper that simulations memory allocation failure or
1650** tracks memory usage, for example. </dd>
1651**
1652** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1653** <dd> ^This option takes single argument of type int, interpreted as a
1654** boolean, which enables or disables the collection of memory allocation
1655** statistics. ^(When memory allocation statistics are disabled, the
1656** following SQLite interfaces become non-operational:
1657**   <ul>
1658**   <li> [sqlite3_memory_used()]
1659**   <li> [sqlite3_memory_highwater()]
1660**   <li> [sqlite3_soft_heap_limit()]
1661**   <li> [sqlite3_status()]
1662**   </ul>)^
1663** ^Memory allocation statistics are enabled by default unless SQLite is
1664** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1665** allocation statistics are disabled by default.
1666** </dd>
1667**
1668** <dt>SQLITE_CONFIG_SCRATCH</dt>
1669** <dd> ^This option specifies a static memory buffer that SQLite can use for
1670** scratch memory.  There are three arguments:  A pointer an 8-byte
1671** aligned memory buffer from which the scrach allocations will be
1672** drawn, the size of each scratch allocation (sz),
1673** and the maximum number of scratch allocations (N).  The sz
1674** argument must be a multiple of 16. The sz parameter should be a few bytes
1675** larger than the actual scratch space required due to internal overhead.
1676** The first argument must be a pointer to an 8-byte aligned buffer
1677** of at least sz*N bytes of memory.
1678** ^SQLite will use no more than one scratch buffer per thread.  So
1679** N should be set to the expected maximum number of threads.  ^SQLite will
1680** never require a scratch buffer that is more than 6 times the database
1681** page size. ^If SQLite needs needs additional scratch memory beyond
1682** what is provided by this configuration option, then
1683** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1684**
1685** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1686** <dd> ^This option specifies a static memory buffer that SQLite can use for
1687** the database page cache with the default page cache implemenation.
1688** This configuration should not be used if an application-define page
1689** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1690** There are three arguments to this option: A pointer to 8-byte aligned
1691** memory, the size of each page buffer (sz), and the number of pages (N).
1692** The sz argument should be the size of the largest database page
1693** (a power of two between 512 and 32768) plus a little extra for each
1694** page header.  ^The page header size is 20 to 40 bytes depending on
1695** the host architecture.  ^It is harmless, apart from the wasted memory,
1696** to make sz a little too large.  The first
1697** argument should point to an allocation of at least sz*N bytes of memory.
1698** ^SQLite will use the memory provided by the first argument to satisfy its
1699** memory needs for the first N pages that it adds to cache.  ^If additional
1700** page cache memory is needed beyond what is provided by this option, then
1701** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1702** ^The implementation might use one or more of the N buffers to hold
1703** memory accounting information. The pointer in the first argument must
1704** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1705** will be undefined.</dd>
1706**
1707** <dt>SQLITE_CONFIG_HEAP</dt>
1708** <dd> ^This option specifies a static memory buffer that SQLite will use
1709** for all of its dynamic memory allocation needs beyond those provided
1710** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1711** There are three arguments: An 8-byte aligned pointer to the memory,
1712** the number of bytes in the memory buffer, and the minimum allocation size.
1713** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1714** to using its default memory allocator (the system malloc() implementation),
1715** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1716** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1717** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1718** allocator is engaged to handle all of SQLites memory allocation needs.
1719** The first pointer (the memory pointer) must be aligned to an 8-byte
1720** boundary or subsequent behavior of SQLite will be undefined.</dd>
1721**
1722** <dt>SQLITE_CONFIG_MUTEX</dt>
1723** <dd> ^(This option takes a single argument which is a pointer to an
1724** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1725** alternative low-level mutex routines to be used in place
1726** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1727** content of the [sqlite3_mutex_methods] structure before the call to
1728** [sqlite3_config()] returns. ^If SQLite is compiled with
1729** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1730** the entire mutexing subsystem is omitted from the build and hence calls to
1731** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1732** return [SQLITE_ERROR].</dd>
1733**
1734** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1735** <dd> ^(This option takes a single argument which is a pointer to an
1736** instance of the [sqlite3_mutex_methods] structure.  The
1737** [sqlite3_mutex_methods]
1738** structure is filled with the currently defined mutex routines.)^
1739** This option can be used to overload the default mutex allocation
1740** routines with a wrapper used to track mutex usage for performance
1741** profiling or testing, for example.   ^If SQLite is compiled with
1742** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1743** the entire mutexing subsystem is omitted from the build and hence calls to
1744** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1745** return [SQLITE_ERROR].</dd>
1746**
1747** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1748** <dd> ^(This option takes two arguments that determine the default
1749** memory allocation for the lookaside memory allocator on each
1750** [database connection].  The first argument is the
1751** size of each lookaside buffer slot and the second is the number of
1752** slots allocated to each database connection.)^  ^(This option sets the
1753** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1754** verb to [sqlite3_db_config()] can be used to change the lookaside
1755** configuration on individual connections.)^ </dd>
1756**
1757** <dt>SQLITE_CONFIG_PCACHE</dt>
1758** <dd> ^(This option takes a single argument which is a pointer to
1759** an [sqlite3_pcache_methods] object.  This object specifies the interface
1760** to a custom page cache implementation.)^  ^SQLite makes a copy of the
1761** object and uses it for page cache memory allocations.</dd>
1762**
1763** <dt>SQLITE_CONFIG_GETPCACHE</dt>
1764** <dd> ^(This option takes a single argument which is a pointer to an
1765** [sqlite3_pcache_methods] object.  SQLite copies of the current
1766** page cache implementation into that object.)^ </dd>
1767**
1768** </dl>
1769*/
1770#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1771#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1772#define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1773#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1774#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1775#define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1776#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1777#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1778#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1779#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1780#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1781/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
1782#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1783#define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
1784#define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
1785#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
1786
1787/*
1788** CAPI3REF: Configuration Options
1789** EXPERIMENTAL
1790**
1791** These constants are the available integer configuration options that
1792** can be passed as the second argument to the [sqlite3_db_config()] interface.
1793**
1794** New configuration options may be added in future releases of SQLite.
1795** Existing configuration options might be discontinued.  Applications
1796** should check the return code from [sqlite3_db_config()] to make sure that
1797** the call worked.  ^The [sqlite3_db_config()] interface will return a
1798** non-zero [error code] if a discontinued or unsupported configuration option
1799** is invoked.
1800**
1801** <dl>
1802** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
1803** <dd> ^This option takes three additional arguments that determine the
1804** [lookaside memory allocator] configuration for the [database connection].
1805** ^The first argument (the third parameter to [sqlite3_db_config()] is a
1806** pointer to an memory buffer to use for lookaside memory.
1807** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
1808** may be NULL in which case SQLite will allocate the
1809** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
1810** size of each lookaside buffer slot.  ^The third argument is the number of
1811** slots.  The size of the buffer in the first argument must be greater than
1812** or equal to the product of the second and third arguments.  The buffer
1813** must be aligned to an 8-byte boundary.  ^If the second argument to
1814** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
1815** rounded down to the next smaller
1816** multiple of 8.  See also: [SQLITE_CONFIG_LOOKASIDE]</dd>
1817**
1818** </dl>
1819*/
1820#define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */
1821
1822
1823/*
1824** CAPI3REF: Enable Or Disable Extended Result Codes
1825**
1826** ^The sqlite3_extended_result_codes() routine enables or disables the
1827** [extended result codes] feature of SQLite. ^The extended result
1828** codes are disabled by default for historical compatibility.
1829*/
1830SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1831
1832/*
1833** CAPI3REF: Last Insert Rowid
1834**
1835** ^Each entry in an SQLite table has a unique 64-bit signed
1836** integer key called the [ROWID | "rowid"]. ^The rowid is always available
1837** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1838** names are not also used by explicitly declared columns. ^If
1839** the table has a column of type [INTEGER PRIMARY KEY] then that column
1840** is another alias for the rowid.
1841**
1842** ^This routine returns the [rowid] of the most recent
1843** successful [INSERT] into the database from the [database connection]
1844** in the first argument.  ^If no successful [INSERT]s
1845** have ever occurred on that database connection, zero is returned.
1846**
1847** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
1848** row is returned by this routine as long as the trigger is running.
1849** But once the trigger terminates, the value returned by this routine
1850** reverts to the last value inserted before the trigger fired.)^
1851**
1852** ^An [INSERT] that fails due to a constraint violation is not a
1853** successful [INSERT] and does not change the value returned by this
1854** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
1855** and INSERT OR ABORT make no changes to the return value of this
1856** routine when their insertion fails.  ^(When INSERT OR REPLACE
1857** encounters a constraint violation, it does not fail.  The
1858** INSERT continues to completion after deleting rows that caused
1859** the constraint problem so INSERT OR REPLACE will always change
1860** the return value of this interface.)^
1861**
1862** ^For the purposes of this routine, an [INSERT] is considered to
1863** be successful even if it is subsequently rolled back.
1864**
1865** This function is accessible to SQL statements via the
1866** [last_insert_rowid() SQL function].
1867**
1868** If a separate thread performs a new [INSERT] on the same
1869** database connection while the [sqlite3_last_insert_rowid()]
1870** function is running and thus changes the last insert [rowid],
1871** then the value returned by [sqlite3_last_insert_rowid()] is
1872** unpredictable and might not equal either the old or the new
1873** last insert [rowid].
1874*/
1875SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
1876
1877/*
1878** CAPI3REF: Count The Number Of Rows Modified
1879**
1880** ^This function returns the number of database rows that were changed
1881** or inserted or deleted by the most recently completed SQL statement
1882** on the [database connection] specified by the first parameter.
1883** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
1884** or [DELETE] statement are counted.  Auxiliary changes caused by
1885** triggers or [foreign key actions] are not counted.)^ Use the
1886** [sqlite3_total_changes()] function to find the total number of changes
1887** including changes caused by triggers and foreign key actions.
1888**
1889** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
1890** are not counted.  Only real table changes are counted.
1891**
1892** ^(A "row change" is a change to a single row of a single table
1893** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
1894** are changed as side effects of [REPLACE] constraint resolution,
1895** rollback, ABORT processing, [DROP TABLE], or by any other
1896** mechanisms do not count as direct row changes.)^
1897**
1898** A "trigger context" is a scope of execution that begins and
1899** ends with the script of a [CREATE TRIGGER | trigger].
1900** Most SQL statements are
1901** evaluated outside of any trigger.  This is the "top level"
1902** trigger context.  If a trigger fires from the top level, a
1903** new trigger context is entered for the duration of that one
1904** trigger.  Subtriggers create subcontexts for their duration.
1905**
1906** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
1907** not create a new trigger context.
1908**
1909** ^This function returns the number of direct row changes in the
1910** most recent INSERT, UPDATE, or DELETE statement within the same
1911** trigger context.
1912**
1913** ^Thus, when called from the top level, this function returns the
1914** number of changes in the most recent INSERT, UPDATE, or DELETE
1915** that also occurred at the top level.  ^(Within the body of a trigger,
1916** the sqlite3_changes() interface can be called to find the number of
1917** changes in the most recently completed INSERT, UPDATE, or DELETE
1918** statement within the body of the same trigger.
1919** However, the number returned does not include changes
1920** caused by subtriggers since those have their own context.)^
1921**
1922** See also the [sqlite3_total_changes()] interface, the
1923** [count_changes pragma], and the [changes() SQL function].
1924**
1925** If a separate thread makes changes on the same database connection
1926** while [sqlite3_changes()] is running then the value returned
1927** is unpredictable and not meaningful.
1928*/
1929SQLITE_API int sqlite3_changes(sqlite3*);
1930
1931/*
1932** CAPI3REF: Total Number Of Rows Modified
1933**
1934** ^This function returns the number of row changes caused by [INSERT],
1935** [UPDATE] or [DELETE] statements since the [database connection] was opened.
1936** ^(The count returned by sqlite3_total_changes() includes all changes
1937** from all [CREATE TRIGGER | trigger] contexts and changes made by
1938** [foreign key actions]. However,
1939** the count does not include changes used to implement [REPLACE] constraints,
1940** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
1941** count does not include rows of views that fire an [INSTEAD OF trigger],
1942** though if the INSTEAD OF trigger makes changes of its own, those changes
1943** are counted.)^
1944** ^The sqlite3_total_changes() function counts the changes as soon as
1945** the statement that makes them is completed (when the statement handle
1946** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
1947**
1948** See also the [sqlite3_changes()] interface, the
1949** [count_changes pragma], and the [total_changes() SQL function].
1950**
1951** If a separate thread makes changes on the same database connection
1952** while [sqlite3_total_changes()] is running then the value
1953** returned is unpredictable and not meaningful.
1954*/
1955SQLITE_API int sqlite3_total_changes(sqlite3*);
1956
1957/*
1958** CAPI3REF: Interrupt A Long-Running Query
1959**
1960** ^This function causes any pending database operation to abort and
1961** return at its earliest opportunity. This routine is typically
1962** called in response to a user action such as pressing "Cancel"
1963** or Ctrl-C where the user wants a long query operation to halt
1964** immediately.
1965**
1966** ^It is safe to call this routine from a thread different from the
1967** thread that is currently running the database operation.  But it
1968** is not safe to call this routine with a [database connection] that
1969** is closed or might close before sqlite3_interrupt() returns.
1970**
1971** ^If an SQL operation is very nearly finished at the time when
1972** sqlite3_interrupt() is called, then it might not have an opportunity
1973** to be interrupted and might continue to completion.
1974**
1975** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
1976** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
1977** that is inside an explicit transaction, then the entire transaction
1978** will be rolled back automatically.
1979**
1980** ^The sqlite3_interrupt(D) call is in effect until all currently running
1981** SQL statements on [database connection] D complete.  ^Any new SQL statements
1982** that are started after the sqlite3_interrupt() call and before the
1983** running statements reaches zero are interrupted as if they had been
1984** running prior to the sqlite3_interrupt() call.  ^New SQL statements
1985** that are started after the running statement count reaches zero are
1986** not effected by the sqlite3_interrupt().
1987** ^A call to sqlite3_interrupt(D) that occurs when there are no running
1988** SQL statements is a no-op and has no effect on SQL statements
1989** that are started after the sqlite3_interrupt() call returns.
1990**
1991** If the database connection closes while [sqlite3_interrupt()]
1992** is running then bad things will likely happen.
1993*/
1994SQLITE_API void sqlite3_interrupt(sqlite3*);
1995
1996/*
1997** CAPI3REF: Determine If An SQL Statement Is Complete
1998**
1999** These routines are useful during command-line input to determine if the
2000** currently entered text seems to form a complete SQL statement or
2001** if additional input is needed before sending the text into
2002** SQLite for parsing.  ^These routines return 1 if the input string
2003** appears to be a complete SQL statement.  ^A statement is judged to be
2004** complete if it ends with a semicolon token and is not a prefix of a
2005** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2006** string literals or quoted identifier names or comments are not
2007** independent tokens (they are part of the token in which they are
2008** embedded) and thus do not count as a statement terminator.  ^Whitespace
2009** and comments that follow the final semicolon are ignored.
2010**
2011** ^These routines return 0 if the statement is incomplete.  ^If a
2012** memory allocation fails, then SQLITE_NOMEM is returned.
2013**
2014** ^These routines do not parse the SQL statements thus
2015** will not detect syntactically incorrect SQL.
2016**
2017** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2018** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2019** automatically by sqlite3_complete16().  If that initialization fails,
2020** then the return value from sqlite3_complete16() will be non-zero
2021** regardless of whether or not the input SQL is complete.)^
2022**
2023** The input to [sqlite3_complete()] must be a zero-terminated
2024** UTF-8 string.
2025**
2026** The input to [sqlite3_complete16()] must be a zero-terminated
2027** UTF-16 string in native byte order.
2028*/
2029SQLITE_API int sqlite3_complete(const char *sql);
2030SQLITE_API int sqlite3_complete16(const void *sql);
2031
2032/*
2033** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2034**
2035** ^This routine sets a callback function that might be invoked whenever
2036** an attempt is made to open a database table that another thread
2037** or process has locked.
2038**
2039** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2040** is returned immediately upon encountering the lock.  ^If the busy callback
2041** is not NULL, then the callback might be invoked with two arguments.
2042**
2043** ^The first argument to the busy handler is a copy of the void* pointer which
2044** is the third argument to sqlite3_busy_handler().  ^The second argument to
2045** the busy handler callback is the number of times that the busy handler has
2046** been invoked for this locking event.  ^If the
2047** busy callback returns 0, then no additional attempts are made to
2048** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2049** ^If the callback returns non-zero, then another attempt
2050** is made to open the database for reading and the cycle repeats.
2051**
2052** The presence of a busy handler does not guarantee that it will be invoked
2053** when there is lock contention. ^If SQLite determines that invoking the busy
2054** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2055** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2056** Consider a scenario where one process is holding a read lock that
2057** it is trying to promote to a reserved lock and
2058** a second process is holding a reserved lock that it is trying
2059** to promote to an exclusive lock.  The first process cannot proceed
2060** because it is blocked by the second and the second process cannot
2061** proceed because it is blocked by the first.  If both processes
2062** invoke the busy handlers, neither will make any progress.  Therefore,
2063** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2064** will induce the first process to release its read lock and allow
2065** the second process to proceed.
2066**
2067** ^The default busy callback is NULL.
2068**
2069** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2070** when SQLite is in the middle of a large transaction where all the
2071** changes will not fit into the in-memory cache.  SQLite will
2072** already hold a RESERVED lock on the database file, but it needs
2073** to promote this lock to EXCLUSIVE so that it can spill cache
2074** pages into the database file without harm to concurrent
2075** readers.  ^If it is unable to promote the lock, then the in-memory
2076** cache will be left in an inconsistent state and so the error
2077** code is promoted from the relatively benign [SQLITE_BUSY] to
2078** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2079** forces an automatic rollback of the changes.  See the
2080** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2081** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2082** this is important.
2083**
2084** ^(There can only be a single busy handler defined for each
2085** [database connection].  Setting a new busy handler clears any
2086** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2087** will also set or clear the busy handler.
2088**
2089** The busy callback should not take any actions which modify the
2090** database connection that invoked the busy handler.  Any such actions
2091** result in undefined behavior.
2092**
2093** A busy handler must not close the database connection
2094** or [prepared statement] that invoked the busy handler.
2095*/
2096SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2097
2098/*
2099** CAPI3REF: Set A Busy Timeout
2100**
2101** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2102** for a specified amount of time when a table is locked.  ^The handler
2103** will sleep multiple times until at least "ms" milliseconds of sleeping
2104** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2105** the handler returns 0 which causes [sqlite3_step()] to return
2106** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2107**
2108** ^Calling this routine with an argument less than or equal to zero
2109** turns off all busy handlers.
2110**
2111** ^(There can only be a single busy handler for a particular
2112** [database connection] any any given moment.  If another busy handler
2113** was defined  (using [sqlite3_busy_handler()]) prior to calling
2114** this routine, that other busy handler is cleared.)^
2115*/
2116SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2117
2118/*
2119** CAPI3REF: Convenience Routines For Running Queries
2120**
2121** Definition: A <b>result table</b> is memory data structure created by the
2122** [sqlite3_get_table()] interface.  A result table records the
2123** complete query results from one or more queries.
2124**
2125** The table conceptually has a number of rows and columns.  But
2126** these numbers are not part of the result table itself.  These
2127** numbers are obtained separately.  Let N be the number of rows
2128** and M be the number of columns.
2129**
2130** A result table is an array of pointers to zero-terminated UTF-8 strings.
2131** There are (N+1)*M elements in the array.  The first M pointers point
2132** to zero-terminated strings that  contain the names of the columns.
2133** The remaining entries all point to query results.  NULL values result
2134** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2135** string representation as returned by [sqlite3_column_text()].
2136**
2137** A result table might consist of one or more memory allocations.
2138** It is not safe to pass a result table directly to [sqlite3_free()].
2139** A result table should be deallocated using [sqlite3_free_table()].
2140**
2141** As an example of the result table format, suppose a query result
2142** is as follows:
2143**
2144** <blockquote><pre>
2145**        Name        | Age
2146**        -----------------------
2147**        Alice       | 43
2148**        Bob         | 28
2149**        Cindy       | 21
2150** </pre></blockquote>
2151**
2152** There are two column (M==2) and three rows (N==3).  Thus the
2153** result table has 8 entries.  Suppose the result table is stored
2154** in an array names azResult.  Then azResult holds this content:
2155**
2156** <blockquote><pre>
2157**        azResult&#91;0] = "Name";
2158**        azResult&#91;1] = "Age";
2159**        azResult&#91;2] = "Alice";
2160**        azResult&#91;3] = "43";
2161**        azResult&#91;4] = "Bob";
2162**        azResult&#91;5] = "28";
2163**        azResult&#91;6] = "Cindy";
2164**        azResult&#91;7] = "21";
2165** </pre></blockquote>
2166**
2167** ^The sqlite3_get_table() function evaluates one or more
2168** semicolon-separated SQL statements in the zero-terminated UTF-8
2169** string of its 2nd parameter and returns a result table to the
2170** pointer given in its 3rd parameter.
2171**
2172** After the application has finished with the result from sqlite3_get_table(),
2173** it should pass the result table pointer to sqlite3_free_table() in order to
2174** release the memory that was malloced.  Because of the way the
2175** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2176** function must not try to call [sqlite3_free()] directly.  Only
2177** [sqlite3_free_table()] is able to release the memory properly and safely.
2178**
2179** ^(The sqlite3_get_table() interface is implemented as a wrapper around
2180** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2181** to any internal data structures of SQLite.  It uses only the public
2182** interface defined here.  As a consequence, errors that occur in the
2183** wrapper layer outside of the internal [sqlite3_exec()] call are not
2184** reflected in subsequent calls to [sqlite3_errcode()] or
2185** [sqlite3_errmsg()].)^
2186*/
2187SQLITE_API int sqlite3_get_table(
2188  sqlite3 *db,          /* An open database */
2189  const char *zSql,     /* SQL to be evaluated */
2190  char ***pazResult,    /* Results of the query */
2191  int *pnRow,           /* Number of result rows written here */
2192  int *pnColumn,        /* Number of result columns written here */
2193  char **pzErrmsg       /* Error msg written here */
2194);
2195SQLITE_API void sqlite3_free_table(char **result);
2196
2197/*
2198** CAPI3REF: Formatted String Printing Functions
2199**
2200** These routines are work-alikes of the "printf()" family of functions
2201** from the standard C library.
2202**
2203** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2204** results into memory obtained from [sqlite3_malloc()].
2205** The strings returned by these two routines should be
2206** released by [sqlite3_free()].  ^Both routines return a
2207** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2208** memory to hold the resulting string.
2209**
2210** ^(In sqlite3_snprintf() routine is similar to "snprintf()" from
2211** the standard C library.  The result is written into the
2212** buffer supplied as the second parameter whose size is given by
2213** the first parameter. Note that the order of the
2214** first two parameters is reversed from snprintf().)^  This is an
2215** historical accident that cannot be fixed without breaking
2216** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2217** returns a pointer to its buffer instead of the number of
2218** characters actually written into the buffer.)^  We admit that
2219** the number of characters written would be a more useful return
2220** value but we cannot change the implementation of sqlite3_snprintf()
2221** now without breaking compatibility.
2222**
2223** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2224** guarantees that the buffer is always zero-terminated.  ^The first
2225** parameter "n" is the total size of the buffer, including space for
2226** the zero terminator.  So the longest string that can be completely
2227** written will be n-1 characters.
2228**
2229** These routines all implement some additional formatting
2230** options that are useful for constructing SQL statements.
2231** All of the usual printf() formatting options apply.  In addition, there
2232** is are "%q", "%Q", and "%z" options.
2233**
2234** ^(The %q option works like %s in that it substitutes a null-terminated
2235** string from the argument list.  But %q also doubles every '\'' character.
2236** %q is designed for use inside a string literal.)^  By doubling each '\''
2237** character it escapes that character and allows it to be inserted into
2238** the string.
2239**
2240** For example, assume the string variable zText contains text as follows:
2241**
2242** <blockquote><pre>
2243**  char *zText = "It's a happy day!";
2244** </pre></blockquote>
2245**
2246** One can use this text in an SQL statement as follows:
2247**
2248** <blockquote><pre>
2249**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2250**  sqlite3_exec(db, zSQL, 0, 0, 0);
2251**  sqlite3_free(zSQL);
2252** </pre></blockquote>
2253**
2254** Because the %q format string is used, the '\'' character in zText
2255** is escaped and the SQL generated is as follows:
2256**
2257** <blockquote><pre>
2258**  INSERT INTO table1 VALUES('It''s a happy day!')
2259** </pre></blockquote>
2260**
2261** This is correct.  Had we used %s instead of %q, the generated SQL
2262** would have looked like this:
2263**
2264** <blockquote><pre>
2265**  INSERT INTO table1 VALUES('It's a happy day!');
2266** </pre></blockquote>
2267**
2268** This second example is an SQL syntax error.  As a general rule you should
2269** always use %q instead of %s when inserting text into a string literal.
2270**
2271** ^(The %Q option works like %q except it also adds single quotes around
2272** the outside of the total string.  Additionally, if the parameter in the
2273** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2274** single quotes).)^  So, for example, one could say:
2275**
2276** <blockquote><pre>
2277**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2278**  sqlite3_exec(db, zSQL, 0, 0, 0);
2279**  sqlite3_free(zSQL);
2280** </pre></blockquote>
2281**
2282** The code above will render a correct SQL statement in the zSQL
2283** variable even if the zText variable is a NULL pointer.
2284**
2285** ^(The "%z" formatting option works like "%s" but with the
2286** addition that after the string has been read and copied into
2287** the result, [sqlite3_free()] is called on the input string.)^
2288*/
2289SQLITE_API char *sqlite3_mprintf(const char*,...);
2290SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2291SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2292
2293/*
2294** CAPI3REF: Memory Allocation Subsystem
2295**
2296** The SQLite core uses these three routines for all of its own
2297** internal memory allocation needs. "Core" in the previous sentence
2298** does not include operating-system specific VFS implementation.  The
2299** Windows VFS uses native malloc() and free() for some operations.
2300**
2301** ^The sqlite3_malloc() routine returns a pointer to a block
2302** of memory at least N bytes in length, where N is the parameter.
2303** ^If sqlite3_malloc() is unable to obtain sufficient free
2304** memory, it returns a NULL pointer.  ^If the parameter N to
2305** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2306** a NULL pointer.
2307**
2308** ^Calling sqlite3_free() with a pointer previously returned
2309** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2310** that it might be reused.  ^The sqlite3_free() routine is
2311** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2312** to sqlite3_free() is harmless.  After being freed, memory
2313** should neither be read nor written.  Even reading previously freed
2314** memory might result in a segmentation fault or other severe error.
2315** Memory corruption, a segmentation fault, or other severe error
2316** might result if sqlite3_free() is called with a non-NULL pointer that
2317** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2318**
2319** ^(The sqlite3_realloc() interface attempts to resize a
2320** prior memory allocation to be at least N bytes, where N is the
2321** second parameter.  The memory allocation to be resized is the first
2322** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2323** is a NULL pointer then its behavior is identical to calling
2324** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2325** ^If the second parameter to sqlite3_realloc() is zero or
2326** negative then the behavior is exactly the same as calling
2327** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2328** ^sqlite3_realloc() returns a pointer to a memory allocation
2329** of at least N bytes in size or NULL if sufficient memory is unavailable.
2330** ^If M is the size of the prior allocation, then min(N,M) bytes
2331** of the prior allocation are copied into the beginning of buffer returned
2332** by sqlite3_realloc() and the prior allocation is freed.
2333** ^If sqlite3_realloc() returns NULL, then the prior allocation
2334** is not freed.
2335**
2336** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2337** is always aligned to at least an 8 byte boundary.
2338**
2339** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2340** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2341** implementation of these routines to be omitted.  That capability
2342** is no longer provided.  Only built-in memory allocators can be used.
2343**
2344** The Windows OS interface layer calls
2345** the system malloc() and free() directly when converting
2346** filenames between the UTF-8 encoding used by SQLite
2347** and whatever filename encoding is used by the particular Windows
2348** installation.  Memory allocation errors are detected, but
2349** they are reported back as [SQLITE_CANTOPEN] or
2350** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2351**
2352** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2353** must be either NULL or else pointers obtained from a prior
2354** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2355** not yet been released.
2356**
2357** The application must not read or write any part of
2358** a block of memory after it has been released using
2359** [sqlite3_free()] or [sqlite3_realloc()].
2360*/
2361SQLITE_API void *sqlite3_malloc(int);
2362SQLITE_API void *sqlite3_realloc(void*, int);
2363SQLITE_API void sqlite3_free(void*);
2364
2365/*
2366** CAPI3REF: Memory Allocator Statistics
2367**
2368** SQLite provides these two interfaces for reporting on the status
2369** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2370** routines, which form the built-in memory allocation subsystem.
2371**
2372** ^The [sqlite3_memory_used()] routine returns the number of bytes
2373** of memory currently outstanding (malloced but not freed).
2374** ^The [sqlite3_memory_highwater()] routine returns the maximum
2375** value of [sqlite3_memory_used()] since the high-water mark
2376** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2377** [sqlite3_memory_highwater()] include any overhead
2378** added by SQLite in its implementation of [sqlite3_malloc()],
2379** but not overhead added by the any underlying system library
2380** routines that [sqlite3_malloc()] may call.
2381**
2382** ^The memory high-water mark is reset to the current value of
2383** [sqlite3_memory_used()] if and only if the parameter to
2384** [sqlite3_memory_highwater()] is true.  ^The value returned
2385** by [sqlite3_memory_highwater(1)] is the high-water mark
2386** prior to the reset.
2387*/
2388SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2389SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2390
2391/*
2392** CAPI3REF: Pseudo-Random Number Generator
2393**
2394** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2395** select random [ROWID | ROWIDs] when inserting new records into a table that
2396** already uses the largest possible [ROWID].  The PRNG is also used for
2397** the build-in random() and randomblob() SQL functions.  This interface allows
2398** applications to access the same PRNG for other purposes.
2399**
2400** ^A call to this routine stores N bytes of randomness into buffer P.
2401**
2402** ^The first time this routine is invoked (either internally or by
2403** the application) the PRNG is seeded using randomness obtained
2404** from the xRandomness method of the default [sqlite3_vfs] object.
2405** ^On all subsequent invocations, the pseudo-randomness is generated
2406** internally and without recourse to the [sqlite3_vfs] xRandomness
2407** method.
2408*/
2409SQLITE_API void sqlite3_randomness(int N, void *P);
2410
2411/*
2412** CAPI3REF: Compile-Time Authorization Callbacks
2413**
2414** ^This routine registers a authorizer callback with a particular
2415** [database connection], supplied in the first argument.
2416** ^The authorizer callback is invoked as SQL statements are being compiled
2417** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2418** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2419** points during the compilation process, as logic is being created
2420** to perform various actions, the authorizer callback is invoked to
2421** see if those actions are allowed.  ^The authorizer callback should
2422** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2423** specific action but allow the SQL statement to continue to be
2424** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2425** rejected with an error.  ^If the authorizer callback returns
2426** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2427** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2428** the authorizer will fail with an error message.
2429**
2430** When the callback returns [SQLITE_OK], that means the operation
2431** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2432** [sqlite3_prepare_v2()] or equivalent call that triggered the
2433** authorizer will fail with an error message explaining that
2434** access is denied.
2435**
2436** ^The first parameter to the authorizer callback is a copy of the third
2437** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2438** to the callback is an integer [SQLITE_COPY | action code] that specifies
2439** the particular action to be authorized. ^The third through sixth parameters
2440** to the callback are zero-terminated strings that contain additional
2441** details about the action to be authorized.
2442**
2443** ^If the action code is [SQLITE_READ]
2444** and the callback returns [SQLITE_IGNORE] then the
2445** [prepared statement] statement is constructed to substitute
2446** a NULL value in place of the table column that would have
2447** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2448** return can be used to deny an untrusted user access to individual
2449** columns of a table.
2450** ^If the action code is [SQLITE_DELETE] and the callback returns
2451** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2452** [truncate optimization] is disabled and all rows are deleted individually.
2453**
2454** An authorizer is used when [sqlite3_prepare | preparing]
2455** SQL statements from an untrusted source, to ensure that the SQL statements
2456** do not try to access data they are not allowed to see, or that they do not
2457** try to execute malicious statements that damage the database.  For
2458** example, an application may allow a user to enter arbitrary
2459** SQL queries for evaluation by a database.  But the application does
2460** not want the user to be able to make arbitrary changes to the
2461** database.  An authorizer could then be put in place while the
2462** user-entered SQL is being [sqlite3_prepare | prepared] that
2463** disallows everything except [SELECT] statements.
2464**
2465** Applications that need to process SQL from untrusted sources
2466** might also consider lowering resource limits using [sqlite3_limit()]
2467** and limiting database size using the [max_page_count] [PRAGMA]
2468** in addition to using an authorizer.
2469**
2470** ^(Only a single authorizer can be in place on a database connection
2471** at a time.  Each call to sqlite3_set_authorizer overrides the
2472** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2473** The authorizer is disabled by default.
2474**
2475** The authorizer callback must not do anything that will modify
2476** the database connection that invoked the authorizer callback.
2477** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2478** database connections for the meaning of "modify" in this paragraph.
2479**
2480** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2481** statement might be re-prepared during [sqlite3_step()] due to a
2482** schema change.  Hence, the application should ensure that the
2483** correct authorizer callback remains in place during the [sqlite3_step()].
2484**
2485** ^Note that the authorizer callback is invoked only during
2486** [sqlite3_prepare()] or its variants.  Authorization is not
2487** performed during statement evaluation in [sqlite3_step()], unless
2488** as stated in the previous paragraph, sqlite3_step() invokes
2489** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2490*/
2491SQLITE_API int sqlite3_set_authorizer(
2492  sqlite3*,
2493  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2494  void *pUserData
2495);
2496
2497/*
2498** CAPI3REF: Authorizer Return Codes
2499**
2500** The [sqlite3_set_authorizer | authorizer callback function] must
2501** return either [SQLITE_OK] or one of these two constants in order
2502** to signal SQLite whether or not the action is permitted.  See the
2503** [sqlite3_set_authorizer | authorizer documentation] for additional
2504** information.
2505*/
2506#define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2507#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2508
2509/*
2510** CAPI3REF: Authorizer Action Codes
2511**
2512** The [sqlite3_set_authorizer()] interface registers a callback function
2513** that is invoked to authorize certain SQL statement actions.  The
2514** second parameter to the callback is an integer code that specifies
2515** what action is being authorized.  These are the integer action codes that
2516** the authorizer callback may be passed.
2517**
2518** These action code values signify what kind of operation is to be
2519** authorized.  The 3rd and 4th parameters to the authorization
2520** callback function will be parameters or NULL depending on which of these
2521** codes is used as the second parameter.  ^(The 5th parameter to the
2522** authorizer callback is the name of the database ("main", "temp",
2523** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2524** is the name of the inner-most trigger or view that is responsible for
2525** the access attempt or NULL if this access attempt is directly from
2526** top-level SQL code.
2527*/
2528/******************************************* 3rd ************ 4th ***********/
2529#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2530#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2531#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2532#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2533#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2534#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2535#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2536#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2537#define SQLITE_DELETE                9   /* Table Name      NULL            */
2538#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2539#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2540#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2541#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2542#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2543#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2544#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2545#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2546#define SQLITE_INSERT               18   /* Table Name      NULL            */
2547#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2548#define SQLITE_READ                 20   /* Table Name      Column Name     */
2549#define SQLITE_SELECT               21   /* NULL            NULL            */
2550#define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2551#define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2552#define SQLITE_ATTACH               24   /* Filename        NULL            */
2553#define SQLITE_DETACH               25   /* Database Name   NULL            */
2554#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2555#define SQLITE_REINDEX              27   /* Index Name      NULL            */
2556#define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2557#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2558#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2559#define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2560#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2561#define SQLITE_COPY                  0   /* No longer used */
2562
2563/*
2564** CAPI3REF: Tracing And Profiling Functions
2565** EXPERIMENTAL
2566**
2567** These routines register callback functions that can be used for
2568** tracing and profiling the execution of SQL statements.
2569**
2570** ^The callback function registered by sqlite3_trace() is invoked at
2571** various times when an SQL statement is being run by [sqlite3_step()].
2572** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2573** SQL statement text as the statement first begins executing.
2574** ^(Additional sqlite3_trace() callbacks might occur
2575** as each triggered subprogram is entered.  The callbacks for triggers
2576** contain a UTF-8 SQL comment that identifies the trigger.)^
2577**
2578** ^The callback function registered by sqlite3_profile() is invoked
2579** as each SQL statement finishes.  ^The profile callback contains
2580** the original statement text and an estimate of wall-clock time
2581** of how long that statement took to run.
2582*/
2583SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2584SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2585   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2586
2587/*
2588** CAPI3REF: Query Progress Callbacks
2589**
2590** ^This routine configures a callback function - the
2591** progress callback - that is invoked periodically during long
2592** running calls to [sqlite3_exec()], [sqlite3_step()] and
2593** [sqlite3_get_table()].  An example use for this
2594** interface is to keep a GUI updated during a large query.
2595**
2596** ^If the progress callback returns non-zero, the operation is
2597** interrupted.  This feature can be used to implement a
2598** "Cancel" button on a GUI progress dialog box.
2599**
2600** The progress handler must not do anything that will modify
2601** the database connection that invoked the progress handler.
2602** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2603** database connections for the meaning of "modify" in this paragraph.
2604**
2605*/
2606SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2607
2608/*
2609** CAPI3REF: Opening A New Database Connection
2610**
2611** ^These routines open an SQLite database file whose name is given by the
2612** filename argument. ^The filename argument is interpreted as UTF-8 for
2613** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2614** order for sqlite3_open16(). ^(A [database connection] handle is usually
2615** returned in *ppDb, even if an error occurs.  The only exception is that
2616** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2617** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2618** object.)^ ^(If the database is opened (and/or created) successfully, then
2619** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2620** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2621** an English language description of the error following a failure of any
2622** of the sqlite3_open() routines.
2623**
2624** ^The default encoding for the database will be UTF-8 if
2625** sqlite3_open() or sqlite3_open_v2() is called and
2626** UTF-16 in the native byte order if sqlite3_open16() is used.
2627**
2628** Whether or not an error occurs when it is opened, resources
2629** associated with the [database connection] handle should be released by
2630** passing it to [sqlite3_close()] when it is no longer required.
2631**
2632** The sqlite3_open_v2() interface works like sqlite3_open()
2633** except that it accepts two additional parameters for additional control
2634** over the new database connection.  ^(The flags parameter to
2635** sqlite3_open_v2() can take one of
2636** the following three values, optionally combined with the
2637** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2638** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^
2639**
2640** <dl>
2641** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2642** <dd>The database is opened in read-only mode.  If the database does not
2643** already exist, an error is returned.</dd>)^
2644**
2645** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2646** <dd>The database is opened for reading and writing if possible, or reading
2647** only if the file is write protected by the operating system.  In either
2648** case the database must already exist, otherwise an error is returned.</dd>)^
2649**
2650** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2651** <dd>The database is opened for reading and writing, and is creates it if
2652** it does not already exist. This is the behavior that is always used for
2653** sqlite3_open() and sqlite3_open16().</dd>)^
2654** </dl>
2655**
2656** If the 3rd parameter to sqlite3_open_v2() is not one of the
2657** combinations shown above or one of the combinations shown above combined
2658** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2659** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_SHAREDCACHE] flags,
2660** then the behavior is undefined.
2661**
2662** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2663** opens in the multi-thread [threading mode] as long as the single-thread
2664** mode has not been set at compile-time or start-time.  ^If the
2665** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2666** in the serialized [threading mode] unless single-thread was
2667** previously selected at compile-time or start-time.
2668** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2669** eligible to use [shared cache mode], regardless of whether or not shared
2670** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
2671** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2672** participate in [shared cache mode] even if it is enabled.
2673**
2674** ^If the filename is ":memory:", then a private, temporary in-memory database
2675** is created for the connection.  ^This in-memory database will vanish when
2676** the database connection is closed.  Future versions of SQLite might
2677** make use of additional special filenames that begin with the ":" character.
2678** It is recommended that when a database filename actually does begin with
2679** a ":" character you should prefix the filename with a pathname such as
2680** "./" to avoid ambiguity.
2681**
2682** ^If the filename is an empty string, then a private, temporary
2683** on-disk database will be created.  ^This private database will be
2684** automatically deleted as soon as the database connection is closed.
2685**
2686** ^The fourth parameter to sqlite3_open_v2() is the name of the
2687** [sqlite3_vfs] object that defines the operating system interface that
2688** the new database connection should use.  ^If the fourth parameter is
2689** a NULL pointer then the default [sqlite3_vfs] object is used.
2690**
2691** <b>Note to Windows users:</b>  The encoding used for the filename argument
2692** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2693** codepage is currently defined.  Filenames containing international
2694** characters must be converted to UTF-8 prior to passing them into
2695** sqlite3_open() or sqlite3_open_v2().
2696*/
2697SQLITE_API int sqlite3_open(
2698  const char *filename,   /* Database filename (UTF-8) */
2699  sqlite3 **ppDb          /* OUT: SQLite db handle */
2700);
2701SQLITE_API int sqlite3_open16(
2702  const void *filename,   /* Database filename (UTF-16) */
2703  sqlite3 **ppDb          /* OUT: SQLite db handle */
2704);
2705SQLITE_API int sqlite3_open_v2(
2706  const char *filename,   /* Database filename (UTF-8) */
2707  sqlite3 **ppDb,         /* OUT: SQLite db handle */
2708  int flags,              /* Flags */
2709  const char *zVfs        /* Name of VFS module to use */
2710);
2711
2712/*
2713** CAPI3REF: Error Codes And Messages
2714**
2715** ^The sqlite3_errcode() interface returns the numeric [result code] or
2716** [extended result code] for the most recent failed sqlite3_* API call
2717** associated with a [database connection]. If a prior API call failed
2718** but the most recent API call succeeded, the return value from
2719** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
2720** interface is the same except that it always returns the
2721** [extended result code] even when extended result codes are
2722** disabled.
2723**
2724** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
2725** text that describes the error, as either UTF-8 or UTF-16 respectively.
2726** ^(Memory to hold the error message string is managed internally.
2727** The application does not need to worry about freeing the result.
2728** However, the error string might be overwritten or deallocated by
2729** subsequent calls to other SQLite interface functions.)^
2730**
2731** When the serialized [threading mode] is in use, it might be the
2732** case that a second error occurs on a separate thread in between
2733** the time of the first error and the call to these interfaces.
2734** When that happens, the second error will be reported since these
2735** interfaces always report the most recent result.  To avoid
2736** this, each thread can obtain exclusive use of the [database connection] D
2737** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
2738** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
2739** all calls to the interfaces listed here are completed.
2740**
2741** If an interface fails with SQLITE_MISUSE, that means the interface
2742** was invoked incorrectly by the application.  In that case, the
2743** error code and message may or may not be set.
2744*/
2745SQLITE_API int sqlite3_errcode(sqlite3 *db);
2746SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
2747SQLITE_API const char *sqlite3_errmsg(sqlite3*);
2748SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
2749
2750/*
2751** CAPI3REF: SQL Statement Object
2752** KEYWORDS: {prepared statement} {prepared statements}
2753**
2754** An instance of this object represents a single SQL statement.
2755** This object is variously known as a "prepared statement" or a
2756** "compiled SQL statement" or simply as a "statement".
2757**
2758** The life of a statement object goes something like this:
2759**
2760** <ol>
2761** <li> Create the object using [sqlite3_prepare_v2()] or a related
2762**      function.
2763** <li> Bind values to [host parameters] using the sqlite3_bind_*()
2764**      interfaces.
2765** <li> Run the SQL by calling [sqlite3_step()] one or more times.
2766** <li> Reset the statement using [sqlite3_reset()] then go back
2767**      to step 2.  Do this zero or more times.
2768** <li> Destroy the object using [sqlite3_finalize()].
2769** </ol>
2770**
2771** Refer to documentation on individual methods above for additional
2772** information.
2773*/
2774typedef struct sqlite3_stmt sqlite3_stmt;
2775
2776/*
2777** CAPI3REF: Run-time Limits
2778**
2779** ^(This interface allows the size of various constructs to be limited
2780** on a connection by connection basis.  The first parameter is the
2781** [database connection] whose limit is to be set or queried.  The
2782** second parameter is one of the [limit categories] that define a
2783** class of constructs to be size limited.  The third parameter is the
2784** new limit for that construct.  The function returns the old limit.)^
2785**
2786** ^If the new limit is a negative number, the limit is unchanged.
2787** ^(For the limit category of SQLITE_LIMIT_XYZ there is a
2788** [limits | hard upper bound]
2789** set by a compile-time C preprocessor macro named
2790** [limits | SQLITE_MAX_XYZ].
2791** (The "_LIMIT_" in the name is changed to "_MAX_".))^
2792** ^Attempts to increase a limit above its hard upper bound are
2793** silently truncated to the hard upper bound.
2794**
2795** Run-time limits are intended for use in applications that manage
2796** both their own internal database and also databases that are controlled
2797** by untrusted external sources.  An example application might be a
2798** web browser that has its own databases for storing history and
2799** separate databases controlled by JavaScript applications downloaded
2800** off the Internet.  The internal databases can be given the
2801** large, default limits.  Databases managed by external sources can
2802** be given much smaller limits designed to prevent a denial of service
2803** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
2804** interface to further control untrusted SQL.  The size of the database
2805** created by an untrusted script can be contained using the
2806** [max_page_count] [PRAGMA].
2807**
2808** New run-time limit categories may be added in future releases.
2809*/
2810SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
2811
2812/*
2813** CAPI3REF: Run-Time Limit Categories
2814** KEYWORDS: {limit category} {*limit categories}
2815**
2816** These constants define various performance limits
2817** that can be lowered at run-time using [sqlite3_limit()].
2818** The synopsis of the meanings of the various limits is shown below.
2819** Additional information is available at [limits | Limits in SQLite].
2820**
2821** <dl>
2822** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
2823** <dd>The maximum size of any string or BLOB or table row.<dd>)^
2824**
2825** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
2826** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
2827**
2828** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
2829** <dd>The maximum number of columns in a table definition or in the
2830** result set of a [SELECT] or the maximum number of columns in an index
2831** or in an ORDER BY or GROUP BY clause.</dd>)^
2832**
2833** ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
2834** <dd>The maximum depth of the parse tree on any expression.</dd>)^
2835**
2836** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
2837** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
2838**
2839** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
2840** <dd>The maximum number of instructions in a virtual machine program
2841** used to implement an SQL statement.</dd>)^
2842**
2843** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
2844** <dd>The maximum number of arguments on a function.</dd>)^
2845**
2846** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
2847** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
2848**
2849** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
2850** <dd>The maximum length of the pattern argument to the [LIKE] or
2851** [GLOB] operators.</dd>)^
2852**
2853** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
2854** <dd>The maximum number of variables in an SQL statement that can
2855** be bound.</dd>)^
2856**
2857** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
2858** <dd>The maximum depth of recursion for triggers.</dd>)^
2859** </dl>
2860*/
2861#define SQLITE_LIMIT_LENGTH                    0
2862#define SQLITE_LIMIT_SQL_LENGTH                1
2863#define SQLITE_LIMIT_COLUMN                    2
2864#define SQLITE_LIMIT_EXPR_DEPTH                3
2865#define SQLITE_LIMIT_COMPOUND_SELECT           4
2866#define SQLITE_LIMIT_VDBE_OP                   5
2867#define SQLITE_LIMIT_FUNCTION_ARG              6
2868#define SQLITE_LIMIT_ATTACHED                  7
2869#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
2870#define SQLITE_LIMIT_VARIABLE_NUMBER           9
2871#define SQLITE_LIMIT_TRIGGER_DEPTH            10
2872
2873/*
2874** CAPI3REF: Compiling An SQL Statement
2875** KEYWORDS: {SQL statement compiler}
2876**
2877** To execute an SQL query, it must first be compiled into a byte-code
2878** program using one of these routines.
2879**
2880** The first argument, "db", is a [database connection] obtained from a
2881** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
2882** [sqlite3_open16()].  The database connection must not have been closed.
2883**
2884** The second argument, "zSql", is the statement to be compiled, encoded
2885** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
2886** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
2887** use UTF-16.
2888**
2889** ^If the nByte argument is less than zero, then zSql is read up to the
2890** first zero terminator. ^If nByte is non-negative, then it is the maximum
2891** number of  bytes read from zSql.  ^When nByte is non-negative, the
2892** zSql string ends at either the first '\000' or '\u0000' character or
2893** the nByte-th byte, whichever comes first. If the caller knows
2894** that the supplied string is nul-terminated, then there is a small
2895** performance advantage to be gained by passing an nByte parameter that
2896** is equal to the number of bytes in the input string <i>including</i>
2897** the nul-terminator bytes.
2898**
2899** ^If pzTail is not NULL then *pzTail is made to point to the first byte
2900** past the end of the first SQL statement in zSql.  These routines only
2901** compile the first statement in zSql, so *pzTail is left pointing to
2902** what remains uncompiled.
2903**
2904** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
2905** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
2906** to NULL.  ^If the input text contains no SQL (if the input is an empty
2907** string or a comment) then *ppStmt is set to NULL.
2908** The calling procedure is responsible for deleting the compiled
2909** SQL statement using [sqlite3_finalize()] after it has finished with it.
2910** ppStmt may not be NULL.
2911**
2912** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
2913** otherwise an [error code] is returned.
2914**
2915** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
2916** recommended for all new programs. The two older interfaces are retained
2917** for backwards compatibility, but their use is discouraged.
2918** ^In the "v2" interfaces, the prepared statement
2919** that is returned (the [sqlite3_stmt] object) contains a copy of the
2920** original SQL text. This causes the [sqlite3_step()] interface to
2921** behave differently in three ways:
2922**
2923** <ol>
2924** <li>
2925** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
2926** always used to do, [sqlite3_step()] will automatically recompile the SQL
2927** statement and try to run it again.  ^If the schema has changed in
2928** a way that makes the statement no longer valid, [sqlite3_step()] will still
2929** return [SQLITE_SCHEMA].  But unlike the legacy behavior, [SQLITE_SCHEMA] is
2930** now a fatal error.  Calling [sqlite3_prepare_v2()] again will not make the
2931** error go away.  Note: use [sqlite3_errmsg()] to find the text
2932** of the parsing error that results in an [SQLITE_SCHEMA] return.
2933** </li>
2934**
2935** <li>
2936** ^When an error occurs, [sqlite3_step()] will return one of the detailed
2937** [error codes] or [extended error codes].  ^The legacy behavior was that
2938** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
2939** and the application would have to make a second call to [sqlite3_reset()]
2940** in order to find the underlying cause of the problem. With the "v2" prepare
2941** interfaces, the underlying reason for the error is returned immediately.
2942** </li>
2943**
2944** <li>
2945** ^If the value of a [parameter | host parameter] in the WHERE clause might
2946** change the query plan for a statement, then the statement may be
2947** automatically recompiled (as if there had been a schema change) on the first
2948** [sqlite3_step()] call following any change to the
2949** [sqlite3_bind_text | bindings] of the [parameter].
2950** </li>
2951** </ol>
2952*/
2953SQLITE_API int sqlite3_prepare(
2954  sqlite3 *db,            /* Database handle */
2955  const char *zSql,       /* SQL statement, UTF-8 encoded */
2956  int nByte,              /* Maximum length of zSql in bytes. */
2957  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2958  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
2959);
2960SQLITE_API int sqlite3_prepare_v2(
2961  sqlite3 *db,            /* Database handle */
2962  const char *zSql,       /* SQL statement, UTF-8 encoded */
2963  int nByte,              /* Maximum length of zSql in bytes. */
2964  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2965  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
2966);
2967SQLITE_API int sqlite3_prepare16(
2968  sqlite3 *db,            /* Database handle */
2969  const void *zSql,       /* SQL statement, UTF-16 encoded */
2970  int nByte,              /* Maximum length of zSql in bytes. */
2971  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2972  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
2973);
2974SQLITE_API int sqlite3_prepare16_v2(
2975  sqlite3 *db,            /* Database handle */
2976  const void *zSql,       /* SQL statement, UTF-16 encoded */
2977  int nByte,              /* Maximum length of zSql in bytes. */
2978  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2979  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
2980);
2981
2982/*
2983** CAPI3REF: Retrieving Statement SQL
2984**
2985** ^This interface can be used to retrieve a saved copy of the original
2986** SQL text used to create a [prepared statement] if that statement was
2987** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
2988*/
2989SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
2990
2991/*
2992** CAPI3REF: Dynamically Typed Value Object
2993** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
2994**
2995** SQLite uses the sqlite3_value object to represent all values
2996** that can be stored in a database table. SQLite uses dynamic typing
2997** for the values it stores.  ^Values stored in sqlite3_value objects
2998** can be integers, floating point values, strings, BLOBs, or NULL.
2999**
3000** An sqlite3_value object may be either "protected" or "unprotected".
3001** Some interfaces require a protected sqlite3_value.  Other interfaces
3002** will accept either a protected or an unprotected sqlite3_value.
3003** Every interface that accepts sqlite3_value arguments specifies
3004** whether or not it requires a protected sqlite3_value.
3005**
3006** The terms "protected" and "unprotected" refer to whether or not
3007** a mutex is held.  A internal mutex is held for a protected
3008** sqlite3_value object but no mutex is held for an unprotected
3009** sqlite3_value object.  If SQLite is compiled to be single-threaded
3010** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3011** or if SQLite is run in one of reduced mutex modes
3012** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3013** then there is no distinction between protected and unprotected
3014** sqlite3_value objects and they can be used interchangeably.  However,
3015** for maximum code portability it is recommended that applications
3016** still make the distinction between between protected and unprotected
3017** sqlite3_value objects even when not strictly required.
3018**
3019** ^The sqlite3_value objects that are passed as parameters into the
3020** implementation of [application-defined SQL functions] are protected.
3021** ^The sqlite3_value object returned by
3022** [sqlite3_column_value()] is unprotected.
3023** Unprotected sqlite3_value objects may only be used with
3024** [sqlite3_result_value()] and [sqlite3_bind_value()].
3025** The [sqlite3_value_blob | sqlite3_value_type()] family of
3026** interfaces require protected sqlite3_value objects.
3027*/
3028typedef struct Mem sqlite3_value;
3029
3030/*
3031** CAPI3REF: SQL Function Context Object
3032**
3033** The context in which an SQL function executes is stored in an
3034** sqlite3_context object.  ^A pointer to an sqlite3_context object
3035** is always first parameter to [application-defined SQL functions].
3036** The application-defined SQL function implementation will pass this
3037** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3038** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3039** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3040** and/or [sqlite3_set_auxdata()].
3041*/
3042typedef struct sqlite3_context sqlite3_context;
3043
3044/*
3045** CAPI3REF: Binding Values To Prepared Statements
3046** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3047** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3048**
3049** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3050** literals may be replaced by a [parameter] that matches one of following
3051** templates:
3052**
3053** <ul>
3054** <li>  ?
3055** <li>  ?NNN
3056** <li>  :VVV
3057** <li>  @VVV
3058** <li>  $VVV
3059** </ul>
3060**
3061** In the templates above, NNN represents an integer literal,
3062** and VVV represents an alphanumeric identifer.)^  ^The values of these
3063** parameters (also called "host parameter names" or "SQL parameters")
3064** can be set using the sqlite3_bind_*() routines defined here.
3065**
3066** ^The first argument to the sqlite3_bind_*() routines is always
3067** a pointer to the [sqlite3_stmt] object returned from
3068** [sqlite3_prepare_v2()] or its variants.
3069**
3070** ^The second argument is the index of the SQL parameter to be set.
3071** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3072** SQL parameter is used more than once, second and subsequent
3073** occurrences have the same index as the first occurrence.
3074** ^The index for named parameters can be looked up using the
3075** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3076** for "?NNN" parameters is the value of NNN.
3077** ^The NNN value must be between 1 and the [sqlite3_limit()]
3078** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3079**
3080** ^The third argument is the value to bind to the parameter.
3081**
3082** ^(In those routines that have a fourth argument, its value is the
3083** number of bytes in the parameter.  To be clear: the value is the
3084** number of <u>bytes</u> in the value, not the number of characters.)^
3085** ^If the fourth parameter is negative, the length of the string is
3086** the number of bytes up to the first zero terminator.
3087**
3088** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3089** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3090** string after SQLite has finished with it. ^If the fifth argument is
3091** the special value [SQLITE_STATIC], then SQLite assumes that the
3092** information is in static, unmanaged space and does not need to be freed.
3093** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3094** SQLite makes its own private copy of the data immediately, before
3095** the sqlite3_bind_*() routine returns.
3096**
3097** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3098** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3099** (just an integer to hold its size) while it is being processed.
3100** Zeroblobs are intended to serve as placeholders for BLOBs whose
3101** content is later written using
3102** [sqlite3_blob_open | incremental BLOB I/O] routines.
3103** ^A negative value for the zeroblob results in a zero-length BLOB.
3104**
3105** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3106** for the [prepared statement] or with a prepared statement for which
3107** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3108** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3109** routine is passed a [prepared statement] that has been finalized, the
3110** result is undefined and probably harmful.
3111**
3112** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3113** ^Unbound parameters are interpreted as NULL.
3114**
3115** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3116** [error code] if anything goes wrong.
3117** ^[SQLITE_RANGE] is returned if the parameter
3118** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3119**
3120** See also: [sqlite3_bind_parameter_count()],
3121** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3122*/
3123SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3124SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3125SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3126SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3127SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3128SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3129SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3130SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3131SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3132
3133/*
3134** CAPI3REF: Number Of SQL Parameters
3135**
3136** ^This routine can be used to find the number of [SQL parameters]
3137** in a [prepared statement].  SQL parameters are tokens of the
3138** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3139** placeholders for values that are [sqlite3_bind_blob | bound]
3140** to the parameters at a later time.
3141**
3142** ^(This routine actually returns the index of the largest (rightmost)
3143** parameter. For all forms except ?NNN, this will correspond to the
3144** number of unique parameters.  If parameters of the ?NNN form are used,
3145** there may be gaps in the list.)^
3146**
3147** See also: [sqlite3_bind_blob|sqlite3_bind()],
3148** [sqlite3_bind_parameter_name()], and
3149** [sqlite3_bind_parameter_index()].
3150*/
3151SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3152
3153/*
3154** CAPI3REF: Name Of A Host Parameter
3155**
3156** ^The sqlite3_bind_parameter_name(P,N) interface returns
3157** the name of the N-th [SQL parameter] in the [prepared statement] P.
3158** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3159** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3160** respectively.
3161** In other words, the initial ":" or "$" or "@" or "?"
3162** is included as part of the name.)^
3163** ^Parameters of the form "?" without a following integer have no name
3164** and are referred to as "nameless" or "anonymous parameters".
3165**
3166** ^The first host parameter has an index of 1, not 0.
3167**
3168** ^If the value N is out of range or if the N-th parameter is
3169** nameless, then NULL is returned.  ^The returned string is
3170** always in UTF-8 encoding even if the named parameter was
3171** originally specified as UTF-16 in [sqlite3_prepare16()] or
3172** [sqlite3_prepare16_v2()].
3173**
3174** See also: [sqlite3_bind_blob|sqlite3_bind()],
3175** [sqlite3_bind_parameter_count()], and
3176** [sqlite3_bind_parameter_index()].
3177*/
3178SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3179
3180/*
3181** CAPI3REF: Index Of A Parameter With A Given Name
3182**
3183** ^Return the index of an SQL parameter given its name.  ^The
3184** index value returned is suitable for use as the second
3185** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3186** is returned if no matching parameter is found.  ^The parameter
3187** name must be given in UTF-8 even if the original statement
3188** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3189**
3190** See also: [sqlite3_bind_blob|sqlite3_bind()],
3191** [sqlite3_bind_parameter_count()], and
3192** [sqlite3_bind_parameter_index()].
3193*/
3194SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3195
3196/*
3197** CAPI3REF: Reset All Bindings On A Prepared Statement
3198**
3199** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3200** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3201** ^Use this routine to reset all host parameters to NULL.
3202*/
3203SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3204
3205/*
3206** CAPI3REF: Number Of Columns In A Result Set
3207**
3208** ^Return the number of columns in the result set returned by the
3209** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3210** statement that does not return data (for example an [UPDATE]).
3211*/
3212SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3213
3214/*
3215** CAPI3REF: Column Names In A Result Set
3216**
3217** ^These routines return the name assigned to a particular column
3218** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3219** interface returns a pointer to a zero-terminated UTF-8 string
3220** and sqlite3_column_name16() returns a pointer to a zero-terminated
3221** UTF-16 string.  ^The first parameter is the [prepared statement]
3222** that implements the [SELECT] statement. ^The second parameter is the
3223** column number.  ^The leftmost column is number 0.
3224**
3225** ^The returned string pointer is valid until either the [prepared statement]
3226** is destroyed by [sqlite3_finalize()] or until the next call to
3227** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3228**
3229** ^If sqlite3_malloc() fails during the processing of either routine
3230** (for example during a conversion from UTF-8 to UTF-16) then a
3231** NULL pointer is returned.
3232**
3233** ^The name of a result column is the value of the "AS" clause for
3234** that column, if there is an AS clause.  If there is no AS clause
3235** then the name of the column is unspecified and may change from
3236** one release of SQLite to the next.
3237*/
3238SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3239SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3240
3241/*
3242** CAPI3REF: Source Of Data In A Query Result
3243**
3244** ^These routines provide a means to determine the database, table, and
3245** table column that is the origin of a particular result column in
3246** [SELECT] statement.
3247** ^The name of the database or table or column can be returned as
3248** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3249** the database name, the _table_ routines return the table name, and
3250** the origin_ routines return the column name.
3251** ^The returned string is valid until the [prepared statement] is destroyed
3252** using [sqlite3_finalize()] or until the same information is requested
3253** again in a different encoding.
3254**
3255** ^The names returned are the original un-aliased names of the
3256** database, table, and column.
3257**
3258** ^The first argument to these interfaces is a [prepared statement].
3259** ^These functions return information about the Nth result column returned by
3260** the statement, where N is the second function argument.
3261** ^The left-most column is column 0 for these routines.
3262**
3263** ^If the Nth column returned by the statement is an expression or
3264** subquery and is not a column value, then all of these functions return
3265** NULL.  ^These routine might also return NULL if a memory allocation error
3266** occurs.  ^Otherwise, they return the name of the attached database, table,
3267** or column that query result column was extracted from.
3268**
3269** ^As with all other SQLite APIs, those whose names end with "16" return
3270** UTF-16 encoded strings and the other functions return UTF-8.
3271**
3272** ^These APIs are only available if the library was compiled with the
3273** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3274**
3275** If two or more threads call one or more of these routines against the same
3276** prepared statement and column at the same time then the results are
3277** undefined.
3278**
3279** If two or more threads call one or more
3280** [sqlite3_column_database_name | column metadata interfaces]
3281** for the same [prepared statement] and result column
3282** at the same time then the results are undefined.
3283*/
3284SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3285SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3286SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3287SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3288SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3289SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3290
3291/*
3292** CAPI3REF: Declared Datatype Of A Query Result
3293**
3294** ^(The first parameter is a [prepared statement].
3295** If this statement is a [SELECT] statement and the Nth column of the
3296** returned result set of that [SELECT] is a table column (not an
3297** expression or subquery) then the declared type of the table
3298** column is returned.)^  ^If the Nth column of the result set is an
3299** expression or subquery, then a NULL pointer is returned.
3300** ^The returned string is always UTF-8 encoded.
3301**
3302** ^(For example, given the database schema:
3303**
3304** CREATE TABLE t1(c1 VARIANT);
3305**
3306** and the following statement to be compiled:
3307**
3308** SELECT c1 + 1, c1 FROM t1;
3309**
3310** this routine would return the string "VARIANT" for the second result
3311** column (i==1), and a NULL pointer for the first result column (i==0).)^
3312**
3313** ^SQLite uses dynamic run-time typing.  ^So just because a column
3314** is declared to contain a particular type does not mean that the
3315** data stored in that column is of the declared type.  SQLite is
3316** strongly typed, but the typing is dynamic not static.  ^Type
3317** is associated with individual values, not with the containers
3318** used to hold those values.
3319*/
3320SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3321SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3322
3323/*
3324** CAPI3REF: Evaluate An SQL Statement
3325**
3326** After a [prepared statement] has been prepared using either
3327** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3328** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3329** must be called one or more times to evaluate the statement.
3330**
3331** The details of the behavior of the sqlite3_step() interface depend
3332** on whether the statement was prepared using the newer "v2" interface
3333** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3334** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3335** new "v2" interface is recommended for new applications but the legacy
3336** interface will continue to be supported.
3337**
3338** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3339** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3340** ^With the "v2" interface, any of the other [result codes] or
3341** [extended result codes] might be returned as well.
3342**
3343** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3344** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3345** or occurs outside of an explicit transaction, then you can retry the
3346** statement.  If the statement is not a [COMMIT] and occurs within a
3347** explicit transaction then you should rollback the transaction before
3348** continuing.
3349**
3350** ^[SQLITE_DONE] means that the statement has finished executing
3351** successfully.  sqlite3_step() should not be called again on this virtual
3352** machine without first calling [sqlite3_reset()] to reset the virtual
3353** machine back to its initial state.
3354**
3355** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3356** is returned each time a new row of data is ready for processing by the
3357** caller. The values may be accessed using the [column access functions].
3358** sqlite3_step() is called again to retrieve the next row of data.
3359**
3360** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3361** violation) has occurred.  sqlite3_step() should not be called again on
3362** the VM. More information may be found by calling [sqlite3_errmsg()].
3363** ^With the legacy interface, a more specific error code (for example,
3364** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3365** can be obtained by calling [sqlite3_reset()] on the
3366** [prepared statement].  ^In the "v2" interface,
3367** the more specific error code is returned directly by sqlite3_step().
3368**
3369** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3370** Perhaps it was called on a [prepared statement] that has
3371** already been [sqlite3_finalize | finalized] or on one that had
3372** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3373** be the case that the same database connection is being used by two or
3374** more threads at the same moment in time.
3375**
3376** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3377** API always returns a generic error code, [SQLITE_ERROR], following any
3378** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3379** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3380** specific [error codes] that better describes the error.
3381** We admit that this is a goofy design.  The problem has been fixed
3382** with the "v2" interface.  If you prepare all of your SQL statements
3383** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3384** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3385** then the more specific [error codes] are returned directly
3386** by sqlite3_step().  The use of the "v2" interface is recommended.
3387*/
3388SQLITE_API int sqlite3_step(sqlite3_stmt*);
3389
3390/*
3391** CAPI3REF: Number of columns in a result set
3392**
3393** ^The sqlite3_data_count(P) the number of columns in the
3394** of the result set of [prepared statement] P.
3395*/
3396SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3397
3398/*
3399** CAPI3REF: Fundamental Datatypes
3400** KEYWORDS: SQLITE_TEXT
3401**
3402** ^(Every value in SQLite has one of five fundamental datatypes:
3403**
3404** <ul>
3405** <li> 64-bit signed integer
3406** <li> 64-bit IEEE floating point number
3407** <li> string
3408** <li> BLOB
3409** <li> NULL
3410** </ul>)^
3411**
3412** These constants are codes for each of those types.
3413**
3414** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3415** for a completely different meaning.  Software that links against both
3416** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3417** SQLITE_TEXT.
3418*/
3419#define SQLITE_INTEGER  1
3420#define SQLITE_FLOAT    2
3421#define SQLITE_BLOB     4
3422#define SQLITE_NULL     5
3423#ifdef SQLITE_TEXT
3424# undef SQLITE_TEXT
3425#else
3426# define SQLITE_TEXT     3
3427#endif
3428#define SQLITE3_TEXT     3
3429
3430/*
3431** CAPI3REF: Result Values From A Query
3432** KEYWORDS: {column access functions}
3433**
3434** These routines form the "result set" interface.
3435**
3436** ^These routines return information about a single column of the current
3437** result row of a query.  ^In every case the first argument is a pointer
3438** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3439** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3440** and the second argument is the index of the column for which information
3441** should be returned. ^The leftmost column of the result set has the index 0.
3442** ^The number of columns in the result can be determined using
3443** [sqlite3_column_count()].
3444**
3445** If the SQL statement does not currently point to a valid row, or if the
3446** column index is out of range, the result is undefined.
3447** These routines may only be called when the most recent call to
3448** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3449** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3450** If any of these routines are called after [sqlite3_reset()] or
3451** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3452** something other than [SQLITE_ROW], the results are undefined.
3453** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3454** are called from a different thread while any of these routines
3455** are pending, then the results are undefined.
3456**
3457** ^The sqlite3_column_type() routine returns the
3458** [SQLITE_INTEGER | datatype code] for the initial data type
3459** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
3460** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3461** returned by sqlite3_column_type() is only meaningful if no type
3462** conversions have occurred as described below.  After a type conversion,
3463** the value returned by sqlite3_column_type() is undefined.  Future
3464** versions of SQLite may change the behavior of sqlite3_column_type()
3465** following a type conversion.
3466**
3467** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3468** routine returns the number of bytes in that BLOB or string.
3469** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3470** the string to UTF-8 and then returns the number of bytes.
3471** ^If the result is a numeric value then sqlite3_column_bytes() uses
3472** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3473** the number of bytes in that string.
3474** ^The value returned does not include the zero terminator at the end
3475** of the string.  ^For clarity: the value returned is the number of
3476** bytes in the string, not the number of characters.
3477**
3478** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3479** even empty strings, are always zero terminated.  ^The return
3480** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
3481** pointer, possibly even a NULL pointer.
3482**
3483** ^The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
3484** but leaves the result in UTF-16 in native byte order instead of UTF-8.
3485** ^The zero terminator is not included in this count.
3486**
3487** ^The object returned by [sqlite3_column_value()] is an
3488** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
3489** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3490** If the [unprotected sqlite3_value] object returned by
3491** [sqlite3_column_value()] is used in any other way, including calls
3492** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
3493** or [sqlite3_value_bytes()], then the behavior is undefined.
3494**
3495** These routines attempt to convert the value where appropriate.  ^For
3496** example, if the internal representation is FLOAT and a text result
3497** is requested, [sqlite3_snprintf()] is used internally to perform the
3498** conversion automatically.  ^(The following table details the conversions
3499** that are applied:
3500**
3501** <blockquote>
3502** <table border="1">
3503** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
3504**
3505** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
3506** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
3507** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
3508** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
3509** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
3510** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
3511** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
3512** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
3513** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
3514** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
3515** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
3516** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
3517** <tr><td>  TEXT    <td>   BLOB    <td> No change
3518** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
3519** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
3520** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
3521** </table>
3522** </blockquote>)^
3523**
3524** The table above makes reference to standard C library functions atoi()
3525** and atof().  SQLite does not really use these functions.  It has its
3526** own equivalent internal routines.  The atoi() and atof() names are
3527** used in the table for brevity and because they are familiar to most
3528** C programmers.
3529**
3530** ^Note that when type conversions occur, pointers returned by prior
3531** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3532** sqlite3_column_text16() may be invalidated.
3533** ^(Type conversions and pointer invalidations might occur
3534** in the following cases:
3535**
3536** <ul>
3537** <li> The initial content is a BLOB and sqlite3_column_text() or
3538**      sqlite3_column_text16() is called.  A zero-terminator might
3539**      need to be added to the string.</li>
3540** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
3541**      sqlite3_column_text16() is called.  The content must be converted
3542**      to UTF-16.</li>
3543** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3544**      sqlite3_column_text() is called.  The content must be converted
3545**      to UTF-8.</li>
3546** </ul>)^
3547**
3548** ^Conversions between UTF-16be and UTF-16le are always done in place and do
3549** not invalidate a prior pointer, though of course the content of the buffer
3550** that the prior pointer points to will have been modified.  Other kinds
3551** of conversion are done in place when it is possible, but sometimes they
3552** are not possible and in those cases prior pointers are invalidated.
3553**
3554** ^(The safest and easiest to remember policy is to invoke these routines
3555** in one of the following ways:
3556**
3557** <ul>
3558**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3559**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3560**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3561** </ul>)^
3562**
3563** In other words, you should call sqlite3_column_text(),
3564** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
3565** into the desired format, then invoke sqlite3_column_bytes() or
3566** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
3567** to sqlite3_column_text() or sqlite3_column_blob() with calls to
3568** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
3569** with calls to sqlite3_column_bytes().
3570**
3571** ^The pointers returned are valid until a type conversion occurs as
3572** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
3573** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
3574** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
3575** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
3576** [sqlite3_free()].
3577**
3578** ^(If a memory allocation error occurs during the evaluation of any
3579** of these routines, a default value is returned.  The default value
3580** is either the integer 0, the floating point number 0.0, or a NULL
3581** pointer.  Subsequent calls to [sqlite3_errcode()] will return
3582** [SQLITE_NOMEM].)^
3583*/
3584SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
3585SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
3586SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
3587SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
3588SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
3589SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
3590SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
3591SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
3592SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
3593SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
3594
3595/*
3596** CAPI3REF: Destroy A Prepared Statement Object
3597**
3598** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3599** ^If the statement was executed successfully or not executed at all, then
3600** SQLITE_OK is returned. ^If execution of the statement failed then an
3601** [error code] or [extended error code] is returned.
3602**
3603** ^This routine can be called at any point during the execution of the
3604** [prepared statement].  ^If the virtual machine has not
3605** completed execution when this routine is called, that is like
3606** encountering an error or an [sqlite3_interrupt | interrupt].
3607** ^Incomplete updates may be rolled back and transactions canceled,
3608** depending on the circumstances, and the
3609** [error code] returned will be [SQLITE_ABORT].
3610*/
3611SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3612
3613/*
3614** CAPI3REF: Reset A Prepared Statement Object
3615**
3616** The sqlite3_reset() function is called to reset a [prepared statement]
3617** object back to its initial state, ready to be re-executed.
3618** ^Any SQL statement variables that had values bound to them using
3619** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
3620** Use [sqlite3_clear_bindings()] to reset the bindings.
3621**
3622** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
3623** back to the beginning of its program.
3624**
3625** ^If the most recent call to [sqlite3_step(S)] for the
3626** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
3627** or if [sqlite3_step(S)] has never before been called on S,
3628** then [sqlite3_reset(S)] returns [SQLITE_OK].
3629**
3630** ^If the most recent call to [sqlite3_step(S)] for the
3631** [prepared statement] S indicated an error, then
3632** [sqlite3_reset(S)] returns an appropriate [error code].
3633**
3634** ^The [sqlite3_reset(S)] interface does not change the values
3635** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
3636*/
3637SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
3638
3639/*
3640** CAPI3REF: Create Or Redefine SQL Functions
3641** KEYWORDS: {function creation routines}
3642** KEYWORDS: {application-defined SQL function}
3643** KEYWORDS: {application-defined SQL functions}
3644**
3645** ^These two functions (collectively known as "function creation routines")
3646** are used to add SQL functions or aggregates or to redefine the behavior
3647** of existing SQL functions or aggregates.  The only difference between the
3648** two is that the second parameter, the name of the (scalar) function or
3649** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
3650** for sqlite3_create_function16().
3651**
3652** ^The first parameter is the [database connection] to which the SQL
3653** function is to be added.  ^If an application uses more than one database
3654** connection then application-defined SQL functions must be added
3655** to each database connection separately.
3656**
3657** The second parameter is the name of the SQL function to be created or
3658** redefined.  ^The length of the name is limited to 255 bytes, exclusive of
3659** the zero-terminator.  Note that the name length limit is in bytes, not
3660** characters.  ^Any attempt to create a function with a longer name
3661** will result in [SQLITE_ERROR] being returned.
3662**
3663** ^The third parameter (nArg)
3664** is the number of arguments that the SQL function or
3665** aggregate takes. ^If this parameter is -1, then the SQL function or
3666** aggregate may take any number of arguments between 0 and the limit
3667** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
3668** parameter is less than -1 or greater than 127 then the behavior is
3669** undefined.
3670**
3671** The fourth parameter, eTextRep, specifies what
3672** [SQLITE_UTF8 | text encoding] this SQL function prefers for
3673** its parameters.  Any SQL function implementation should be able to work
3674** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
3675** more efficient with one encoding than another.  ^An application may
3676** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
3677** times with the same function but with different values of eTextRep.
3678** ^When multiple implementations of the same function are available, SQLite
3679** will pick the one that involves the least amount of data conversion.
3680** If there is only a single implementation which does not care what text
3681** encoding is used, then the fourth argument should be [SQLITE_ANY].
3682**
3683** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
3684** function can gain access to this pointer using [sqlite3_user_data()].)^
3685**
3686** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
3687** pointers to C-language functions that implement the SQL function or
3688** aggregate. ^A scalar SQL function requires an implementation of the xFunc
3689** callback only; NULL pointers should be passed as the xStep and xFinal
3690** parameters. ^An aggregate SQL function requires an implementation of xStep
3691** and xFinal and NULL should be passed for xFunc. ^To delete an existing
3692** SQL function or aggregate, pass NULL for all three function callbacks.
3693**
3694** ^It is permitted to register multiple implementations of the same
3695** functions with the same name but with either differing numbers of
3696** arguments or differing preferred text encodings.  ^SQLite will use
3697** the implementation that most closely matches the way in which the
3698** SQL function is used.  ^A function implementation with a non-negative
3699** nArg parameter is a better match than a function implementation with
3700** a negative nArg.  ^A function where the preferred text encoding
3701** matches the database encoding is a better
3702** match than a function where the encoding is different.
3703** ^A function where the encoding difference is between UTF16le and UTF16be
3704** is a closer match than a function where the encoding difference is
3705** between UTF8 and UTF16.
3706**
3707** ^Built-in functions may be overloaded by new application-defined functions.
3708** ^The first application-defined function with a given name overrides all
3709** built-in functions in the same [database connection] with the same name.
3710** ^Subsequent application-defined functions of the same name only override
3711** prior application-defined functions that are an exact match for the
3712** number of parameters and preferred encoding.
3713**
3714** ^An application-defined function is permitted to call other
3715** SQLite interfaces.  However, such calls must not
3716** close the database connection nor finalize or reset the prepared
3717** statement in which the function is running.
3718*/
3719SQLITE_API int sqlite3_create_function(
3720  sqlite3 *db,
3721  const char *zFunctionName,
3722  int nArg,
3723  int eTextRep,
3724  void *pApp,
3725  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3726  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3727  void (*xFinal)(sqlite3_context*)
3728);
3729SQLITE_API int sqlite3_create_function16(
3730  sqlite3 *db,
3731  const void *zFunctionName,
3732  int nArg,
3733  int eTextRep,
3734  void *pApp,
3735  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3736  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3737  void (*xFinal)(sqlite3_context*)
3738);
3739
3740/*
3741** CAPI3REF: Text Encodings
3742**
3743** These constant define integer codes that represent the various
3744** text encodings supported by SQLite.
3745*/
3746#define SQLITE_UTF8           1
3747#define SQLITE_UTF16LE        2
3748#define SQLITE_UTF16BE        3
3749#define SQLITE_UTF16          4    /* Use native byte order */
3750#define SQLITE_ANY            5    /* sqlite3_create_function only */
3751#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
3752
3753/*
3754** CAPI3REF: Deprecated Functions
3755** DEPRECATED
3756**
3757** These functions are [deprecated].  In order to maintain
3758** backwards compatibility with older code, these functions continue
3759** to be supported.  However, new applications should avoid
3760** the use of these functions.  To help encourage people to avoid
3761** using these functions, we are not going to tell you what they do.
3762*/
3763#ifndef SQLITE_OMIT_DEPRECATED
3764SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
3765SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
3766SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
3767SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
3768SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
3769SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
3770#endif
3771
3772/*
3773** CAPI3REF: Obtaining SQL Function Parameter Values
3774**
3775** The C-language implementation of SQL functions and aggregates uses
3776** this set of interface routines to access the parameter values on
3777** the function or aggregate.
3778**
3779** The xFunc (for scalar functions) or xStep (for aggregates) parameters
3780** to [sqlite3_create_function()] and [sqlite3_create_function16()]
3781** define callbacks that implement the SQL functions and aggregates.
3782** The 4th parameter to these callbacks is an array of pointers to
3783** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
3784** each parameter to the SQL function.  These routines are used to
3785** extract values from the [sqlite3_value] objects.
3786**
3787** These routines work only with [protected sqlite3_value] objects.
3788** Any attempt to use these routines on an [unprotected sqlite3_value]
3789** object results in undefined behavior.
3790**
3791** ^These routines work just like the corresponding [column access functions]
3792** except that  these routines take a single [protected sqlite3_value] object
3793** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
3794**
3795** ^The sqlite3_value_text16() interface extracts a UTF-16 string
3796** in the native byte-order of the host machine.  ^The
3797** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
3798** extract UTF-16 strings as big-endian and little-endian respectively.
3799**
3800** ^(The sqlite3_value_numeric_type() interface attempts to apply
3801** numeric affinity to the value.  This means that an attempt is
3802** made to convert the value to an integer or floating point.  If
3803** such a conversion is possible without loss of information (in other
3804** words, if the value is a string that looks like a number)
3805** then the conversion is performed.  Otherwise no conversion occurs.
3806** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
3807**
3808** Please pay particular attention to the fact that the pointer returned
3809** from [sqlite3_value_blob()], [sqlite3_value_text()], or
3810** [sqlite3_value_text16()] can be invalidated by a subsequent call to
3811** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
3812** or [sqlite3_value_text16()].
3813**
3814** These routines must be called from the same thread as
3815** the SQL function that supplied the [sqlite3_value*] parameters.
3816*/
3817SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
3818SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
3819SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
3820SQLITE_API double sqlite3_value_double(sqlite3_value*);
3821SQLITE_API int sqlite3_value_int(sqlite3_value*);
3822SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
3823SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
3824SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
3825SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
3826SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
3827SQLITE_API int sqlite3_value_type(sqlite3_value*);
3828SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
3829
3830/*
3831** CAPI3REF: Obtain Aggregate Function Context
3832**
3833** Implementions of aggregate SQL functions use this
3834** routine to allocate memory for storing their state.
3835**
3836** ^The first time the sqlite3_aggregate_context(C,N) routine is called
3837** for a particular aggregate function, SQLite
3838** allocates N of memory, zeroes out that memory, and returns a pointer
3839** to the new memory. ^On second and subsequent calls to
3840** sqlite3_aggregate_context() for the same aggregate function instance,
3841** the same buffer is returned.  Sqlite3_aggregate_context() is normally
3842** called once for each invocation of the xStep callback and then one
3843** last time when the xFinal callback is invoked.  ^(When no rows match
3844** an aggregate query, the xStep() callback of the aggregate function
3845** implementation is never called and xFinal() is called exactly once.
3846** In those cases, sqlite3_aggregate_context() might be called for the
3847** first time from within xFinal().)^
3848**
3849** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
3850** less than or equal to zero or if a memory allocate error occurs.
3851**
3852** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
3853** determined by the N parameter on first successful call.  Changing the
3854** value of N in subsequent call to sqlite3_aggregate_context() within
3855** the same aggregate function instance will not resize the memory
3856** allocation.)^
3857**
3858** ^SQLite automatically frees the memory allocated by
3859** sqlite3_aggregate_context() when the aggregate query concludes.
3860**
3861** The first parameter must be a copy of the
3862** [sqlite3_context | SQL function context] that is the first parameter
3863** to the xStep or xFinal callback routine that implements the aggregate
3864** function.
3865**
3866** This routine must be called from the same thread in which
3867** the aggregate SQL function is running.
3868*/
3869SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
3870
3871/*
3872** CAPI3REF: User Data For Functions
3873**
3874** ^The sqlite3_user_data() interface returns a copy of
3875** the pointer that was the pUserData parameter (the 5th parameter)
3876** of the [sqlite3_create_function()]
3877** and [sqlite3_create_function16()] routines that originally
3878** registered the application defined function.
3879**
3880** This routine must be called from the same thread in which
3881** the application-defined function is running.
3882*/
3883SQLITE_API void *sqlite3_user_data(sqlite3_context*);
3884
3885/*
3886** CAPI3REF: Database Connection For Functions
3887**
3888** ^The sqlite3_context_db_handle() interface returns a copy of
3889** the pointer to the [database connection] (the 1st parameter)
3890** of the [sqlite3_create_function()]
3891** and [sqlite3_create_function16()] routines that originally
3892** registered the application defined function.
3893*/
3894SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
3895
3896/*
3897** CAPI3REF: Function Auxiliary Data
3898**
3899** The following two functions may be used by scalar SQL functions to
3900** associate metadata with argument values. If the same value is passed to
3901** multiple invocations of the same SQL function during query execution, under
3902** some circumstances the associated metadata may be preserved. This may
3903** be used, for example, to add a regular-expression matching scalar
3904** function. The compiled version of the regular expression is stored as
3905** metadata associated with the SQL value passed as the regular expression
3906** pattern.  The compiled regular expression can be reused on multiple
3907** invocations of the same function so that the original pattern string
3908** does not need to be recompiled on each invocation.
3909**
3910** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
3911** associated by the sqlite3_set_auxdata() function with the Nth argument
3912** value to the application-defined function. ^If no metadata has been ever
3913** been set for the Nth argument of the function, or if the corresponding
3914** function parameter has changed since the meta-data was set,
3915** then sqlite3_get_auxdata() returns a NULL pointer.
3916**
3917** ^The sqlite3_set_auxdata() interface saves the metadata
3918** pointed to by its 3rd parameter as the metadata for the N-th
3919** argument of the application-defined function.  Subsequent
3920** calls to sqlite3_get_auxdata() might return this data, if it has
3921** not been destroyed.
3922** ^If it is not NULL, SQLite will invoke the destructor
3923** function given by the 4th parameter to sqlite3_set_auxdata() on
3924** the metadata when the corresponding function parameter changes
3925** or when the SQL statement completes, whichever comes first.
3926**
3927** SQLite is free to call the destructor and drop metadata on any
3928** parameter of any function at any time.  ^The only guarantee is that
3929** the destructor will be called before the metadata is dropped.
3930**
3931** ^(In practice, metadata is preserved between function calls for
3932** expressions that are constant at compile time. This includes literal
3933** values and [parameters].)^
3934**
3935** These routines must be called from the same thread in which
3936** the SQL function is running.
3937*/
3938SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
3939SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
3940
3941
3942/*
3943** CAPI3REF: Constants Defining Special Destructor Behavior
3944**
3945** These are special values for the destructor that is passed in as the
3946** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
3947** argument is SQLITE_STATIC, it means that the content pointer is constant
3948** and will never change.  It does not need to be destroyed.  ^The
3949** SQLITE_TRANSIENT value means that the content will likely change in
3950** the near future and that SQLite should make its own private copy of
3951** the content before returning.
3952**
3953** The typedef is necessary to work around problems in certain
3954** C++ compilers.  See ticket #2191.
3955*/
3956typedef void (*sqlite3_destructor_type)(void*);
3957#define SQLITE_STATIC      ((sqlite3_destructor_type)0)
3958#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
3959
3960/*
3961** CAPI3REF: Setting The Result Of An SQL Function
3962**
3963** These routines are used by the xFunc or xFinal callbacks that
3964** implement SQL functions and aggregates.  See
3965** [sqlite3_create_function()] and [sqlite3_create_function16()]
3966** for additional information.
3967**
3968** These functions work very much like the [parameter binding] family of
3969** functions used to bind values to host parameters in prepared statements.
3970** Refer to the [SQL parameter] documentation for additional information.
3971**
3972** ^The sqlite3_result_blob() interface sets the result from
3973** an application-defined function to be the BLOB whose content is pointed
3974** to by the second parameter and which is N bytes long where N is the
3975** third parameter.
3976**
3977** ^The sqlite3_result_zeroblob() interfaces set the result of
3978** the application-defined function to be a BLOB containing all zero
3979** bytes and N bytes in size, where N is the value of the 2nd parameter.
3980**
3981** ^The sqlite3_result_double() interface sets the result from
3982** an application-defined function to be a floating point value specified
3983** by its 2nd argument.
3984**
3985** ^The sqlite3_result_error() and sqlite3_result_error16() functions
3986** cause the implemented SQL function to throw an exception.
3987** ^SQLite uses the string pointed to by the
3988** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
3989** as the text of an error message.  ^SQLite interprets the error
3990** message string from sqlite3_result_error() as UTF-8. ^SQLite
3991** interprets the string from sqlite3_result_error16() as UTF-16 in native
3992** byte order.  ^If the third parameter to sqlite3_result_error()
3993** or sqlite3_result_error16() is negative then SQLite takes as the error
3994** message all text up through the first zero character.
3995** ^If the third parameter to sqlite3_result_error() or
3996** sqlite3_result_error16() is non-negative then SQLite takes that many
3997** bytes (not characters) from the 2nd parameter as the error message.
3998** ^The sqlite3_result_error() and sqlite3_result_error16()
3999** routines make a private copy of the error message text before
4000** they return.  Hence, the calling function can deallocate or
4001** modify the text after they return without harm.
4002** ^The sqlite3_result_error_code() function changes the error code
4003** returned by SQLite as a result of an error in a function.  ^By default,
4004** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4005** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4006**
4007** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4008** indicating that a string or BLOB is too long to represent.
4009**
4010** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4011** indicating that a memory allocation failed.
4012**
4013** ^The sqlite3_result_int() interface sets the return value
4014** of the application-defined function to be the 32-bit signed integer
4015** value given in the 2nd argument.
4016** ^The sqlite3_result_int64() interface sets the return value
4017** of the application-defined function to be the 64-bit signed integer
4018** value given in the 2nd argument.
4019**
4020** ^The sqlite3_result_null() interface sets the return value
4021** of the application-defined function to be NULL.
4022**
4023** ^The sqlite3_result_text(), sqlite3_result_text16(),
4024** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4025** set the return value of the application-defined function to be
4026** a text string which is represented as UTF-8, UTF-16 native byte order,
4027** UTF-16 little endian, or UTF-16 big endian, respectively.
4028** ^SQLite takes the text result from the application from
4029** the 2nd parameter of the sqlite3_result_text* interfaces.
4030** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4031** is negative, then SQLite takes result text from the 2nd parameter
4032** through the first zero character.
4033** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4034** is non-negative, then as many bytes (not characters) of the text
4035** pointed to by the 2nd parameter are taken as the application-defined
4036** function result.
4037** ^If the 4th parameter to the sqlite3_result_text* interfaces
4038** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4039** function as the destructor on the text or BLOB result when it has
4040** finished using that result.
4041** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4042** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4043** assumes that the text or BLOB result is in constant space and does not
4044** copy the content of the parameter nor call a destructor on the content
4045** when it has finished using that result.
4046** ^If the 4th parameter to the sqlite3_result_text* interfaces
4047** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4048** then SQLite makes a copy of the result into space obtained from
4049** from [sqlite3_malloc()] before it returns.
4050**
4051** ^The sqlite3_result_value() interface sets the result of
4052** the application-defined function to be a copy the
4053** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4054** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4055** so that the [sqlite3_value] specified in the parameter may change or
4056** be deallocated after sqlite3_result_value() returns without harm.
4057** ^A [protected sqlite3_value] object may always be used where an
4058** [unprotected sqlite3_value] object is required, so either
4059** kind of [sqlite3_value] object can be used with this interface.
4060**
4061** If these routines are called from within the different thread
4062** than the one containing the application-defined function that received
4063** the [sqlite3_context] pointer, the results are undefined.
4064*/
4065SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4066SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4067SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4068SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4069SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4070SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4071SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4072SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4073SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4074SQLITE_API void sqlite3_result_null(sqlite3_context*);
4075SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4076SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4077SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4078SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4079SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4080SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4081
4082/*
4083** CAPI3REF: Define New Collating Sequences
4084**
4085** These functions are used to add new collation sequences to the
4086** [database connection] specified as the first argument.
4087**
4088** ^The name of the new collation sequence is specified as a UTF-8 string
4089** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4090** and a UTF-16 string for sqlite3_create_collation16(). ^In all cases
4091** the name is passed as the second function argument.
4092**
4093** ^The third argument may be one of the constants [SQLITE_UTF8],
4094** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied
4095** routine expects to be passed pointers to strings encoded using UTF-8,
4096** UTF-16 little-endian, or UTF-16 big-endian, respectively. ^The
4097** third argument might also be [SQLITE_UTF16] to indicate that the routine
4098** expects pointers to be UTF-16 strings in the native byte order, or the
4099** argument can be [SQLITE_UTF16_ALIGNED] if the
4100** the routine expects pointers to 16-bit word aligned strings
4101** of UTF-16 in the native byte order.
4102**
4103** A pointer to the user supplied routine must be passed as the fifth
4104** argument.  ^If it is NULL, this is the same as deleting the collation
4105** sequence (so that SQLite cannot call it anymore).
4106** ^Each time the application supplied function is invoked, it is passed
4107** as its first parameter a copy of the void* passed as the fourth argument
4108** to sqlite3_create_collation() or sqlite3_create_collation16().
4109**
4110** ^The remaining arguments to the application-supplied routine are two strings,
4111** each represented by a (length, data) pair and encoded in the encoding
4112** that was passed as the third argument when the collation sequence was
4113** registered.  The application defined collation routine should
4114** return negative, zero or positive if the first string is less than,
4115** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
4116**
4117** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4118** except that it takes an extra argument which is a destructor for
4119** the collation.  ^The destructor is called when the collation is
4120** destroyed and is passed a copy of the fourth parameter void* pointer
4121** of the sqlite3_create_collation_v2().
4122** ^Collations are destroyed when they are overridden by later calls to the
4123** collation creation functions or when the [database connection] is closed
4124** using [sqlite3_close()].
4125**
4126** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4127*/
4128SQLITE_API int sqlite3_create_collation(
4129  sqlite3*,
4130  const char *zName,
4131  int eTextRep,
4132  void*,
4133  int(*xCompare)(void*,int,const void*,int,const void*)
4134);
4135SQLITE_API int sqlite3_create_collation_v2(
4136  sqlite3*,
4137  const char *zName,
4138  int eTextRep,
4139  void*,
4140  int(*xCompare)(void*,int,const void*,int,const void*),
4141  void(*xDestroy)(void*)
4142);
4143SQLITE_API int sqlite3_create_collation16(
4144  sqlite3*,
4145  const void *zName,
4146  int eTextRep,
4147  void*,
4148  int(*xCompare)(void*,int,const void*,int,const void*)
4149);
4150
4151/*
4152** CAPI3REF: Collation Needed Callbacks
4153**
4154** ^To avoid having to register all collation sequences before a database
4155** can be used, a single callback function may be registered with the
4156** [database connection] to be invoked whenever an undefined collation
4157** sequence is required.
4158**
4159** ^If the function is registered using the sqlite3_collation_needed() API,
4160** then it is passed the names of undefined collation sequences as strings
4161** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4162** the names are passed as UTF-16 in machine native byte order.
4163** ^A call to either function replaces the existing collation-needed callback.
4164**
4165** ^(When the callback is invoked, the first argument passed is a copy
4166** of the second argument to sqlite3_collation_needed() or
4167** sqlite3_collation_needed16().  The second argument is the database
4168** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4169** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4170** sequence function required.  The fourth parameter is the name of the
4171** required collation sequence.)^
4172**
4173** The callback function should register the desired collation using
4174** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4175** [sqlite3_create_collation_v2()].
4176*/
4177SQLITE_API int sqlite3_collation_needed(
4178  sqlite3*,
4179  void*,
4180  void(*)(void*,sqlite3*,int eTextRep,const char*)
4181);
4182SQLITE_API int sqlite3_collation_needed16(
4183  sqlite3*,
4184  void*,
4185  void(*)(void*,sqlite3*,int eTextRep,const void*)
4186);
4187
4188/*
4189** Specify the key for an encrypted database.  This routine should be
4190** called right after sqlite3_open().
4191**
4192** The code to implement this API is not available in the public release
4193** of SQLite.
4194*/
4195SQLITE_API int sqlite3_key(
4196  sqlite3 *db,                   /* Database to be rekeyed */
4197  const void *pKey, int nKey     /* The key */
4198);
4199
4200/*
4201** Change the key on an open database.  If the current database is not
4202** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4203** database is decrypted.
4204**
4205** The code to implement this API is not available in the public release
4206** of SQLite.
4207*/
4208SQLITE_API int sqlite3_rekey(
4209  sqlite3 *db,                   /* Database to be rekeyed */
4210  const void *pKey, int nKey     /* The new key */
4211);
4212
4213/*
4214** CAPI3REF: Suspend Execution For A Short Time
4215**
4216** ^The sqlite3_sleep() function causes the current thread to suspend execution
4217** for at least a number of milliseconds specified in its parameter.
4218**
4219** ^If the operating system does not support sleep requests with
4220** millisecond time resolution, then the time will be rounded up to
4221** the nearest second. ^The number of milliseconds of sleep actually
4222** requested from the operating system is returned.
4223**
4224** ^SQLite implements this interface by calling the xSleep()
4225** method of the default [sqlite3_vfs] object.
4226*/
4227SQLITE_API int sqlite3_sleep(int);
4228
4229/*
4230** CAPI3REF: Name Of The Folder Holding Temporary Files
4231**
4232** ^(If this global variable is made to point to a string which is
4233** the name of a folder (a.k.a. directory), then all temporary files
4234** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4235** will be placed in that directory.)^  ^If this variable
4236** is a NULL pointer, then SQLite performs a search for an appropriate
4237** temporary file directory.
4238**
4239** It is not safe to read or modify this variable in more than one
4240** thread at a time.  It is not safe to read or modify this variable
4241** if a [database connection] is being used at the same time in a separate
4242** thread.
4243** It is intended that this variable be set once
4244** as part of process initialization and before any SQLite interface
4245** routines have been called and that this variable remain unchanged
4246** thereafter.
4247**
4248** ^The [temp_store_directory pragma] may modify this variable and cause
4249** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4250** the [temp_store_directory pragma] always assumes that any string
4251** that this variable points to is held in memory obtained from
4252** [sqlite3_malloc] and the pragma may attempt to free that memory
4253** using [sqlite3_free].
4254** Hence, if this variable is modified directly, either it should be
4255** made NULL or made to point to memory obtained from [sqlite3_malloc]
4256** or else the use of the [temp_store_directory pragma] should be avoided.
4257*/
4258SQLITE_API char *sqlite3_temp_directory;
4259
4260/*
4261** CAPI3REF: Test For Auto-Commit Mode
4262** KEYWORDS: {autocommit mode}
4263**
4264** ^The sqlite3_get_autocommit() interface returns non-zero or
4265** zero if the given database connection is or is not in autocommit mode,
4266** respectively.  ^Autocommit mode is on by default.
4267** ^Autocommit mode is disabled by a [BEGIN] statement.
4268** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4269**
4270** If certain kinds of errors occur on a statement within a multi-statement
4271** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4272** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4273** transaction might be rolled back automatically.  The only way to
4274** find out whether SQLite automatically rolled back the transaction after
4275** an error is to use this function.
4276**
4277** If another thread changes the autocommit status of the database
4278** connection while this routine is running, then the return value
4279** is undefined.
4280*/
4281SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4282
4283/*
4284** CAPI3REF: Find The Database Handle Of A Prepared Statement
4285**
4286** ^The sqlite3_db_handle interface returns the [database connection] handle
4287** to which a [prepared statement] belongs.  ^The [database connection]
4288** returned by sqlite3_db_handle is the same [database connection]
4289** that was the first argument
4290** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4291** create the statement in the first place.
4292*/
4293SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4294
4295/*
4296** CAPI3REF: Find the next prepared statement
4297**
4298** ^This interface returns a pointer to the next [prepared statement] after
4299** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
4300** then this interface returns a pointer to the first prepared statement
4301** associated with the database connection pDb.  ^If no prepared statement
4302** satisfies the conditions of this routine, it returns NULL.
4303**
4304** The [database connection] pointer D in a call to
4305** [sqlite3_next_stmt(D,S)] must refer to an open database
4306** connection and in particular must not be a NULL pointer.
4307*/
4308SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
4309
4310/*
4311** CAPI3REF: Commit And Rollback Notification Callbacks
4312**
4313** ^The sqlite3_commit_hook() interface registers a callback
4314** function to be invoked whenever a transaction is [COMMIT | committed].
4315** ^Any callback set by a previous call to sqlite3_commit_hook()
4316** for the same database connection is overridden.
4317** ^The sqlite3_rollback_hook() interface registers a callback
4318** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4319** ^Any callback set by a previous call to sqlite3_rollback_hook()
4320** for the same database connection is overridden.
4321** ^The pArg argument is passed through to the callback.
4322** ^If the callback on a commit hook function returns non-zero,
4323** then the commit is converted into a rollback.
4324**
4325** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
4326** return the P argument from the previous call of the same function
4327** on the same [database connection] D, or NULL for
4328** the first call for each function on D.
4329**
4330** The callback implementation must not do anything that will modify
4331** the database connection that invoked the callback.  Any actions
4332** to modify the database connection must be deferred until after the
4333** completion of the [sqlite3_step()] call that triggered the commit
4334** or rollback hook in the first place.
4335** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4336** database connections for the meaning of "modify" in this paragraph.
4337**
4338** ^Registering a NULL function disables the callback.
4339**
4340** ^When the commit hook callback routine returns zero, the [COMMIT]
4341** operation is allowed to continue normally.  ^If the commit hook
4342** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4343** ^The rollback hook is invoked on a rollback that results from a commit
4344** hook returning non-zero, just as it would be with any other rollback.
4345**
4346** ^For the purposes of this API, a transaction is said to have been
4347** rolled back if an explicit "ROLLBACK" statement is executed, or
4348** an error or constraint causes an implicit rollback to occur.
4349** ^The rollback callback is not invoked if a transaction is
4350** automatically rolled back because the database connection is closed.
4351** ^The rollback callback is not invoked if a transaction is
4352** rolled back because a commit callback returned non-zero.
4353**
4354** See also the [sqlite3_update_hook()] interface.
4355*/
4356SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4357SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4358
4359/*
4360** CAPI3REF: Data Change Notification Callbacks
4361**
4362** ^The sqlite3_update_hook() interface registers a callback function
4363** with the [database connection] identified by the first argument
4364** to be invoked whenever a row is updated, inserted or deleted.
4365** ^Any callback set by a previous call to this function
4366** for the same database connection is overridden.
4367**
4368** ^The second argument is a pointer to the function to invoke when a
4369** row is updated, inserted or deleted.
4370** ^The first argument to the callback is a copy of the third argument
4371** to sqlite3_update_hook().
4372** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
4373** or [SQLITE_UPDATE], depending on the operation that caused the callback
4374** to be invoked.
4375** ^The third and fourth arguments to the callback contain pointers to the
4376** database and table name containing the affected row.
4377** ^The final callback parameter is the [rowid] of the row.
4378** ^In the case of an update, this is the [rowid] after the update takes place.
4379**
4380** ^(The update hook is not invoked when internal system tables are
4381** modified (i.e. sqlite_master and sqlite_sequence).)^
4382**
4383** ^In the current implementation, the update hook
4384** is not invoked when duplication rows are deleted because of an
4385** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
4386** invoked when rows are deleted using the [truncate optimization].
4387** The exceptions defined in this paragraph might change in a future
4388** release of SQLite.
4389**
4390** The update hook implementation must not do anything that will modify
4391** the database connection that invoked the update hook.  Any actions
4392** to modify the database connection must be deferred until after the
4393** completion of the [sqlite3_step()] call that triggered the update hook.
4394** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4395** database connections for the meaning of "modify" in this paragraph.
4396**
4397** ^The sqlite3_update_hook(D,C,P) function
4398** returns the P argument from the previous call
4399** on the same [database connection] D, or NULL for
4400** the first call on D.
4401**
4402** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
4403** interfaces.
4404*/
4405SQLITE_API void *sqlite3_update_hook(
4406  sqlite3*,
4407  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
4408  void*
4409);
4410
4411/*
4412** CAPI3REF: Enable Or Disable Shared Pager Cache
4413** KEYWORDS: {shared cache}
4414**
4415** ^(This routine enables or disables the sharing of the database cache
4416** and schema data structures between [database connection | connections]
4417** to the same database. Sharing is enabled if the argument is true
4418** and disabled if the argument is false.)^
4419**
4420** ^Cache sharing is enabled and disabled for an entire process.
4421** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
4422** sharing was enabled or disabled for each thread separately.
4423**
4424** ^(The cache sharing mode set by this interface effects all subsequent
4425** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
4426** Existing database connections continue use the sharing mode
4427** that was in effect at the time they were opened.)^
4428**
4429** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
4430** successfully.  An [error code] is returned otherwise.)^
4431**
4432** ^Shared cache is disabled by default. But this might change in
4433** future releases of SQLite.  Applications that care about shared
4434** cache setting should set it explicitly.
4435**
4436** See Also:  [SQLite Shared-Cache Mode]
4437*/
4438SQLITE_API int sqlite3_enable_shared_cache(int);
4439
4440/*
4441** CAPI3REF: Attempt To Free Heap Memory
4442**
4443** ^The sqlite3_release_memory() interface attempts to free N bytes
4444** of heap memory by deallocating non-essential memory allocations
4445** held by the database library.   Memory used to cache database
4446** pages to improve performance is an example of non-essential memory.
4447** ^sqlite3_release_memory() returns the number of bytes actually freed,
4448** which might be more or less than the amount requested.
4449*/
4450SQLITE_API int sqlite3_release_memory(int);
4451
4452/*
4453** CAPI3REF: Impose A Limit On Heap Size
4454**
4455** ^The sqlite3_soft_heap_limit() interface places a "soft" limit
4456** on the amount of heap memory that may be allocated by SQLite.
4457** ^If an internal allocation is requested that would exceed the
4458** soft heap limit, [sqlite3_release_memory()] is invoked one or
4459** more times to free up some space before the allocation is performed.
4460**
4461** ^The limit is called "soft" because if [sqlite3_release_memory()]
4462** cannot free sufficient memory to prevent the limit from being exceeded,
4463** the memory is allocated anyway and the current operation proceeds.
4464**
4465** ^A negative or zero value for N means that there is no soft heap limit and
4466** [sqlite3_release_memory()] will only be called when memory is exhausted.
4467** ^The default value for the soft heap limit is zero.
4468**
4469** ^(SQLite makes a best effort to honor the soft heap limit.
4470** But if the soft heap limit cannot be honored, execution will
4471** continue without error or notification.)^  This is why the limit is
4472** called a "soft" limit.  It is advisory only.
4473**
4474** Prior to SQLite version 3.5.0, this routine only constrained the memory
4475** allocated by a single thread - the same thread in which this routine
4476** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
4477** applied to all threads. The value specified for the soft heap limit
4478** is an upper bound on the total memory allocation for all threads. In
4479** version 3.5.0 there is no mechanism for limiting the heap usage for
4480** individual threads.
4481*/
4482SQLITE_API void sqlite3_soft_heap_limit(int);
4483
4484/*
4485** CAPI3REF: Extract Metadata About A Column Of A Table
4486**
4487** ^This routine returns metadata about a specific column of a specific
4488** database table accessible using the [database connection] handle
4489** passed as the first function argument.
4490**
4491** ^The column is identified by the second, third and fourth parameters to
4492** this function. ^The second parameter is either the name of the database
4493** (i.e. "main", "temp", or an attached database) containing the specified
4494** table or NULL. ^If it is NULL, then all attached databases are searched
4495** for the table using the same algorithm used by the database engine to
4496** resolve unqualified table references.
4497**
4498** ^The third and fourth parameters to this function are the table and column
4499** name of the desired column, respectively. Neither of these parameters
4500** may be NULL.
4501**
4502** ^Metadata is returned by writing to the memory locations passed as the 5th
4503** and subsequent parameters to this function. ^Any of these arguments may be
4504** NULL, in which case the corresponding element of metadata is omitted.
4505**
4506** ^(<blockquote>
4507** <table border="1">
4508** <tr><th> Parameter <th> Output<br>Type <th>  Description
4509**
4510** <tr><td> 5th <td> const char* <td> Data type
4511** <tr><td> 6th <td> const char* <td> Name of default collation sequence
4512** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
4513** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
4514** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
4515** </table>
4516** </blockquote>)^
4517**
4518** ^The memory pointed to by the character pointers returned for the
4519** declaration type and collation sequence is valid only until the next
4520** call to any SQLite API function.
4521**
4522** ^If the specified table is actually a view, an [error code] is returned.
4523**
4524** ^If the specified column is "rowid", "oid" or "_rowid_" and an
4525** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
4526** parameters are set for the explicitly declared column. ^(If there is no
4527** explicitly declared [INTEGER PRIMARY KEY] column, then the output
4528** parameters are set as follows:
4529**
4530** <pre>
4531**     data type: "INTEGER"
4532**     collation sequence: "BINARY"
4533**     not null: 0
4534**     primary key: 1
4535**     auto increment: 0
4536** </pre>)^
4537**
4538** ^(This function may load one or more schemas from database files. If an
4539** error occurs during this process, or if the requested table or column
4540** cannot be found, an [error code] is returned and an error message left
4541** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
4542**
4543** ^This API is only available if the library was compiled with the
4544** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
4545*/
4546SQLITE_API int sqlite3_table_column_metadata(
4547  sqlite3 *db,                /* Connection handle */
4548  const char *zDbName,        /* Database name or NULL */
4549  const char *zTableName,     /* Table name */
4550  const char *zColumnName,    /* Column name */
4551  char const **pzDataType,    /* OUTPUT: Declared data type */
4552  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
4553  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
4554  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
4555  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
4556);
4557
4558/*
4559** CAPI3REF: Load An Extension
4560**
4561** ^This interface loads an SQLite extension library from the named file.
4562**
4563** ^The sqlite3_load_extension() interface attempts to load an
4564** SQLite extension library contained in the file zFile.
4565**
4566** ^The entry point is zProc.
4567** ^zProc may be 0, in which case the name of the entry point
4568** defaults to "sqlite3_extension_init".
4569** ^The sqlite3_load_extension() interface returns
4570** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
4571** ^If an error occurs and pzErrMsg is not 0, then the
4572** [sqlite3_load_extension()] interface shall attempt to
4573** fill *pzErrMsg with error message text stored in memory
4574** obtained from [sqlite3_malloc()]. The calling function
4575** should free this memory by calling [sqlite3_free()].
4576**
4577** ^Extension loading must be enabled using
4578** [sqlite3_enable_load_extension()] prior to calling this API,
4579** otherwise an error will be returned.
4580**
4581** See also the [load_extension() SQL function].
4582*/
4583SQLITE_API int sqlite3_load_extension(
4584  sqlite3 *db,          /* Load the extension into this database connection */
4585  const char *zFile,    /* Name of the shared library containing extension */
4586  const char *zProc,    /* Entry point.  Derived from zFile if 0 */
4587  char **pzErrMsg       /* Put error message here if not 0 */
4588);
4589
4590/*
4591** CAPI3REF: Enable Or Disable Extension Loading
4592**
4593** ^So as not to open security holes in older applications that are
4594** unprepared to deal with extension loading, and as a means of disabling
4595** extension loading while evaluating user-entered SQL, the following API
4596** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
4597**
4598** ^Extension loading is off by default. See ticket #1863.
4599** ^Call the sqlite3_enable_load_extension() routine with onoff==1
4600** to turn extension loading on and call it with onoff==0 to turn
4601** it back off again.
4602*/
4603SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
4604
4605/*
4606** CAPI3REF: Automatically Load An Extensions
4607**
4608** ^This API can be invoked at program startup in order to register
4609** one or more statically linked extensions that will be available
4610** to all new [database connections].
4611**
4612** ^(This routine stores a pointer to the extension entry point
4613** in an array that is obtained from [sqlite3_malloc()].  That memory
4614** is deallocated by [sqlite3_reset_auto_extension()].)^
4615**
4616** ^This function registers an extension entry point that is
4617** automatically invoked whenever a new [database connection]
4618** is opened using [sqlite3_open()], [sqlite3_open16()],
4619** or [sqlite3_open_v2()].
4620** ^Duplicate extensions are detected so calling this routine
4621** multiple times with the same extension is harmless.
4622** ^Automatic extensions apply across all threads.
4623*/
4624SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
4625
4626/*
4627** CAPI3REF: Reset Automatic Extension Loading
4628**
4629** ^(This function disables all previously registered automatic
4630** extensions. It undoes the effect of all prior
4631** [sqlite3_auto_extension()] calls.)^
4632**
4633** ^This function disables automatic extensions in all threads.
4634*/
4635SQLITE_API void sqlite3_reset_auto_extension(void);
4636
4637/*
4638****** EXPERIMENTAL - subject to change without notice **************
4639**
4640** The interface to the virtual-table mechanism is currently considered
4641** to be experimental.  The interface might change in incompatible ways.
4642** If this is a problem for you, do not use the interface at this time.
4643**
4644** When the virtual-table mechanism stabilizes, we will declare the
4645** interface fixed, support it indefinitely, and remove this comment.
4646*/
4647
4648/*
4649** Structures used by the virtual table interface
4650*/
4651typedef struct sqlite3_vtab sqlite3_vtab;
4652typedef struct sqlite3_index_info sqlite3_index_info;
4653typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
4654typedef struct sqlite3_module sqlite3_module;
4655
4656/*
4657** CAPI3REF: Virtual Table Object
4658** KEYWORDS: sqlite3_module {virtual table module}
4659** EXPERIMENTAL
4660**
4661** This structure, sometimes called a a "virtual table module",
4662** defines the implementation of a [virtual tables].
4663** This structure consists mostly of methods for the module.
4664**
4665** ^A virtual table module is created by filling in a persistent
4666** instance of this structure and passing a pointer to that instance
4667** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
4668** ^The registration remains valid until it is replaced by a different
4669** module or until the [database connection] closes.  The content
4670** of this structure must not change while it is registered with
4671** any database connection.
4672*/
4673struct sqlite3_module {
4674  int iVersion;
4675  int (*xCreate)(sqlite3*, void *pAux,
4676               int argc, const char *const*argv,
4677               sqlite3_vtab **ppVTab, char**);
4678  int (*xConnect)(sqlite3*, void *pAux,
4679               int argc, const char *const*argv,
4680               sqlite3_vtab **ppVTab, char**);
4681  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
4682  int (*xDisconnect)(sqlite3_vtab *pVTab);
4683  int (*xDestroy)(sqlite3_vtab *pVTab);
4684  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
4685  int (*xClose)(sqlite3_vtab_cursor*);
4686  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
4687                int argc, sqlite3_value **argv);
4688  int (*xNext)(sqlite3_vtab_cursor*);
4689  int (*xEof)(sqlite3_vtab_cursor*);
4690  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
4691  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
4692  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
4693  int (*xBegin)(sqlite3_vtab *pVTab);
4694  int (*xSync)(sqlite3_vtab *pVTab);
4695  int (*xCommit)(sqlite3_vtab *pVTab);
4696  int (*xRollback)(sqlite3_vtab *pVTab);
4697  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
4698                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
4699                       void **ppArg);
4700  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
4701};
4702
4703/*
4704** CAPI3REF: Virtual Table Indexing Information
4705** KEYWORDS: sqlite3_index_info
4706** EXPERIMENTAL
4707**
4708** The sqlite3_index_info structure and its substructures is used to
4709** pass information into and receive the reply from the [xBestIndex]
4710** method of a [virtual table module].  The fields under **Inputs** are the
4711** inputs to xBestIndex and are read-only.  xBestIndex inserts its
4712** results into the **Outputs** fields.
4713**
4714** ^(The aConstraint[] array records WHERE clause constraints of the form:
4715**
4716** <pre>column OP expr</pre>
4717**
4718** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
4719** stored in aConstraint[].op.)^  ^(The index of the column is stored in
4720** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
4721** expr on the right-hand side can be evaluated (and thus the constraint
4722** is usable) and false if it cannot.)^
4723**
4724** ^The optimizer automatically inverts terms of the form "expr OP column"
4725** and makes other simplifications to the WHERE clause in an attempt to
4726** get as many WHERE clause terms into the form shown above as possible.
4727** ^The aConstraint[] array only reports WHERE clause terms that are
4728** relevant to the particular virtual table being queried.
4729**
4730** ^Information about the ORDER BY clause is stored in aOrderBy[].
4731** ^Each term of aOrderBy records a column of the ORDER BY clause.
4732**
4733** The [xBestIndex] method must fill aConstraintUsage[] with information
4734** about what parameters to pass to xFilter.  ^If argvIndex>0 then
4735** the right-hand side of the corresponding aConstraint[] is evaluated
4736** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
4737** is true, then the constraint is assumed to be fully handled by the
4738** virtual table and is not checked again by SQLite.)^
4739**
4740** ^The idxNum and idxPtr values are recorded and passed into the
4741** [xFilter] method.
4742** ^[sqlite3_free()] is used to free idxPtr if and only if
4743** needToFreeIdxPtr is true.
4744**
4745** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
4746** the correct order to satisfy the ORDER BY clause so that no separate
4747** sorting step is required.
4748**
4749** ^The estimatedCost value is an estimate of the cost of doing the
4750** particular lookup.  A full scan of a table with N entries should have
4751** a cost of N.  A binary search of a table of N entries should have a
4752** cost of approximately log(N).
4753*/
4754struct sqlite3_index_info {
4755  /* Inputs */
4756  int nConstraint;           /* Number of entries in aConstraint */
4757  struct sqlite3_index_constraint {
4758     int iColumn;              /* Column on left-hand side of constraint */
4759     unsigned char op;         /* Constraint operator */
4760     unsigned char usable;     /* True if this constraint is usable */
4761     int iTermOffset;          /* Used internally - xBestIndex should ignore */
4762  } *aConstraint;            /* Table of WHERE clause constraints */
4763  int nOrderBy;              /* Number of terms in the ORDER BY clause */
4764  struct sqlite3_index_orderby {
4765     int iColumn;              /* Column number */
4766     unsigned char desc;       /* True for DESC.  False for ASC. */
4767  } *aOrderBy;               /* The ORDER BY clause */
4768  /* Outputs */
4769  struct sqlite3_index_constraint_usage {
4770    int argvIndex;           /* if >0, constraint is part of argv to xFilter */
4771    unsigned char omit;      /* Do not code a test for this constraint */
4772  } *aConstraintUsage;
4773  int idxNum;                /* Number used to identify the index */
4774  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
4775  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
4776  int orderByConsumed;       /* True if output is already ordered */
4777  double estimatedCost;      /* Estimated cost of using this index */
4778};
4779#define SQLITE_INDEX_CONSTRAINT_EQ    2
4780#define SQLITE_INDEX_CONSTRAINT_GT    4
4781#define SQLITE_INDEX_CONSTRAINT_LE    8
4782#define SQLITE_INDEX_CONSTRAINT_LT    16
4783#define SQLITE_INDEX_CONSTRAINT_GE    32
4784#define SQLITE_INDEX_CONSTRAINT_MATCH 64
4785
4786/*
4787** CAPI3REF: Register A Virtual Table Implementation
4788** EXPERIMENTAL
4789**
4790** ^These routines are used to register a new [virtual table module] name.
4791** ^Module names must be registered before
4792** creating a new [virtual table] using the module and before using a
4793** preexisting [virtual table] for the module.
4794**
4795** ^The module name is registered on the [database connection] specified
4796** by the first parameter.  ^The name of the module is given by the
4797** second parameter.  ^The third parameter is a pointer to
4798** the implementation of the [virtual table module].   ^The fourth
4799** parameter is an arbitrary client data pointer that is passed through
4800** into the [xCreate] and [xConnect] methods of the virtual table module
4801** when a new virtual table is be being created or reinitialized.
4802**
4803** ^The sqlite3_create_module_v2() interface has a fifth parameter which
4804** is a pointer to a destructor for the pClientData.  ^SQLite will
4805** invoke the destructor function (if it is not NULL) when SQLite
4806** no longer needs the pClientData pointer.  ^The sqlite3_create_module()
4807** interface is equivalent to sqlite3_create_module_v2() with a NULL
4808** destructor.
4809*/
4810SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module(
4811  sqlite3 *db,               /* SQLite connection to register module with */
4812  const char *zName,         /* Name of the module */
4813  const sqlite3_module *p,   /* Methods for the module */
4814  void *pClientData          /* Client data for xCreate/xConnect */
4815);
4816SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
4817  sqlite3 *db,               /* SQLite connection to register module with */
4818  const char *zName,         /* Name of the module */
4819  const sqlite3_module *p,   /* Methods for the module */
4820  void *pClientData,         /* Client data for xCreate/xConnect */
4821  void(*xDestroy)(void*)     /* Module destructor function */
4822);
4823
4824/*
4825** CAPI3REF: Virtual Table Instance Object
4826** KEYWORDS: sqlite3_vtab
4827** EXPERIMENTAL
4828**
4829** Every [virtual table module] implementation uses a subclass
4830** of this object to describe a particular instance
4831** of the [virtual table].  Each subclass will
4832** be tailored to the specific needs of the module implementation.
4833** The purpose of this superclass is to define certain fields that are
4834** common to all module implementations.
4835**
4836** ^Virtual tables methods can set an error message by assigning a
4837** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
4838** take care that any prior string is freed by a call to [sqlite3_free()]
4839** prior to assigning a new string to zErrMsg.  ^After the error message
4840** is delivered up to the client application, the string will be automatically
4841** freed by sqlite3_free() and the zErrMsg field will be zeroed.
4842*/
4843struct sqlite3_vtab {
4844  const sqlite3_module *pModule;  /* The module for this virtual table */
4845  int nRef;                       /* NO LONGER USED */
4846  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
4847  /* Virtual table implementations will typically add additional fields */
4848};
4849
4850/*
4851** CAPI3REF: Virtual Table Cursor Object
4852** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
4853** EXPERIMENTAL
4854**
4855** Every [virtual table module] implementation uses a subclass of the
4856** following structure to describe cursors that point into the
4857** [virtual table] and are used
4858** to loop through the virtual table.  Cursors are created using the
4859** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
4860** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
4861** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
4862** of the module.  Each module implementation will define
4863** the content of a cursor structure to suit its own needs.
4864**
4865** This superclass exists in order to define fields of the cursor that
4866** are common to all implementations.
4867*/
4868struct sqlite3_vtab_cursor {
4869  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
4870  /* Virtual table implementations will typically add additional fields */
4871};
4872
4873/*
4874** CAPI3REF: Declare The Schema Of A Virtual Table
4875** EXPERIMENTAL
4876**
4877** ^The [xCreate] and [xConnect] methods of a
4878** [virtual table module] call this interface
4879** to declare the format (the names and datatypes of the columns) of
4880** the virtual tables they implement.
4881*/
4882SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
4883
4884/*
4885** CAPI3REF: Overload A Function For A Virtual Table
4886** EXPERIMENTAL
4887**
4888** ^(Virtual tables can provide alternative implementations of functions
4889** using the [xFindFunction] method of the [virtual table module].
4890** But global versions of those functions
4891** must exist in order to be overloaded.)^
4892**
4893** ^(This API makes sure a global version of a function with a particular
4894** name and number of parameters exists.  If no such function exists
4895** before this API is called, a new function is created.)^  ^The implementation
4896** of the new function always causes an exception to be thrown.  So
4897** the new function is not good for anything by itself.  Its only
4898** purpose is to be a placeholder function that can be overloaded
4899** by a [virtual table].
4900*/
4901SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
4902
4903/*
4904** The interface to the virtual-table mechanism defined above (back up
4905** to a comment remarkably similar to this one) is currently considered
4906** to be experimental.  The interface might change in incompatible ways.
4907** If this is a problem for you, do not use the interface at this time.
4908**
4909** When the virtual-table mechanism stabilizes, we will declare the
4910** interface fixed, support it indefinitely, and remove this comment.
4911**
4912****** EXPERIMENTAL - subject to change without notice **************
4913*/
4914
4915/*
4916** CAPI3REF: A Handle To An Open BLOB
4917** KEYWORDS: {BLOB handle} {BLOB handles}
4918**
4919** An instance of this object represents an open BLOB on which
4920** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
4921** ^Objects of this type are created by [sqlite3_blob_open()]
4922** and destroyed by [sqlite3_blob_close()].
4923** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
4924** can be used to read or write small subsections of the BLOB.
4925** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
4926*/
4927typedef struct sqlite3_blob sqlite3_blob;
4928
4929/*
4930** CAPI3REF: Open A BLOB For Incremental I/O
4931**
4932** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
4933** in row iRow, column zColumn, table zTable in database zDb;
4934** in other words, the same BLOB that would be selected by:
4935**
4936** <pre>
4937**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
4938** </pre>)^
4939**
4940** ^If the flags parameter is non-zero, then the BLOB is opened for read
4941** and write access. ^If it is zero, the BLOB is opened for read access.
4942** ^It is not possible to open a column that is part of an index or primary
4943** key for writing. ^If [foreign key constraints] are enabled, it is
4944** not possible to open a column that is part of a [child key] for writing.
4945**
4946** ^Note that the database name is not the filename that contains
4947** the database but rather the symbolic name of the database that
4948** appears after the AS keyword when the database is connected using [ATTACH].
4949** ^For the main database file, the database name is "main".
4950** ^For TEMP tables, the database name is "temp".
4951**
4952** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
4953** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
4954** to be a null pointer.)^
4955** ^This function sets the [database connection] error code and message
4956** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
4957** functions. ^Note that the *ppBlob variable is always initialized in a
4958** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
4959** regardless of the success or failure of this routine.
4960**
4961** ^(If the row that a BLOB handle points to is modified by an
4962** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
4963** then the BLOB handle is marked as "expired".
4964** This is true if any column of the row is changed, even a column
4965** other than the one the BLOB handle is open on.)^
4966** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
4967** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
4968** ^(Changes written into a BLOB prior to the BLOB expiring are not
4969** rolled back by the expiration of the BLOB.  Such changes will eventually
4970** commit if the transaction continues to completion.)^
4971**
4972** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
4973** the opened blob.  ^The size of a blob may not be changed by this
4974** interface.  Use the [UPDATE] SQL command to change the size of a
4975** blob.
4976**
4977** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
4978** and the built-in [zeroblob] SQL function can be used, if desired,
4979** to create an empty, zero-filled blob in which to read or write using
4980** this interface.
4981**
4982** To avoid a resource leak, every open [BLOB handle] should eventually
4983** be released by a call to [sqlite3_blob_close()].
4984*/
4985SQLITE_API int sqlite3_blob_open(
4986  sqlite3*,
4987  const char *zDb,
4988  const char *zTable,
4989  const char *zColumn,
4990  sqlite3_int64 iRow,
4991  int flags,
4992  sqlite3_blob **ppBlob
4993);
4994
4995/*
4996** CAPI3REF: Close A BLOB Handle
4997**
4998** ^Closes an open [BLOB handle].
4999**
5000** ^Closing a BLOB shall cause the current transaction to commit
5001** if there are no other BLOBs, no pending prepared statements, and the
5002** database connection is in [autocommit mode].
5003** ^If any writes were made to the BLOB, they might be held in cache
5004** until the close operation if they will fit.
5005**
5006** ^(Closing the BLOB often forces the changes
5007** out to disk and so if any I/O errors occur, they will likely occur
5008** at the time when the BLOB is closed.  Any errors that occur during
5009** closing are reported as a non-zero return value.)^
5010**
5011** ^(The BLOB is closed unconditionally.  Even if this routine returns
5012** an error code, the BLOB is still closed.)^
5013**
5014** ^Calling this routine with a null pointer (such as would be returned
5015** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5016*/
5017SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5018
5019/*
5020** CAPI3REF: Return The Size Of An Open BLOB
5021**
5022** ^Returns the size in bytes of the BLOB accessible via the
5023** successfully opened [BLOB handle] in its only argument.  ^The
5024** incremental blob I/O routines can only read or overwriting existing
5025** blob content; they cannot change the size of a blob.
5026**
5027** This routine only works on a [BLOB handle] which has been created
5028** by a prior successful call to [sqlite3_blob_open()] and which has not
5029** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5030** to this routine results in undefined and probably undesirable behavior.
5031*/
5032SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5033
5034/*
5035** CAPI3REF: Read Data From A BLOB Incrementally
5036**
5037** ^(This function is used to read data from an open [BLOB handle] into a
5038** caller-supplied buffer. N bytes of data are copied into buffer Z
5039** from the open BLOB, starting at offset iOffset.)^
5040**
5041** ^If offset iOffset is less than N bytes from the end of the BLOB,
5042** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5043** less than zero, [SQLITE_ERROR] is returned and no data is read.
5044** ^The size of the blob (and hence the maximum value of N+iOffset)
5045** can be determined using the [sqlite3_blob_bytes()] interface.
5046**
5047** ^An attempt to read from an expired [BLOB handle] fails with an
5048** error code of [SQLITE_ABORT].
5049**
5050** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5051** Otherwise, an [error code] or an [extended error code] is returned.)^
5052**
5053** This routine only works on a [BLOB handle] which has been created
5054** by a prior successful call to [sqlite3_blob_open()] and which has not
5055** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5056** to this routine results in undefined and probably undesirable behavior.
5057**
5058** See also: [sqlite3_blob_write()].
5059*/
5060SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5061
5062/*
5063** CAPI3REF: Write Data Into A BLOB Incrementally
5064**
5065** ^This function is used to write data into an open [BLOB handle] from a
5066** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5067** into the open BLOB, starting at offset iOffset.
5068**
5069** ^If the [BLOB handle] passed as the first argument was not opened for
5070** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5071** this function returns [SQLITE_READONLY].
5072**
5073** ^This function may only modify the contents of the BLOB; it is
5074** not possible to increase the size of a BLOB using this API.
5075** ^If offset iOffset is less than N bytes from the end of the BLOB,
5076** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5077** less than zero [SQLITE_ERROR] is returned and no data is written.
5078** The size of the BLOB (and hence the maximum value of N+iOffset)
5079** can be determined using the [sqlite3_blob_bytes()] interface.
5080**
5081** ^An attempt to write to an expired [BLOB handle] fails with an
5082** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5083** before the [BLOB handle] expired are not rolled back by the
5084** expiration of the handle, though of course those changes might
5085** have been overwritten by the statement that expired the BLOB handle
5086** or by other independent statements.
5087**
5088** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5089** Otherwise, an  [error code] or an [extended error code] is returned.)^
5090**
5091** This routine only works on a [BLOB handle] which has been created
5092** by a prior successful call to [sqlite3_blob_open()] and which has not
5093** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5094** to this routine results in undefined and probably undesirable behavior.
5095**
5096** See also: [sqlite3_blob_read()].
5097*/
5098SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5099
5100/*
5101** CAPI3REF: Virtual File System Objects
5102**
5103** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5104** that SQLite uses to interact
5105** with the underlying operating system.  Most SQLite builds come with a
5106** single default VFS that is appropriate for the host computer.
5107** New VFSes can be registered and existing VFSes can be unregistered.
5108** The following interfaces are provided.
5109**
5110** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5111** ^Names are case sensitive.
5112** ^Names are zero-terminated UTF-8 strings.
5113** ^If there is no match, a NULL pointer is returned.
5114** ^If zVfsName is NULL then the default VFS is returned.
5115**
5116** ^New VFSes are registered with sqlite3_vfs_register().
5117** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5118** ^The same VFS can be registered multiple times without injury.
5119** ^To make an existing VFS into the default VFS, register it again
5120** with the makeDflt flag set.  If two different VFSes with the
5121** same name are registered, the behavior is undefined.  If a
5122** VFS is registered with a name that is NULL or an empty string,
5123** then the behavior is undefined.
5124**
5125** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5126** ^(If the default VFS is unregistered, another VFS is chosen as
5127** the default.  The choice for the new VFS is arbitrary.)^
5128*/
5129SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5130SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5131SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5132
5133/*
5134** CAPI3REF: Mutexes
5135**
5136** The SQLite core uses these routines for thread
5137** synchronization. Though they are intended for internal
5138** use by SQLite, code that links against SQLite is
5139** permitted to use any of these routines.
5140**
5141** The SQLite source code contains multiple implementations
5142** of these mutex routines.  An appropriate implementation
5143** is selected automatically at compile-time.  ^(The following
5144** implementations are available in the SQLite core:
5145**
5146** <ul>
5147** <li>   SQLITE_MUTEX_OS2
5148** <li>   SQLITE_MUTEX_PTHREAD
5149** <li>   SQLITE_MUTEX_W32
5150** <li>   SQLITE_MUTEX_NOOP
5151** </ul>)^
5152**
5153** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
5154** that does no real locking and is appropriate for use in
5155** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
5156** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
5157** are appropriate for use on OS/2, Unix, and Windows.
5158**
5159** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5160** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5161** implementation is included with the library. In this case the
5162** application must supply a custom mutex implementation using the
5163** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
5164** before calling sqlite3_initialize() or any other public sqlite3_
5165** function that calls sqlite3_initialize().)^
5166**
5167** ^The sqlite3_mutex_alloc() routine allocates a new
5168** mutex and returns a pointer to it. ^If it returns NULL
5169** that means that a mutex could not be allocated.  ^SQLite
5170** will unwind its stack and return an error.  ^(The argument
5171** to sqlite3_mutex_alloc() is one of these integer constants:
5172**
5173** <ul>
5174** <li>  SQLITE_MUTEX_FAST
5175** <li>  SQLITE_MUTEX_RECURSIVE
5176** <li>  SQLITE_MUTEX_STATIC_MASTER
5177** <li>  SQLITE_MUTEX_STATIC_MEM
5178** <li>  SQLITE_MUTEX_STATIC_MEM2
5179** <li>  SQLITE_MUTEX_STATIC_PRNG
5180** <li>  SQLITE_MUTEX_STATIC_LRU
5181** <li>  SQLITE_MUTEX_STATIC_LRU2
5182** </ul>)^
5183**
5184** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
5185** cause sqlite3_mutex_alloc() to create
5186** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5187** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
5188** The mutex implementation does not need to make a distinction
5189** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5190** not want to.  ^SQLite will only request a recursive mutex in
5191** cases where it really needs one.  ^If a faster non-recursive mutex
5192** implementation is available on the host platform, the mutex subsystem
5193** might return such a mutex in response to SQLITE_MUTEX_FAST.
5194**
5195** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
5196** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
5197** a pointer to a static preexisting mutex.  ^Six static mutexes are
5198** used by the current version of SQLite.  Future versions of SQLite
5199** may add additional static mutexes.  Static mutexes are for internal
5200** use by SQLite only.  Applications that use SQLite mutexes should
5201** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5202** SQLITE_MUTEX_RECURSIVE.
5203**
5204** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5205** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5206** returns a different mutex on every call.  ^But for the static
5207** mutex types, the same mutex is returned on every call that has
5208** the same type number.
5209**
5210** ^The sqlite3_mutex_free() routine deallocates a previously
5211** allocated dynamic mutex.  ^SQLite is careful to deallocate every
5212** dynamic mutex that it allocates.  The dynamic mutexes must not be in
5213** use when they are deallocated.  Attempting to deallocate a static
5214** mutex results in undefined behavior.  ^SQLite never deallocates
5215** a static mutex.
5216**
5217** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5218** to enter a mutex.  ^If another thread is already within the mutex,
5219** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5220** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
5221** upon successful entry.  ^(Mutexes created using
5222** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5223** In such cases the,
5224** mutex must be exited an equal number of times before another thread
5225** can enter.)^  ^(If the same thread tries to enter any other
5226** kind of mutex more than once, the behavior is undefined.
5227** SQLite will never exhibit
5228** such behavior in its own use of mutexes.)^
5229**
5230** ^(Some systems (for example, Windows 95) do not support the operation
5231** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
5232** will always return SQLITE_BUSY.  The SQLite core only ever uses
5233** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
5234**
5235** ^The sqlite3_mutex_leave() routine exits a mutex that was
5236** previously entered by the same thread.   ^(The behavior
5237** is undefined if the mutex is not currently entered by the
5238** calling thread or is not currently allocated.  SQLite will
5239** never do either.)^
5240**
5241** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
5242** sqlite3_mutex_leave() is a NULL pointer, then all three routines
5243** behave as no-ops.
5244**
5245** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5246*/
5247SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5248SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5249SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5250SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5251SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5252
5253/*
5254** CAPI3REF: Mutex Methods Object
5255** EXPERIMENTAL
5256**
5257** An instance of this structure defines the low-level routines
5258** used to allocate and use mutexes.
5259**
5260** Usually, the default mutex implementations provided by SQLite are
5261** sufficient, however the user has the option of substituting a custom
5262** implementation for specialized deployments or systems for which SQLite
5263** does not provide a suitable implementation. In this case, the user
5264** creates and populates an instance of this structure to pass
5265** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
5266** Additionally, an instance of this structure can be used as an
5267** output variable when querying the system for the current mutex
5268** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5269**
5270** ^The xMutexInit method defined by this structure is invoked as
5271** part of system initialization by the sqlite3_initialize() function.
5272** ^The xMutexInit routine is calle by SQLite exactly once for each
5273** effective call to [sqlite3_initialize()].
5274**
5275** ^The xMutexEnd method defined by this structure is invoked as
5276** part of system shutdown by the sqlite3_shutdown() function. The
5277** implementation of this method is expected to release all outstanding
5278** resources obtained by the mutex methods implementation, especially
5279** those obtained by the xMutexInit method.  ^The xMutexEnd()
5280** interface is invoked exactly once for each call to [sqlite3_shutdown()].
5281**
5282** ^(The remaining seven methods defined by this structure (xMutexAlloc,
5283** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
5284** xMutexNotheld) implement the following interfaces (respectively):
5285**
5286** <ul>
5287**   <li>  [sqlite3_mutex_alloc()] </li>
5288**   <li>  [sqlite3_mutex_free()] </li>
5289**   <li>  [sqlite3_mutex_enter()] </li>
5290**   <li>  [sqlite3_mutex_try()] </li>
5291**   <li>  [sqlite3_mutex_leave()] </li>
5292**   <li>  [sqlite3_mutex_held()] </li>
5293**   <li>  [sqlite3_mutex_notheld()] </li>
5294** </ul>)^
5295**
5296** The only difference is that the public sqlite3_XXX functions enumerated
5297** above silently ignore any invocations that pass a NULL pointer instead
5298** of a valid mutex handle. The implementations of the methods defined
5299** by this structure are not required to handle this case, the results
5300** of passing a NULL pointer instead of a valid mutex handle are undefined
5301** (i.e. it is acceptable to provide an implementation that segfaults if
5302** it is passed a NULL pointer).
5303**
5304** The xMutexInit() method must be threadsafe.  ^It must be harmless to
5305** invoke xMutexInit() mutiple times within the same process and without
5306** intervening calls to xMutexEnd().  Second and subsequent calls to
5307** xMutexInit() must be no-ops.
5308**
5309** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
5310** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
5311** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
5312** memory allocation for a fast or recursive mutex.
5313**
5314** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
5315** called, but only if the prior call to xMutexInit returned SQLITE_OK.
5316** If xMutexInit fails in any way, it is expected to clean up after itself
5317** prior to returning.
5318*/
5319typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
5320struct sqlite3_mutex_methods {
5321  int (*xMutexInit)(void);
5322  int (*xMutexEnd)(void);
5323  sqlite3_mutex *(*xMutexAlloc)(int);
5324  void (*xMutexFree)(sqlite3_mutex *);
5325  void (*xMutexEnter)(sqlite3_mutex *);
5326  int (*xMutexTry)(sqlite3_mutex *);
5327  void (*xMutexLeave)(sqlite3_mutex *);
5328  int (*xMutexHeld)(sqlite3_mutex *);
5329  int (*xMutexNotheld)(sqlite3_mutex *);
5330};
5331
5332/*
5333** CAPI3REF: Mutex Verification Routines
5334**
5335** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
5336** are intended for use inside assert() statements.  ^The SQLite core
5337** never uses these routines except inside an assert() and applications
5338** are advised to follow the lead of the core.  ^The SQLite core only
5339** provides implementations for these routines when it is compiled
5340** with the SQLITE_DEBUG flag.  ^External mutex implementations
5341** are only required to provide these routines if SQLITE_DEBUG is
5342** defined and if NDEBUG is not defined.
5343**
5344** ^These routines should return true if the mutex in their argument
5345** is held or not held, respectively, by the calling thread.
5346**
5347** ^The implementation is not required to provided versions of these
5348** routines that actually work. If the implementation does not provide working
5349** versions of these routines, it should at least provide stubs that always
5350** return true so that one does not get spurious assertion failures.
5351**
5352** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
5353** the routine should return 1.   This seems counter-intuitive since
5354** clearly the mutex cannot be held if it does not exist.  But the
5355** the reason the mutex does not exist is because the build is not
5356** using mutexes.  And we do not want the assert() containing the
5357** call to sqlite3_mutex_held() to fail, so a non-zero return is
5358** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
5359** interface should also return 1 when given a NULL pointer.
5360*/
5361#ifndef NDEBUG
5362SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
5363SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
5364#endif
5365
5366/*
5367** CAPI3REF: Mutex Types
5368**
5369** The [sqlite3_mutex_alloc()] interface takes a single argument
5370** which is one of these integer constants.
5371**
5372** The set of static mutexes may change from one SQLite release to the
5373** next.  Applications that override the built-in mutex logic must be
5374** prepared to accommodate additional static mutexes.
5375*/
5376#define SQLITE_MUTEX_FAST             0
5377#define SQLITE_MUTEX_RECURSIVE        1
5378#define SQLITE_MUTEX_STATIC_MASTER    2
5379#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
5380#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
5381#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
5382#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
5383#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
5384#define SQLITE_MUTEX_STATIC_LRU2      7  /* lru page list */
5385
5386/*
5387** CAPI3REF: Retrieve the mutex for a database connection
5388**
5389** ^This interface returns a pointer the [sqlite3_mutex] object that
5390** serializes access to the [database connection] given in the argument
5391** when the [threading mode] is Serialized.
5392** ^If the [threading mode] is Single-thread or Multi-thread then this
5393** routine returns a NULL pointer.
5394*/
5395SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
5396
5397/*
5398** CAPI3REF: Low-Level Control Of Database Files
5399**
5400** ^The [sqlite3_file_control()] interface makes a direct call to the
5401** xFileControl method for the [sqlite3_io_methods] object associated
5402** with a particular database identified by the second argument. ^The
5403** name of the database "main" for the main database or "temp" for the
5404** TEMP database, or the name that appears after the AS keyword for
5405** databases that are added using the [ATTACH] SQL command.
5406** ^A NULL pointer can be used in place of "main" to refer to the
5407** main database file.
5408** ^The third and fourth parameters to this routine
5409** are passed directly through to the second and third parameters of
5410** the xFileControl method.  ^The return value of the xFileControl
5411** method becomes the return value of this routine.
5412**
5413** ^If the second parameter (zDbName) does not match the name of any
5414** open database file, then SQLITE_ERROR is returned.  ^This error
5415** code is not remembered and will not be recalled by [sqlite3_errcode()]
5416** or [sqlite3_errmsg()].  The underlying xFileControl method might
5417** also return SQLITE_ERROR.  There is no way to distinguish between
5418** an incorrect zDbName and an SQLITE_ERROR return from the underlying
5419** xFileControl method.
5420**
5421** See also: [SQLITE_FCNTL_LOCKSTATE]
5422*/
5423SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
5424
5425/*
5426** CAPI3REF: Testing Interface
5427**
5428** ^The sqlite3_test_control() interface is used to read out internal
5429** state of SQLite and to inject faults into SQLite for testing
5430** purposes.  ^The first parameter is an operation code that determines
5431** the number, meaning, and operation of all subsequent parameters.
5432**
5433** This interface is not for use by applications.  It exists solely
5434** for verifying the correct operation of the SQLite library.  Depending
5435** on how the SQLite library is compiled, this interface might not exist.
5436**
5437** The details of the operation codes, their meanings, the parameters
5438** they take, and what they do are all subject to change without notice.
5439** Unlike most of the SQLite API, this function is not guaranteed to
5440** operate consistently from one release to the next.
5441*/
5442SQLITE_API int sqlite3_test_control(int op, ...);
5443
5444/*
5445** CAPI3REF: Testing Interface Operation Codes
5446**
5447** These constants are the valid operation code parameters used
5448** as the first argument to [sqlite3_test_control()].
5449**
5450** These parameters and their meanings are subject to change
5451** without notice.  These values are for testing purposes only.
5452** Applications should not use any of these parameters or the
5453** [sqlite3_test_control()] interface.
5454*/
5455#define SQLITE_TESTCTRL_FIRST                    5
5456#define SQLITE_TESTCTRL_PRNG_SAVE                5
5457#define SQLITE_TESTCTRL_PRNG_RESTORE             6
5458#define SQLITE_TESTCTRL_PRNG_RESET               7
5459#define SQLITE_TESTCTRL_BITVEC_TEST              8
5460#define SQLITE_TESTCTRL_FAULT_INSTALL            9
5461#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
5462#define SQLITE_TESTCTRL_PENDING_BYTE            11
5463#define SQLITE_TESTCTRL_ASSERT                  12
5464#define SQLITE_TESTCTRL_ALWAYS                  13
5465#define SQLITE_TESTCTRL_RESERVE                 14
5466#define SQLITE_TESTCTRL_OPTIMIZATIONS           15
5467#define SQLITE_TESTCTRL_ISKEYWORD               16
5468#define SQLITE_TESTCTRL_LAST                    16
5469
5470/*
5471** CAPI3REF: SQLite Runtime Status
5472** EXPERIMENTAL
5473**
5474** ^This interface is used to retrieve runtime status information
5475** about the preformance of SQLite, and optionally to reset various
5476** highwater marks.  ^The first argument is an integer code for
5477** the specific parameter to measure.  ^(Recognized integer codes
5478** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
5479** ^The current value of the parameter is returned into *pCurrent.
5480** ^The highest recorded value is returned in *pHighwater.  ^If the
5481** resetFlag is true, then the highest record value is reset after
5482** *pHighwater is written.  ^(Some parameters do not record the highest
5483** value.  For those parameters
5484** nothing is written into *pHighwater and the resetFlag is ignored.)^
5485** ^(Other parameters record only the highwater mark and not the current
5486** value.  For these latter parameters nothing is written into *pCurrent.)^
5487**
5488** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
5489** non-zero [error code] on failure.
5490**
5491** This routine is threadsafe but is not atomic.  This routine can be
5492** called while other threads are running the same or different SQLite
5493** interfaces.  However the values returned in *pCurrent and
5494** *pHighwater reflect the status of SQLite at different points in time
5495** and it is possible that another thread might change the parameter
5496** in between the times when *pCurrent and *pHighwater are written.
5497**
5498** See also: [sqlite3_db_status()]
5499*/
5500SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
5501
5502
5503/*
5504** CAPI3REF: Status Parameters
5505** EXPERIMENTAL
5506**
5507** These integer constants designate various run-time status parameters
5508** that can be returned by [sqlite3_status()].
5509**
5510** <dl>
5511** ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
5512** <dd>This parameter is the current amount of memory checked out
5513** using [sqlite3_malloc()], either directly or indirectly.  The
5514** figure includes calls made to [sqlite3_malloc()] by the application
5515** and internal memory usage by the SQLite library.  Scratch memory
5516** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
5517** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
5518** this parameter.  The amount returned is the sum of the allocation
5519** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
5520**
5521** ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
5522** <dd>This parameter records the largest memory allocation request
5523** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
5524** internal equivalents).  Only the value returned in the
5525** *pHighwater parameter to [sqlite3_status()] is of interest.
5526** The value written into the *pCurrent parameter is undefined.</dd>)^
5527**
5528** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
5529** <dd>This parameter returns the number of pages used out of the
5530** [pagecache memory allocator] that was configured using
5531** [SQLITE_CONFIG_PAGECACHE].  The
5532** value returned is in pages, not in bytes.</dd>)^
5533**
5534** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
5535** <dd>This parameter returns the number of bytes of page cache
5536** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
5537** buffer and where forced to overflow to [sqlite3_malloc()].  The
5538** returned value includes allocations that overflowed because they
5539** where too large (they were larger than the "sz" parameter to
5540** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
5541** no space was left in the page cache.</dd>)^
5542**
5543** ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
5544** <dd>This parameter records the largest memory allocation request
5545** handed to [pagecache memory allocator].  Only the value returned in the
5546** *pHighwater parameter to [sqlite3_status()] is of interest.
5547** The value written into the *pCurrent parameter is undefined.</dd>)^
5548**
5549** ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
5550** <dd>This parameter returns the number of allocations used out of the
5551** [scratch memory allocator] configured using
5552** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
5553** in bytes.  Since a single thread may only have one scratch allocation
5554** outstanding at time, this parameter also reports the number of threads
5555** using scratch memory at the same time.</dd>)^
5556**
5557** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
5558** <dd>This parameter returns the number of bytes of scratch memory
5559** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
5560** buffer and where forced to overflow to [sqlite3_malloc()].  The values
5561** returned include overflows because the requested allocation was too
5562** larger (that is, because the requested allocation was larger than the
5563** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
5564** slots were available.
5565** </dd>)^
5566**
5567** ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
5568** <dd>This parameter records the largest memory allocation request
5569** handed to [scratch memory allocator].  Only the value returned in the
5570** *pHighwater parameter to [sqlite3_status()] is of interest.
5571** The value written into the *pCurrent parameter is undefined.</dd>)^
5572**
5573** ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
5574** <dd>This parameter records the deepest parser stack.  It is only
5575** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
5576** </dl>
5577**
5578** New status parameters may be added from time to time.
5579*/
5580#define SQLITE_STATUS_MEMORY_USED          0
5581#define SQLITE_STATUS_PAGECACHE_USED       1
5582#define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
5583#define SQLITE_STATUS_SCRATCH_USED         3
5584#define SQLITE_STATUS_SCRATCH_OVERFLOW     4
5585#define SQLITE_STATUS_MALLOC_SIZE          5
5586#define SQLITE_STATUS_PARSER_STACK         6
5587#define SQLITE_STATUS_PAGECACHE_SIZE       7
5588#define SQLITE_STATUS_SCRATCH_SIZE         8
5589
5590/*
5591** CAPI3REF: Database Connection Status
5592** EXPERIMENTAL
5593**
5594** ^This interface is used to retrieve runtime status information
5595** about a single [database connection].  ^The first argument is the
5596** database connection object to be interrogated.  ^The second argument
5597** is the parameter to interrogate.  ^Currently, the only allowed value
5598** for the second parameter is [SQLITE_DBSTATUS_LOOKASIDE_USED].
5599** Additional options will likely appear in future releases of SQLite.
5600**
5601** ^The current value of the requested parameter is written into *pCur
5602** and the highest instantaneous value is written into *pHiwtr.  ^If
5603** the resetFlg is true, then the highest instantaneous value is
5604** reset back down to the current value.
5605**
5606** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
5607*/
5608SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
5609
5610/*
5611** CAPI3REF: Status Parameters for database connections
5612** EXPERIMENTAL
5613**
5614** These constants are the available integer "verbs" that can be passed as
5615** the second argument to the [sqlite3_db_status()] interface.
5616**
5617** New verbs may be added in future releases of SQLite. Existing verbs
5618** might be discontinued. Applications should check the return code from
5619** [sqlite3_db_status()] to make sure that the call worked.
5620** The [sqlite3_db_status()] interface will return a non-zero error code
5621** if a discontinued or unsupported verb is invoked.
5622**
5623** <dl>
5624** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
5625** <dd>This parameter returns the number of lookaside memory slots currently
5626** checked out.</dd>)^
5627** </dl>
5628*/
5629#define SQLITE_DBSTATUS_LOOKASIDE_USED     0
5630
5631
5632/*
5633** CAPI3REF: Prepared Statement Status
5634** EXPERIMENTAL
5635**
5636** ^(Each prepared statement maintains various
5637** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
5638** of times it has performed specific operations.)^  These counters can
5639** be used to monitor the performance characteristics of the prepared
5640** statements.  For example, if the number of table steps greatly exceeds
5641** the number of table searches or result rows, that would tend to indicate
5642** that the prepared statement is using a full table scan rather than
5643** an index.
5644**
5645** ^(This interface is used to retrieve and reset counter values from
5646** a [prepared statement].  The first argument is the prepared statement
5647** object to be interrogated.  The second argument
5648** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
5649** to be interrogated.)^
5650** ^The current value of the requested counter is returned.
5651** ^If the resetFlg is true, then the counter is reset to zero after this
5652** interface call returns.
5653**
5654** See also: [sqlite3_status()] and [sqlite3_db_status()].
5655*/
5656SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
5657
5658/*
5659** CAPI3REF: Status Parameters for prepared statements
5660** EXPERIMENTAL
5661**
5662** These preprocessor macros define integer codes that name counter
5663** values associated with the [sqlite3_stmt_status()] interface.
5664** The meanings of the various counters are as follows:
5665**
5666** <dl>
5667** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
5668** <dd>^This is the number of times that SQLite has stepped forward in
5669** a table as part of a full table scan.  Large numbers for this counter
5670** may indicate opportunities for performance improvement through
5671** careful use of indices.</dd>
5672**
5673** <dt>SQLITE_STMTSTATUS_SORT</dt>
5674** <dd>^This is the number of sort operations that have occurred.
5675** A non-zero value in this counter may indicate an opportunity to
5676** improvement performance through careful use of indices.</dd>
5677**
5678** </dl>
5679*/
5680#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
5681#define SQLITE_STMTSTATUS_SORT              2
5682
5683/*
5684** CAPI3REF: Custom Page Cache Object
5685** EXPERIMENTAL
5686**
5687** The sqlite3_pcache type is opaque.  It is implemented by
5688** the pluggable module.  The SQLite core has no knowledge of
5689** its size or internal structure and never deals with the
5690** sqlite3_pcache object except by holding and passing pointers
5691** to the object.
5692**
5693** See [sqlite3_pcache_methods] for additional information.
5694*/
5695typedef struct sqlite3_pcache sqlite3_pcache;
5696
5697/*
5698** CAPI3REF: Application Defined Page Cache.
5699** KEYWORDS: {page cache}
5700** EXPERIMENTAL
5701**
5702** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
5703** register an alternative page cache implementation by passing in an
5704** instance of the sqlite3_pcache_methods structure.)^ The majority of the
5705** heap memory used by SQLite is used by the page cache to cache data read
5706** from, or ready to be written to, the database file. By implementing a
5707** custom page cache using this API, an application can control more
5708** precisely the amount of memory consumed by SQLite, the way in which
5709** that memory is allocated and released, and the policies used to
5710** determine exactly which parts of a database file are cached and for
5711** how long.
5712**
5713** ^(The contents of the sqlite3_pcache_methods structure are copied to an
5714** internal buffer by SQLite within the call to [sqlite3_config].  Hence
5715** the application may discard the parameter after the call to
5716** [sqlite3_config()] returns.)^
5717**
5718** ^The xInit() method is called once for each call to [sqlite3_initialize()]
5719** (usually only once during the lifetime of the process). ^(The xInit()
5720** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
5721** ^The xInit() method can set up up global structures and/or any mutexes
5722** required by the custom page cache implementation.
5723**
5724** ^The xShutdown() method is called from within [sqlite3_shutdown()],
5725** if the application invokes this API. It can be used to clean up
5726** any outstanding resources before process shutdown, if required.
5727**
5728** ^SQLite holds a [SQLITE_MUTEX_RECURSIVE] mutex when it invokes
5729** the xInit method, so the xInit method need not be threadsafe.  ^The
5730** xShutdown method is only called from [sqlite3_shutdown()] so it does
5731** not need to be threadsafe either.  All other methods must be threadsafe
5732** in multithreaded applications.
5733**
5734** ^SQLite will never invoke xInit() more than once without an intervening
5735** call to xShutdown().
5736**
5737** ^The xCreate() method is used to construct a new cache instance.  SQLite
5738** will typically create one cache instance for each open database file,
5739** though this is not guaranteed. ^The
5740** first parameter, szPage, is the size in bytes of the pages that must
5741** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
5742** will the page size of the database file that is to be cached plus an
5743** increment (here called "R") of about 100 or 200.  ^SQLite will use the
5744** extra R bytes on each page to store metadata about the underlying
5745** database page on disk.  The value of R depends
5746** on the SQLite version, the target platform, and how SQLite was compiled.
5747** ^R is constant for a particular build of SQLite.  ^The second argument to
5748** xCreate(), bPurgeable, is true if the cache being created will
5749** be used to cache database pages of a file stored on disk, or
5750** false if it is used for an in-memory database. ^The cache implementation
5751** does not have to do anything special based with the value of bPurgeable;
5752** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
5753** never invoke xUnpin() except to deliberately delete a page.
5754** ^In other words, a cache created with bPurgeable set to false will
5755** never contain any unpinned pages.
5756**
5757** ^(The xCachesize() method may be called at any time by SQLite to set the
5758** suggested maximum cache-size (number of pages stored by) the cache
5759** instance passed as the first argument. This is the value configured using
5760** the SQLite "[PRAGMA cache_size]" command.)^  ^As with the bPurgeable
5761** parameter, the implementation is not required to do anything with this
5762** value; it is advisory only.
5763**
5764** ^The xPagecount() method should return the number of pages currently
5765** stored in the cache.
5766**
5767** ^The xFetch() method is used to fetch a page and return a pointer to it.
5768** ^A 'page', in this context, is a buffer of szPage bytes aligned at an
5769** 8-byte boundary. ^The page to be fetched is determined by the key. ^The
5770** mimimum key value is 1. After it has been retrieved using xFetch, the page
5771** is considered to be "pinned".
5772**
5773** ^If the requested page is already in the page cache, then the page cache
5774** implementation must return a pointer to the page buffer with its content
5775** intact.  ^(If the requested page is not already in the cache, then the
5776** behavior of the cache implementation is determined by the value of the
5777** createFlag parameter passed to xFetch, according to the following table:
5778**
5779** <table border=1 width=85% align=center>
5780** <tr><th> createFlag <th> Behaviour when page is not already in cache
5781** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
5782** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
5783**                 Otherwise return NULL.
5784** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
5785**                 NULL if allocating a new page is effectively impossible.
5786** </table>)^
5787**
5788** SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  If
5789** a call to xFetch() with createFlag==1 returns NULL, then SQLite will
5790** attempt to unpin one or more cache pages by spilling the content of
5791** pinned pages to disk and synching the operating system disk cache. After
5792** attempting to unpin pages, the xFetch() method will be invoked again with
5793** a createFlag of 2.
5794**
5795** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
5796** as its second argument. ^(If the third parameter, discard, is non-zero,
5797** then the page should be evicted from the cache. In this case SQLite
5798** assumes that the next time the page is retrieved from the cache using
5799** the xFetch() method, it will be zeroed.)^ ^If the discard parameter is
5800** zero, then the page is considered to be unpinned. ^The cache implementation
5801** may choose to evict unpinned pages at any time.
5802**
5803** ^(The cache is not required to perform any reference counting. A single
5804** call to xUnpin() unpins the page regardless of the number of prior calls
5805** to xFetch().)^
5806**
5807** ^The xRekey() method is used to change the key value associated with the
5808** page passed as the second argument from oldKey to newKey. ^If the cache
5809** previously contains an entry associated with newKey, it should be
5810** discarded. ^Any prior cache entry associated with newKey is guaranteed not
5811** to be pinned.
5812**
5813** ^When SQLite calls the xTruncate() method, the cache must discard all
5814** existing cache entries with page numbers (keys) greater than or equal
5815** to the value of the iLimit parameter passed to xTruncate(). ^If any
5816** of these pages are pinned, they are implicitly unpinned, meaning that
5817** they can be safely discarded.
5818**
5819** ^The xDestroy() method is used to delete a cache allocated by xCreate().
5820** All resources associated with the specified cache should be freed. ^After
5821** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
5822** handle invalid, and will not use it with any other sqlite3_pcache_methods
5823** functions.
5824*/
5825typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
5826struct sqlite3_pcache_methods {
5827  void *pArg;
5828  int (*xInit)(void*);
5829  void (*xShutdown)(void*);
5830  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
5831  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
5832  int (*xPagecount)(sqlite3_pcache*);
5833  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
5834  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
5835  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
5836  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
5837  void (*xDestroy)(sqlite3_pcache*);
5838};
5839
5840/*
5841** CAPI3REF: Online Backup Object
5842** EXPERIMENTAL
5843**
5844** The sqlite3_backup object records state information about an ongoing
5845** online backup operation.  ^The sqlite3_backup object is created by
5846** a call to [sqlite3_backup_init()] and is destroyed by a call to
5847** [sqlite3_backup_finish()].
5848**
5849** See Also: [Using the SQLite Online Backup API]
5850*/
5851typedef struct sqlite3_backup sqlite3_backup;
5852
5853/*
5854** CAPI3REF: Online Backup API.
5855** EXPERIMENTAL
5856**
5857** The backup API copies the content of one database into another.
5858** It is useful either for creating backups of databases or
5859** for copying in-memory databases to or from persistent files.
5860**
5861** See Also: [Using the SQLite Online Backup API]
5862**
5863** ^Exclusive access is required to the destination database for the
5864** duration of the operation. ^However the source database is only
5865** read-locked while it is actually being read; it is not locked
5866** continuously for the entire backup operation. ^Thus, the backup may be
5867** performed on a live source database without preventing other users from
5868** reading or writing to the source database while the backup is underway.
5869**
5870** ^(To perform a backup operation:
5871**   <ol>
5872**     <li><b>sqlite3_backup_init()</b> is called once to initialize the
5873**         backup,
5874**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
5875**         the data between the two databases, and finally
5876**     <li><b>sqlite3_backup_finish()</b> is called to release all resources
5877**         associated with the backup operation.
5878**   </ol>)^
5879** There should be exactly one call to sqlite3_backup_finish() for each
5880** successful call to sqlite3_backup_init().
5881**
5882** <b>sqlite3_backup_init()</b>
5883**
5884** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
5885** [database connection] associated with the destination database
5886** and the database name, respectively.
5887** ^The database name is "main" for the main database, "temp" for the
5888** temporary database, or the name specified after the AS keyword in
5889** an [ATTACH] statement for an attached database.
5890** ^The S and M arguments passed to
5891** sqlite3_backup_init(D,N,S,M) identify the [database connection]
5892** and database name of the source database, respectively.
5893** ^The source and destination [database connections] (parameters S and D)
5894** must be different or else sqlite3_backup_init(D,N,S,M) will file with
5895** an error.
5896**
5897** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
5898** returned and an error code and error message are store3d in the
5899** destination [database connection] D.
5900** ^The error code and message for the failed call to sqlite3_backup_init()
5901** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
5902** [sqlite3_errmsg16()] functions.
5903** ^A successful call to sqlite3_backup_init() returns a pointer to an
5904** [sqlite3_backup] object.
5905** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
5906** sqlite3_backup_finish() functions to perform the specified backup
5907** operation.
5908**
5909** <b>sqlite3_backup_step()</b>
5910**
5911** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
5912** the source and destination databases specified by [sqlite3_backup] object B.
5913** ^If N is negative, all remaining source pages are copied.
5914** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
5915** are still more pages to be copied, then the function resturns [SQLITE_OK].
5916** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
5917** from source to destination, then it returns [SQLITE_DONE].
5918** ^If an error occurs while running sqlite3_backup_step(B,N),
5919** then an [error code] is returned. ^As well as [SQLITE_OK] and
5920** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
5921** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
5922** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
5923**
5924** ^The sqlite3_backup_step() might return [SQLITE_READONLY] if the destination
5925** database was opened read-only or if
5926** the destination is an in-memory database with a different page size
5927** from the source database.
5928**
5929** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
5930** the [sqlite3_busy_handler | busy-handler function]
5931** is invoked (if one is specified). ^If the
5932** busy-handler returns non-zero before the lock is available, then
5933** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
5934** sqlite3_backup_step() can be retried later. ^If the source
5935** [database connection]
5936** is being used to write to the source database when sqlite3_backup_step()
5937** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
5938** case the call to sqlite3_backup_step() can be retried later on. ^(If
5939** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
5940** [SQLITE_READONLY] is returned, then
5941** there is no point in retrying the call to sqlite3_backup_step(). These
5942** errors are considered fatal.)^  The application must accept
5943** that the backup operation has failed and pass the backup operation handle
5944** to the sqlite3_backup_finish() to release associated resources.
5945**
5946** ^The first call to sqlite3_backup_step() obtains an exclusive lock
5947** on the destination file. ^The exclusive lock is not released until either
5948** sqlite3_backup_finish() is called or the backup operation is complete
5949** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
5950** sqlite3_backup_step() obtains a [shared lock] on the source database that
5951** lasts for the duration of the sqlite3_backup_step() call.
5952** ^Because the source database is not locked between calls to
5953** sqlite3_backup_step(), the source database may be modified mid-way
5954** through the backup process.  ^If the source database is modified by an
5955** external process or via a database connection other than the one being
5956** used by the backup operation, then the backup will be automatically
5957** restarted by the next call to sqlite3_backup_step(). ^If the source
5958** database is modified by the using the same database connection as is used
5959** by the backup operation, then the backup database is automatically
5960** updated at the same time.
5961**
5962** <b>sqlite3_backup_finish()</b>
5963**
5964** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
5965** application wishes to abandon the backup operation, the application
5966** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
5967** ^The sqlite3_backup_finish() interfaces releases all
5968** resources associated with the [sqlite3_backup] object.
5969** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
5970** active write-transaction on the destination database is rolled back.
5971** The [sqlite3_backup] object is invalid
5972** and may not be used following a call to sqlite3_backup_finish().
5973**
5974** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
5975** sqlite3_backup_step() errors occurred, regardless or whether or not
5976** sqlite3_backup_step() completed.
5977** ^If an out-of-memory condition or IO error occurred during any prior
5978** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
5979** sqlite3_backup_finish() returns the corresponding [error code].
5980**
5981** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
5982** is not a permanent error and does not affect the return value of
5983** sqlite3_backup_finish().
5984**
5985** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
5986**
5987** ^Each call to sqlite3_backup_step() sets two values inside
5988** the [sqlite3_backup] object: the number of pages still to be backed
5989** up and the total number of pages in the source databae file.
5990** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
5991** retrieve these two values, respectively.
5992**
5993** ^The values returned by these functions are only updated by
5994** sqlite3_backup_step(). ^If the source database is modified during a backup
5995** operation, then the values are not updated to account for any extra
5996** pages that need to be updated or the size of the source database file
5997** changing.
5998**
5999** <b>Concurrent Usage of Database Handles</b>
6000**
6001** ^The source [database connection] may be used by the application for other
6002** purposes while a backup operation is underway or being initialized.
6003** ^If SQLite is compiled and configured to support threadsafe database
6004** connections, then the source database connection may be used concurrently
6005** from within other threads.
6006**
6007** However, the application must guarantee that the destination
6008** [database connection] is not passed to any other API (by any thread) after
6009** sqlite3_backup_init() is called and before the corresponding call to
6010** sqlite3_backup_finish().  SQLite does not currently check to see
6011** if the application incorrectly accesses the destination [database connection]
6012** and so no error code is reported, but the operations may malfunction
6013** nevertheless.  Use of the destination database connection while a
6014** backup is in progress might also also cause a mutex deadlock.
6015**
6016** If running in [shared cache mode], the application must
6017** guarantee that the shared cache used by the destination database
6018** is not accessed while the backup is running. In practice this means
6019** that the application must guarantee that the disk file being
6020** backed up to is not accessed by any connection within the process,
6021** not just the specific connection that was passed to sqlite3_backup_init().
6022**
6023** The [sqlite3_backup] object itself is partially threadsafe. Multiple
6024** threads may safely make multiple concurrent calls to sqlite3_backup_step().
6025** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
6026** APIs are not strictly speaking threadsafe. If they are invoked at the
6027** same time as another thread is invoking sqlite3_backup_step() it is
6028** possible that they return invalid values.
6029*/
6030SQLITE_API sqlite3_backup *sqlite3_backup_init(
6031  sqlite3 *pDest,                        /* Destination database handle */
6032  const char *zDestName,                 /* Destination database name */
6033  sqlite3 *pSource,                      /* Source database handle */
6034  const char *zSourceName                /* Source database name */
6035);
6036SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
6037SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
6038SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
6039SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
6040
6041/*
6042** CAPI3REF: Unlock Notification
6043** EXPERIMENTAL
6044**
6045** ^When running in shared-cache mode, a database operation may fail with
6046** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
6047** individual tables within the shared-cache cannot be obtained. See
6048** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
6049** ^This API may be used to register a callback that SQLite will invoke
6050** when the connection currently holding the required lock relinquishes it.
6051** ^This API is only available if the library was compiled with the
6052** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6053**
6054** See Also: [Using the SQLite Unlock Notification Feature].
6055**
6056** ^Shared-cache locks are released when a database connection concludes
6057** its current transaction, either by committing it or rolling it back.
6058**
6059** ^When a connection (known as the blocked connection) fails to obtain a
6060** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
6061** identity of the database connection (the blocking connection) that
6062** has locked the required resource is stored internally. ^After an
6063** application receives an SQLITE_LOCKED error, it may call the
6064** sqlite3_unlock_notify() method with the blocked connection handle as
6065** the first argument to register for a callback that will be invoked
6066** when the blocking connections current transaction is concluded. ^The
6067** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
6068** call that concludes the blocking connections transaction.
6069**
6070** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
6071** there is a chance that the blocking connection will have already
6072** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
6073** If this happens, then the specified callback is invoked immediately,
6074** from within the call to sqlite3_unlock_notify().)^
6075**
6076** ^If the blocked connection is attempting to obtain a write-lock on a
6077** shared-cache table, and more than one other connection currently holds
6078** a read-lock on the same table, then SQLite arbitrarily selects one of
6079** the other connections to use as the blocking connection.
6080**
6081** ^(There may be at most one unlock-notify callback registered by a
6082** blocked connection. If sqlite3_unlock_notify() is called when the
6083** blocked connection already has a registered unlock-notify callback,
6084** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6085** called with a NULL pointer as its second argument, then any existing
6086** unlock-notify callback is cancelled. ^The blocked connections
6087** unlock-notify callback may also be canceled by closing the blocked
6088** connection using [sqlite3_close()].
6089**
6090** The unlock-notify callback is not reentrant. If an application invokes
6091** any sqlite3_xxx API functions from within an unlock-notify callback, a
6092** crash or deadlock may be the result.
6093**
6094** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
6095** returns SQLITE_OK.
6096**
6097** <b>Callback Invocation Details</b>
6098**
6099** When an unlock-notify callback is registered, the application provides a
6100** single void* pointer that is passed to the callback when it is invoked.
6101** However, the signature of the callback function allows SQLite to pass
6102** it an array of void* context pointers. The first argument passed to
6103** an unlock-notify callback is a pointer to an array of void* pointers,
6104** and the second is the number of entries in the array.
6105**
6106** When a blocking connections transaction is concluded, there may be
6107** more than one blocked connection that has registered for an unlock-notify
6108** callback. ^If two or more such blocked connections have specified the
6109** same callback function, then instead of invoking the callback function
6110** multiple times, it is invoked once with the set of void* context pointers
6111** specified by the blocked connections bundled together into an array.
6112** This gives the application an opportunity to prioritize any actions
6113** related to the set of unblocked database connections.
6114**
6115** <b>Deadlock Detection</b>
6116**
6117** Assuming that after registering for an unlock-notify callback a
6118** database waits for the callback to be issued before taking any further
6119** action (a reasonable assumption), then using this API may cause the
6120** application to deadlock. For example, if connection X is waiting for
6121** connection Y's transaction to be concluded, and similarly connection
6122** Y is waiting on connection X's transaction, then neither connection
6123** will proceed and the system may remain deadlocked indefinitely.
6124**
6125** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
6126** detection. ^If a given call to sqlite3_unlock_notify() would put the
6127** system in a deadlocked state, then SQLITE_LOCKED is returned and no
6128** unlock-notify callback is registered. The system is said to be in
6129** a deadlocked state if connection A has registered for an unlock-notify
6130** callback on the conclusion of connection B's transaction, and connection
6131** B has itself registered for an unlock-notify callback when connection
6132** A's transaction is concluded. ^Indirect deadlock is also detected, so
6133** the system is also considered to be deadlocked if connection B has
6134** registered for an unlock-notify callback on the conclusion of connection
6135** C's transaction, where connection C is waiting on connection A. ^Any
6136** number of levels of indirection are allowed.
6137**
6138** <b>The "DROP TABLE" Exception</b>
6139**
6140** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
6141** always appropriate to call sqlite3_unlock_notify(). There is however,
6142** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
6143** SQLite checks if there are any currently executing SELECT statements
6144** that belong to the same connection. If there are, SQLITE_LOCKED is
6145** returned. In this case there is no "blocking connection", so invoking
6146** sqlite3_unlock_notify() results in the unlock-notify callback being
6147** invoked immediately. If the application then re-attempts the "DROP TABLE"
6148** or "DROP INDEX" query, an infinite loop might be the result.
6149**
6150** One way around this problem is to check the extended error code returned
6151** by an sqlite3_step() call. ^(If there is a blocking connection, then the
6152** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
6153** the special "DROP TABLE/INDEX" case, the extended error code is just
6154** SQLITE_LOCKED.)^
6155*/
6156SQLITE_API int sqlite3_unlock_notify(
6157  sqlite3 *pBlocked,                          /* Waiting connection */
6158  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
6159  void *pNotifyArg                            /* Argument to pass to xNotify */
6160);
6161
6162
6163/*
6164** CAPI3REF: String Comparison
6165** EXPERIMENTAL
6166**
6167** ^The [sqlite3_strnicmp()] API allows applications and extensions to
6168** compare the contents of two buffers containing UTF-8 strings in a
6169** case-indendent fashion, using the same definition of case independence
6170** that SQLite uses internally when comparing identifiers.
6171*/
6172SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
6173
6174/*
6175** CAPI3REF: Error Logging Interface
6176** EXPERIMENTAL
6177**
6178** ^The [sqlite3_log()] interface writes a message into the error log
6179** established by the [SQLITE_CONFIG_ERRORLOG] option to [sqlite3_config()].
6180**
6181** The sqlite3_log() interface is intended for use by extensions such as
6182** virtual tables, collating functions, and SQL functions.  While there is
6183** nothing to prevent an application from calling sqlite3_log(), doing so
6184** is considered bad form.
6185**
6186** To avoid deadlocks and other threading problems, the sqlite3_log() routine
6187** will not use dynamically allocated memory.  The log message is stored in
6188** a fixed-length buffer on the stack.  If the log message is longer than
6189** a few hundred characters, it will be truncated to the length of the
6190** buffer.
6191*/
6192SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
6193
6194/*
6195** Undo the hack that converts floating point types to integer for
6196** builds on processors without floating point support.
6197*/
6198#ifdef SQLITE_OMIT_FLOATING_POINT
6199# undef double
6200#endif
6201
6202#if 0
6203}  /* End of the 'extern "C"' block */
6204#endif
6205#endif
6206
6207
6208/************** End of sqlite3.h *********************************************/
6209// Begin Android Add
6210#define SQLITE_BeginImmediate 0x00200000  /* Default BEGIN to IMMEDIATE */
6211#define fdatasync fsync
6212#undef __APPLE__
6213// End Android Add
6214/************** Continuing where we left off in sqliteInt.h ******************/
6215/************** Include hash.h in the middle of sqliteInt.h ******************/
6216/************** Begin file hash.h ********************************************/
6217/*
6218** 2001 September 22
6219**
6220** The author disclaims copyright to this source code.  In place of
6221** a legal notice, here is a blessing:
6222**
6223**    May you do good and not evil.
6224**    May you find forgiveness for yourself and forgive others.
6225**    May you share freely, never taking more than you give.
6226**
6227*************************************************************************
6228** This is the header file for the generic hash-table implemenation
6229** used in SQLite.
6230*/
6231#ifndef _SQLITE_HASH_H_
6232#define _SQLITE_HASH_H_
6233
6234/* Forward declarations of structures. */
6235typedef struct Hash Hash;
6236typedef struct HashElem HashElem;
6237
6238/* A complete hash table is an instance of the following structure.
6239** The internals of this structure are intended to be opaque -- client
6240** code should not attempt to access or modify the fields of this structure
6241** directly.  Change this structure only by using the routines below.
6242** However, some of the "procedures" and "functions" for modifying and
6243** accessing this structure are really macros, so we can't really make
6244** this structure opaque.
6245**
6246** All elements of the hash table are on a single doubly-linked list.
6247** Hash.first points to the head of this list.
6248**
6249** There are Hash.htsize buckets.  Each bucket points to a spot in
6250** the global doubly-linked list.  The contents of the bucket are the
6251** element pointed to plus the next _ht.count-1 elements in the list.
6252**
6253** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
6254** by a linear search of the global list.  For small tables, the
6255** Hash.ht table is never allocated because if there are few elements
6256** in the table, it is faster to do a linear search than to manage
6257** the hash table.
6258*/
6259struct Hash {
6260  unsigned int htsize;      /* Number of buckets in the hash table */
6261  unsigned int count;       /* Number of entries in this table */
6262  HashElem *first;          /* The first element of the array */
6263  struct _ht {              /* the hash table */
6264    int count;                 /* Number of entries with this hash */
6265    HashElem *chain;           /* Pointer to first entry with this hash */
6266  } *ht;
6267};
6268
6269/* Each element in the hash table is an instance of the following
6270** structure.  All elements are stored on a single doubly-linked list.
6271**
6272** Again, this structure is intended to be opaque, but it can't really
6273** be opaque because it is used by macros.
6274*/
6275struct HashElem {
6276  HashElem *next, *prev;       /* Next and previous elements in the table */
6277  void *data;                  /* Data associated with this element */
6278  const char *pKey; int nKey;  /* Key associated with this element */
6279};
6280
6281/*
6282** Access routines.  To delete, insert a NULL pointer.
6283*/
6284SQLITE_PRIVATE void sqlite3HashInit(Hash*);
6285SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
6286SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
6287SQLITE_PRIVATE void sqlite3HashClear(Hash*);
6288
6289/*
6290** Macros for looping over all elements of a hash table.  The idiom is
6291** like this:
6292**
6293**   Hash h;
6294**   HashElem *p;
6295**   ...
6296**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
6297**     SomeStructure *pData = sqliteHashData(p);
6298**     // do something with pData
6299**   }
6300*/
6301#define sqliteHashFirst(H)  ((H)->first)
6302#define sqliteHashNext(E)   ((E)->next)
6303#define sqliteHashData(E)   ((E)->data)
6304/* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
6305/* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
6306
6307/*
6308** Number of entries in a hash table
6309*/
6310/* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
6311
6312#endif /* _SQLITE_HASH_H_ */
6313
6314/************** End of hash.h ************************************************/
6315/************** Continuing where we left off in sqliteInt.h ******************/
6316/************** Include parse.h in the middle of sqliteInt.h *****************/
6317/************** Begin file parse.h *******************************************/
6318#define TK_SEMI                            1
6319#define TK_EXPLAIN                         2
6320#define TK_QUERY                           3
6321#define TK_PLAN                            4
6322#define TK_BEGIN                           5
6323#define TK_TRANSACTION                     6
6324#define TK_DEFERRED                        7
6325#define TK_IMMEDIATE                       8
6326#define TK_EXCLUSIVE                       9
6327#define TK_COMMIT                         10
6328#define TK_END                            11
6329#define TK_ROLLBACK                       12
6330#define TK_SAVEPOINT                      13
6331#define TK_RELEASE                        14
6332#define TK_TO                             15
6333#define TK_TABLE                          16
6334#define TK_CREATE                         17
6335#define TK_IF                             18
6336#define TK_NOT                            19
6337#define TK_EXISTS                         20
6338#define TK_TEMP                           21
6339#define TK_LP                             22
6340#define TK_RP                             23
6341#define TK_AS                             24
6342#define TK_COMMA                          25
6343#define TK_ID                             26
6344#define TK_INDEXED                        27
6345#define TK_ABORT                          28
6346#define TK_ACTION                         29
6347#define TK_AFTER                          30
6348#define TK_ANALYZE                        31
6349#define TK_ASC                            32
6350#define TK_ATTACH                         33
6351#define TK_BEFORE                         34
6352#define TK_BY                             35
6353#define TK_CASCADE                        36
6354#define TK_CAST                           37
6355#define TK_COLUMNKW                       38
6356#define TK_CONFLICT                       39
6357#define TK_DATABASE                       40
6358#define TK_DESC                           41
6359#define TK_DETACH                         42
6360#define TK_EACH                           43
6361#define TK_FAIL                           44
6362#define TK_FOR                            45
6363#define TK_IGNORE                         46
6364#define TK_INITIALLY                      47
6365#define TK_INSTEAD                        48
6366#define TK_LIKE_KW                        49
6367#define TK_MATCH                          50
6368#define TK_NO                             51
6369#define TK_KEY                            52
6370#define TK_OF                             53
6371#define TK_OFFSET                         54
6372#define TK_PRAGMA                         55
6373#define TK_RAISE                          56
6374#define TK_REPLACE                        57
6375#define TK_RESTRICT                       58
6376#define TK_ROW                            59
6377#define TK_TRIGGER                        60
6378#define TK_VACUUM                         61
6379#define TK_VIEW                           62
6380#define TK_VIRTUAL                        63
6381#define TK_REINDEX                        64
6382#define TK_RENAME                         65
6383#define TK_CTIME_KW                       66
6384#define TK_ANY                            67
6385#define TK_OR                             68
6386#define TK_AND                            69
6387#define TK_IS                             70
6388#define TK_BETWEEN                        71
6389#define TK_IN                             72
6390#define TK_ISNULL                         73
6391#define TK_NOTNULL                        74
6392#define TK_NE                             75
6393#define TK_EQ                             76
6394#define TK_GT                             77
6395#define TK_LE                             78
6396#define TK_LT                             79
6397#define TK_GE                             80
6398#define TK_ESCAPE                         81
6399#define TK_BITAND                         82
6400#define TK_BITOR                          83
6401#define TK_LSHIFT                         84
6402#define TK_RSHIFT                         85
6403#define TK_PLUS                           86
6404#define TK_MINUS                          87
6405#define TK_STAR                           88
6406#define TK_SLASH                          89
6407#define TK_REM                            90
6408#define TK_CONCAT                         91
6409#define TK_COLLATE                        92
6410#define TK_BITNOT                         93
6411#define TK_STRING                         94
6412#define TK_JOIN_KW                        95
6413#define TK_CONSTRAINT                     96
6414#define TK_DEFAULT                        97
6415#define TK_NULL                           98
6416#define TK_PRIMARY                        99
6417#define TK_UNIQUE                         100
6418#define TK_CHECK                          101
6419#define TK_REFERENCES                     102
6420#define TK_AUTOINCR                       103
6421#define TK_ON                             104
6422#define TK_INSERT                         105
6423#define TK_DELETE                         106
6424#define TK_UPDATE                         107
6425#define TK_SET                            108
6426#define TK_DEFERRABLE                     109
6427#define TK_FOREIGN                        110
6428#define TK_DROP                           111
6429#define TK_UNION                          112
6430#define TK_ALL                            113
6431#define TK_EXCEPT                         114
6432#define TK_INTERSECT                      115
6433#define TK_SELECT                         116
6434#define TK_DISTINCT                       117
6435#define TK_DOT                            118
6436#define TK_FROM                           119
6437#define TK_JOIN                           120
6438#define TK_USING                          121
6439#define TK_ORDER                          122
6440#define TK_GROUP                          123
6441#define TK_HAVING                         124
6442#define TK_LIMIT                          125
6443#define TK_WHERE                          126
6444#define TK_INTO                           127
6445#define TK_VALUES                         128
6446#define TK_INTEGER                        129
6447#define TK_FLOAT                          130
6448#define TK_BLOB                           131
6449#define TK_REGISTER                       132
6450#define TK_VARIABLE                       133
6451#define TK_CASE                           134
6452#define TK_WHEN                           135
6453#define TK_THEN                           136
6454#define TK_ELSE                           137
6455#define TK_INDEX                          138
6456#define TK_ALTER                          139
6457#define TK_ADD                            140
6458#define TK_TO_TEXT                        141
6459#define TK_TO_BLOB                        142
6460#define TK_TO_NUMERIC                     143
6461#define TK_TO_INT                         144
6462#define TK_TO_REAL                        145
6463#define TK_ISNOT                          146
6464#define TK_END_OF_FILE                    147
6465#define TK_ILLEGAL                        148
6466#define TK_SPACE                          149
6467#define TK_UNCLOSED_STRING                150
6468#define TK_FUNCTION                       151
6469#define TK_COLUMN                         152
6470#define TK_AGG_FUNCTION                   153
6471#define TK_AGG_COLUMN                     154
6472#define TK_CONST_FUNC                     155
6473#define TK_UMINUS                         156
6474#define TK_UPLUS                          157
6475
6476/************** End of parse.h ***********************************************/
6477/************** Continuing where we left off in sqliteInt.h ******************/
6478#include <stdio.h>
6479#include <stdlib.h>
6480#include <string.h>
6481#include <assert.h>
6482#include <stddef.h>
6483
6484/*
6485** If compiling for a processor that lacks floating point support,
6486** substitute integer for floating-point
6487*/
6488#ifdef SQLITE_OMIT_FLOATING_POINT
6489# define double sqlite_int64
6490# define LONGDOUBLE_TYPE sqlite_int64
6491# ifndef SQLITE_BIG_DBL
6492#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
6493# endif
6494# define SQLITE_OMIT_DATETIME_FUNCS 1
6495# define SQLITE_OMIT_TRACE 1
6496# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
6497# undef SQLITE_HAVE_ISNAN
6498#endif
6499#ifndef SQLITE_BIG_DBL
6500# define SQLITE_BIG_DBL (1e99)
6501#endif
6502
6503/*
6504** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
6505** afterward. Having this macro allows us to cause the C compiler
6506** to omit code used by TEMP tables without messy #ifndef statements.
6507*/
6508#ifdef SQLITE_OMIT_TEMPDB
6509#define OMIT_TEMPDB 1
6510#else
6511#define OMIT_TEMPDB 0
6512#endif
6513
6514/*
6515** If the following macro is set to 1, then NULL values are considered
6516** distinct when determining whether or not two entries are the same
6517** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
6518** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
6519** is the way things are suppose to work.
6520**
6521** If the following macro is set to 0, the NULLs are indistinct for
6522** a UNIQUE index.  In this mode, you can only have a single NULL entry
6523** for a column declared UNIQUE.  This is the way Informix and SQL Server
6524** work.
6525*/
6526#define NULL_DISTINCT_FOR_UNIQUE 1
6527
6528/*
6529** The "file format" number is an integer that is incremented whenever
6530** the VDBE-level file format changes.  The following macros define the
6531** the default file format for new databases and the maximum file format
6532** that the library can read.
6533*/
6534#define SQLITE_MAX_FILE_FORMAT 4
6535#ifndef SQLITE_DEFAULT_FILE_FORMAT
6536# define SQLITE_DEFAULT_FILE_FORMAT 1
6537#endif
6538
6539#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
6540# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
6541#endif
6542
6543/*
6544** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
6545** on the command-line
6546*/
6547#ifndef SQLITE_TEMP_STORE
6548# define SQLITE_TEMP_STORE 1
6549#endif
6550
6551/*
6552** GCC does not define the offsetof() macro so we'll have to do it
6553** ourselves.
6554*/
6555#ifndef offsetof
6556#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
6557#endif
6558
6559/*
6560** Check to see if this machine uses EBCDIC.  (Yes, believe it or
6561** not, there are still machines out there that use EBCDIC.)
6562*/
6563#if 'A' == '\301'
6564# define SQLITE_EBCDIC 1
6565#else
6566# define SQLITE_ASCII 1
6567#endif
6568
6569/*
6570** Integers of known sizes.  These typedefs might change for architectures
6571** where the sizes very.  Preprocessor macros are available so that the
6572** types can be conveniently redefined at compile-type.  Like this:
6573**
6574**         cc '-DUINTPTR_TYPE=long long int' ...
6575*/
6576#ifndef UINT32_TYPE
6577# ifdef HAVE_UINT32_T
6578#  define UINT32_TYPE uint32_t
6579# else
6580#  define UINT32_TYPE unsigned int
6581# endif
6582#endif
6583#ifndef UINT16_TYPE
6584# ifdef HAVE_UINT16_T
6585#  define UINT16_TYPE uint16_t
6586# else
6587#  define UINT16_TYPE unsigned short int
6588# endif
6589#endif
6590#ifndef INT16_TYPE
6591# ifdef HAVE_INT16_T
6592#  define INT16_TYPE int16_t
6593# else
6594#  define INT16_TYPE short int
6595# endif
6596#endif
6597#ifndef UINT8_TYPE
6598# ifdef HAVE_UINT8_T
6599#  define UINT8_TYPE uint8_t
6600# else
6601#  define UINT8_TYPE unsigned char
6602# endif
6603#endif
6604#ifndef INT8_TYPE
6605# ifdef HAVE_INT8_T
6606#  define INT8_TYPE int8_t
6607# else
6608#  define INT8_TYPE signed char
6609# endif
6610#endif
6611#ifndef LONGDOUBLE_TYPE
6612# define LONGDOUBLE_TYPE long double
6613#endif
6614typedef sqlite_int64 i64;          /* 8-byte signed integer */
6615typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
6616typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
6617typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
6618typedef INT16_TYPE i16;            /* 2-byte signed integer */
6619typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
6620typedef INT8_TYPE i8;              /* 1-byte signed integer */
6621
6622/*
6623** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
6624** that can be stored in a u32 without loss of data.  The value
6625** is 0x00000000ffffffff.  But because of quirks of some compilers, we
6626** have to specify the value in the less intuitive manner shown:
6627*/
6628#define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
6629
6630/*
6631** Macros to determine whether the machine is big or little endian,
6632** evaluated at runtime.
6633*/
6634#ifdef SQLITE_AMALGAMATION
6635SQLITE_PRIVATE const int sqlite3one = 1;
6636#else
6637SQLITE_PRIVATE const int sqlite3one;
6638#endif
6639#if defined(i386) || defined(__i386__) || defined(_M_IX86)\
6640                             || defined(__x86_64) || defined(__x86_64__)
6641# define SQLITE_BIGENDIAN    0
6642# define SQLITE_LITTLEENDIAN 1
6643# define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
6644#else
6645# define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
6646# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
6647# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
6648#endif
6649
6650/*
6651** Constants for the largest and smallest possible 64-bit signed integers.
6652** These macros are designed to work correctly on both 32-bit and 64-bit
6653** compilers.
6654*/
6655#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
6656#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
6657
6658/*
6659** Round up a number to the next larger multiple of 8.  This is used
6660** to force 8-byte alignment on 64-bit architectures.
6661*/
6662#define ROUND8(x)     (((x)+7)&~7)
6663
6664/*
6665** Round down to the nearest multiple of 8
6666*/
6667#define ROUNDDOWN8(x) ((x)&~7)
6668
6669/*
6670** Assert that the pointer X is aligned to an 8-byte boundary.  This
6671** macro is used only within assert() to verify that the code gets
6672** all alignment restrictions correct.
6673**
6674** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
6675** underlying malloc() implemention might return us 4-byte aligned
6676** pointers.  In that case, only verify 4-byte alignment.
6677*/
6678#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
6679# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
6680#else
6681# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
6682#endif
6683
6684
6685/*
6686** An instance of the following structure is used to store the busy-handler
6687** callback for a given sqlite handle.
6688**
6689** The sqlite.busyHandler member of the sqlite struct contains the busy
6690** callback for the database handle. Each pager opened via the sqlite
6691** handle is passed a pointer to sqlite.busyHandler. The busy-handler
6692** callback is currently invoked only from within pager.c.
6693*/
6694typedef struct BusyHandler BusyHandler;
6695struct BusyHandler {
6696  int (*xFunc)(void *,int);  /* The busy callback */
6697  void *pArg;                /* First arg to busy callback */
6698  int nBusy;                 /* Incremented with each busy call */
6699};
6700
6701/*
6702** Name of the master database table.  The master database table
6703** is a special table that holds the names and attributes of all
6704** user tables and indices.
6705*/
6706#define MASTER_NAME       "sqlite_master"
6707#define TEMP_MASTER_NAME  "sqlite_temp_master"
6708
6709/*
6710** The root-page of the master database table.
6711*/
6712#define MASTER_ROOT       1
6713
6714/*
6715** The name of the schema table.
6716*/
6717#define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
6718
6719/*
6720** A convenience macro that returns the number of elements in
6721** an array.
6722*/
6723#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
6724
6725/*
6726** The following value as a destructor means to use sqlite3DbFree().
6727** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
6728*/
6729#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
6730
6731/*
6732** When SQLITE_OMIT_WSD is defined, it means that the target platform does
6733** not support Writable Static Data (WSD) such as global and static variables.
6734** All variables must either be on the stack or dynamically allocated from
6735** the heap.  When WSD is unsupported, the variable declarations scattered
6736** throughout the SQLite code must become constants instead.  The SQLITE_WSD
6737** macro is used for this purpose.  And instead of referencing the variable
6738** directly, we use its constant as a key to lookup the run-time allocated
6739** buffer that holds real variable.  The constant is also the initializer
6740** for the run-time allocated buffer.
6741**
6742** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
6743** macros become no-ops and have zero performance impact.
6744*/
6745#ifdef SQLITE_OMIT_WSD
6746  #define SQLITE_WSD const
6747  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
6748  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
6749SQLITE_API   int sqlite3_wsd_init(int N, int J);
6750SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
6751#else
6752  #define SQLITE_WSD
6753  #define GLOBAL(t,v) v
6754  #define sqlite3GlobalConfig sqlite3Config
6755#endif
6756
6757/*
6758** The following macros are used to suppress compiler warnings and to
6759** make it clear to human readers when a function parameter is deliberately
6760** left unused within the body of a function. This usually happens when
6761** a function is called via a function pointer. For example the
6762** implementation of an SQL aggregate step callback may not use the
6763** parameter indicating the number of arguments passed to the aggregate,
6764** if it knows that this is enforced elsewhere.
6765**
6766** When a function parameter is not used at all within the body of a function,
6767** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
6768** However, these macros may also be used to suppress warnings related to
6769** parameters that may or may not be used depending on compilation options.
6770** For example those parameters only used in assert() statements. In these
6771** cases the parameters are named as per the usual conventions.
6772*/
6773#define UNUSED_PARAMETER(x) (void)(x)
6774#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
6775
6776/*
6777** Forward references to structures
6778*/
6779typedef struct AggInfo AggInfo;
6780typedef struct AuthContext AuthContext;
6781typedef struct AutoincInfo AutoincInfo;
6782typedef struct Bitvec Bitvec;
6783typedef struct RowSet RowSet;
6784typedef struct CollSeq CollSeq;
6785typedef struct Column Column;
6786typedef struct Db Db;
6787typedef struct Schema Schema;
6788typedef struct Expr Expr;
6789typedef struct ExprList ExprList;
6790typedef struct ExprSpan ExprSpan;
6791typedef struct FKey FKey;
6792typedef struct FuncDef FuncDef;
6793typedef struct FuncDefHash FuncDefHash;
6794typedef struct IdList IdList;
6795typedef struct Index Index;
6796typedef struct IndexSample IndexSample;
6797typedef struct KeyClass KeyClass;
6798typedef struct KeyInfo KeyInfo;
6799typedef struct Lookaside Lookaside;
6800typedef struct LookasideSlot LookasideSlot;
6801typedef struct Module Module;
6802typedef struct NameContext NameContext;
6803typedef struct Parse Parse;
6804typedef struct Savepoint Savepoint;
6805typedef struct Select Select;
6806typedef struct SrcList SrcList;
6807typedef struct StrAccum StrAccum;
6808typedef struct Table Table;
6809typedef struct TableLock TableLock;
6810typedef struct Token Token;
6811typedef struct TriggerPrg TriggerPrg;
6812typedef struct TriggerStep TriggerStep;
6813typedef struct Trigger Trigger;
6814typedef struct UnpackedRecord UnpackedRecord;
6815typedef struct VTable VTable;
6816typedef struct Walker Walker;
6817typedef struct WherePlan WherePlan;
6818typedef struct WhereInfo WhereInfo;
6819typedef struct WhereLevel WhereLevel;
6820
6821/*
6822** Defer sourcing vdbe.h and btree.h until after the "u8" and
6823** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
6824** pointer types (i.e. FuncDef) defined above.
6825*/
6826/************** Include btree.h in the middle of sqliteInt.h *****************/
6827/************** Begin file btree.h *******************************************/
6828/*
6829** 2001 September 15
6830**
6831** The author disclaims copyright to this source code.  In place of
6832** a legal notice, here is a blessing:
6833**
6834**    May you do good and not evil.
6835**    May you find forgiveness for yourself and forgive others.
6836**    May you share freely, never taking more than you give.
6837**
6838*************************************************************************
6839** This header file defines the interface that the sqlite B-Tree file
6840** subsystem.  See comments in the source code for a detailed description
6841** of what each interface routine does.
6842*/
6843#ifndef _BTREE_H_
6844#define _BTREE_H_
6845
6846/* TODO: This definition is just included so other modules compile. It
6847** needs to be revisited.
6848*/
6849#define SQLITE_N_BTREE_META 10
6850
6851/*
6852** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
6853** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
6854*/
6855#ifndef SQLITE_DEFAULT_AUTOVACUUM
6856  #define SQLITE_DEFAULT_AUTOVACUUM 0
6857#endif
6858
6859#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
6860#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
6861#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
6862
6863/*
6864** Forward declarations of structure
6865*/
6866typedef struct Btree Btree;
6867typedef struct BtCursor BtCursor;
6868typedef struct BtShared BtShared;
6869typedef struct BtreeMutexArray BtreeMutexArray;
6870
6871/*
6872** This structure records all of the Btrees that need to hold
6873** a mutex before we enter sqlite3VdbeExec().  The Btrees are
6874** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
6875** we can always lock and unlock them all quickly.
6876*/
6877struct BtreeMutexArray {
6878  int nMutex;
6879  Btree *aBtree[SQLITE_MAX_ATTACHED+1];
6880};
6881
6882
6883SQLITE_PRIVATE int sqlite3BtreeOpen(
6884  const char *zFilename,   /* Name of database file to open */
6885  sqlite3 *db,             /* Associated database connection */
6886  Btree **ppBtree,         /* Return open Btree* here */
6887  int flags,               /* Flags */
6888  int vfsFlags             /* Flags passed through to VFS open */
6889);
6890
6891/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
6892** following values.
6893**
6894** NOTE:  These values must match the corresponding PAGER_ values in
6895** pager.h.
6896*/
6897#define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
6898#define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
6899#define BTREE_MEMORY        4  /* In-memory DB.  No argument */
6900#define BTREE_READONLY      8  /* Open the database in read-only mode */
6901#define BTREE_READWRITE    16  /* Open for both reading and writing */
6902#define BTREE_CREATE       32  /* Create the database if it does not exist */
6903
6904SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
6905SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
6906SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
6907SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
6908SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
6909SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
6910SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
6911SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
6912SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
6913SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
6914SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
6915SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
6916SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
6917SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
6918SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
6919SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
6920SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
6921SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
6922SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
6923SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
6924SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
6925SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
6926SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
6927SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
6928
6929SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
6930SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
6931SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
6932
6933SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
6934
6935/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
6936** of the following flags:
6937*/
6938#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
6939#define BTREE_ZERODATA   2    /* Table has keys only - no data */
6940#define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */
6941
6942SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
6943SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
6944SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
6945
6946SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
6947SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
6948
6949/*
6950** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
6951** should be one of the following values. The integer values are assigned
6952** to constants so that the offset of the corresponding field in an
6953** SQLite database header may be found using the following formula:
6954**
6955**   offset = 36 + (idx * 4)
6956**
6957** For example, the free-page-count field is located at byte offset 36 of
6958** the database file header. The incr-vacuum-flag field is located at
6959** byte offset 64 (== 36+4*7).
6960*/
6961#define BTREE_FREE_PAGE_COUNT     0
6962#define BTREE_SCHEMA_VERSION      1
6963#define BTREE_FILE_FORMAT         2
6964#define BTREE_DEFAULT_CACHE_SIZE  3
6965#define BTREE_LARGEST_ROOT_PAGE   4
6966#define BTREE_TEXT_ENCODING       5
6967#define BTREE_USER_VERSION        6
6968#define BTREE_INCR_VACUUM         7
6969
6970SQLITE_PRIVATE int sqlite3BtreeCursor(
6971  Btree*,                              /* BTree containing table to open */
6972  int iTable,                          /* Index of root page */
6973  int wrFlag,                          /* 1 for writing.  0 for read-only */
6974  struct KeyInfo*,                     /* First argument to compare function */
6975  BtCursor *pCursor                    /* Space to write cursor structure */
6976);
6977SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
6978SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
6979
6980SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
6981SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
6982  BtCursor*,
6983  UnpackedRecord *pUnKey,
6984  i64 intKey,
6985  int bias,
6986  int *pRes
6987);
6988SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
6989SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
6990SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
6991                                  const void *pData, int nData,
6992                                  int nZero, int bias, int seekResult);
6993SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
6994SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
6995SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
6996SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
6997SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
6998SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
6999SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
7000SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
7001SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
7002SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
7003SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
7004SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
7005SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
7006
7007SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
7008SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
7009
7010SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
7011SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7012SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
7013
7014#ifndef NDEBUG
7015SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
7016#endif
7017
7018#ifndef SQLITE_OMIT_BTREECOUNT
7019SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
7020#endif
7021
7022#ifdef SQLITE_TEST
7023SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
7024SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7025#endif
7026
7027/*
7028** If we are not using shared cache, then there is no need to
7029** use mutexes to access the BtShared structures.  So make the
7030** Enter and Leave procedures no-ops.
7031*/
7032#ifndef SQLITE_OMIT_SHARED_CACHE
7033SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
7034SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
7035#else
7036# define sqlite3BtreeEnter(X)
7037# define sqlite3BtreeEnterAll(X)
7038#endif
7039
7040#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7041SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
7042SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
7043SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
7044SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
7045SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
7046SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
7047SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
7048#ifndef NDEBUG
7049  /* These routines are used inside assert() statements only. */
7050SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
7051SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7052#endif
7053#else
7054
7055# define sqlite3BtreeLeave(X)
7056# define sqlite3BtreeEnterCursor(X)
7057# define sqlite3BtreeLeaveCursor(X)
7058# define sqlite3BtreeLeaveAll(X)
7059# define sqlite3BtreeMutexArrayEnter(X)
7060# define sqlite3BtreeMutexArrayLeave(X)
7061# define sqlite3BtreeMutexArrayInsert(X,Y)
7062
7063# define sqlite3BtreeHoldsMutex(X) 1
7064# define sqlite3BtreeHoldsAllMutexes(X) 1
7065#endif
7066
7067
7068#endif /* _BTREE_H_ */
7069
7070/************** End of btree.h ***********************************************/
7071/************** Continuing where we left off in sqliteInt.h ******************/
7072/************** Include vdbe.h in the middle of sqliteInt.h ******************/
7073/************** Begin file vdbe.h ********************************************/
7074/*
7075** 2001 September 15
7076**
7077** The author disclaims copyright to this source code.  In place of
7078** a legal notice, here is a blessing:
7079**
7080**    May you do good and not evil.
7081**    May you find forgiveness for yourself and forgive others.
7082**    May you share freely, never taking more than you give.
7083**
7084*************************************************************************
7085** Header file for the Virtual DataBase Engine (VDBE)
7086**
7087** This header defines the interface to the virtual database engine
7088** or VDBE.  The VDBE implements an abstract machine that runs a
7089** simple program to access and modify the underlying database.
7090*/
7091#ifndef _SQLITE_VDBE_H_
7092#define _SQLITE_VDBE_H_
7093
7094/*
7095** A single VDBE is an opaque structure named "Vdbe".  Only routines
7096** in the source file sqliteVdbe.c are allowed to see the insides
7097** of this structure.
7098*/
7099typedef struct Vdbe Vdbe;
7100
7101/*
7102** The names of the following types declared in vdbeInt.h are required
7103** for the VdbeOp definition.
7104*/
7105typedef struct VdbeFunc VdbeFunc;
7106typedef struct Mem Mem;
7107typedef struct SubProgram SubProgram;
7108
7109/*
7110** A single instruction of the virtual machine has an opcode
7111** and as many as three operands.  The instruction is recorded
7112** as an instance of the following structure:
7113*/
7114struct VdbeOp {
7115  u8 opcode;          /* What operation to perform */
7116  signed char p4type; /* One of the P4_xxx constants for p4 */
7117  u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
7118  u8 p5;              /* Fifth parameter is an unsigned character */
7119  int p1;             /* First operand */
7120  int p2;             /* Second parameter (often the jump destination) */
7121  int p3;             /* The third parameter */
7122  union {             /* fourth parameter */
7123    int i;                 /* Integer value if p4type==P4_INT32 */
7124    void *p;               /* Generic pointer */
7125    char *z;               /* Pointer to data for string (char array) types */
7126    i64 *pI64;             /* Used when p4type is P4_INT64 */
7127    double *pReal;         /* Used when p4type is P4_REAL */
7128    FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
7129    VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
7130    CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
7131    Mem *pMem;             /* Used when p4type is P4_MEM */
7132    VTable *pVtab;         /* Used when p4type is P4_VTAB */
7133    KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
7134    int *ai;               /* Used when p4type is P4_INTARRAY */
7135    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
7136  } p4;
7137#ifdef SQLITE_DEBUG
7138  char *zComment;          /* Comment to improve readability */
7139#endif
7140#ifdef VDBE_PROFILE
7141  int cnt;                 /* Number of times this instruction was executed */
7142  u64 cycles;              /* Total time spent executing this instruction */
7143#endif
7144};
7145typedef struct VdbeOp VdbeOp;
7146
7147
7148/*
7149** A sub-routine used to implement a trigger program.
7150*/
7151struct SubProgram {
7152  VdbeOp *aOp;                  /* Array of opcodes for sub-program */
7153  int nOp;                      /* Elements in aOp[] */
7154  int nMem;                     /* Number of memory cells required */
7155  int nCsr;                     /* Number of cursors required */
7156  int nRef;                     /* Number of pointers to this structure */
7157  void *token;                  /* id that may be used to recursive triggers */
7158};
7159
7160/*
7161** A smaller version of VdbeOp used for the VdbeAddOpList() function because
7162** it takes up less space.
7163*/
7164struct VdbeOpList {
7165  u8 opcode;          /* What operation to perform */
7166  signed char p1;     /* First operand */
7167  signed char p2;     /* Second parameter (often the jump destination) */
7168  signed char p3;     /* Third parameter */
7169};
7170typedef struct VdbeOpList VdbeOpList;
7171
7172/*
7173** Allowed values of VdbeOp.p4type
7174*/
7175#define P4_NOTUSED    0   /* The P4 parameter is not used */
7176#define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
7177#define P4_STATIC   (-2)  /* Pointer to a static string */
7178#define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
7179#define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
7180#define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
7181#define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
7182#define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
7183#define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
7184#define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
7185#define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
7186#define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
7187#define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
7188#define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
7189#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
7190#define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
7191
7192/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
7193** is made.  That copy is freed when the Vdbe is finalized.  But if the
7194** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
7195** gets freed when the Vdbe is finalized so it still should be obtained
7196** from a single sqliteMalloc().  But no copy is made and the calling
7197** function should *not* try to free the KeyInfo.
7198*/
7199#define P4_KEYINFO_HANDOFF (-16)
7200#define P4_KEYINFO_STATIC  (-17)
7201
7202/*
7203** The Vdbe.aColName array contains 5n Mem structures, where n is the
7204** number of columns of data returned by the statement.
7205*/
7206#define COLNAME_NAME     0
7207#define COLNAME_DECLTYPE 1
7208#define COLNAME_DATABASE 2
7209#define COLNAME_TABLE    3
7210#define COLNAME_COLUMN   4
7211#ifdef SQLITE_ENABLE_COLUMN_METADATA
7212# define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
7213#else
7214# ifdef SQLITE_OMIT_DECLTYPE
7215#   define COLNAME_N      1      /* Store only the name */
7216# else
7217#   define COLNAME_N      2      /* Store the name and decltype */
7218# endif
7219#endif
7220
7221/*
7222** The following macro converts a relative address in the p2 field
7223** of a VdbeOp structure into a negative number so that
7224** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
7225** the macro again restores the address.
7226*/
7227#define ADDR(X)  (-1-(X))
7228
7229/*
7230** The makefile scans the vdbe.c source file and creates the "opcodes.h"
7231** header file that defines a number for each opcode used by the VDBE.
7232*/
7233/************** Include opcodes.h in the middle of vdbe.h ********************/
7234/************** Begin file opcodes.h *****************************************/
7235/* Automatically generated.  Do not edit */
7236/* See the mkopcodeh.awk script for details */
7237#define OP_Goto                                 1
7238#define OP_Gosub                                2
7239#define OP_Return                               3
7240#define OP_Yield                                4
7241#define OP_HaltIfNull                           5
7242#define OP_Halt                                 6
7243#define OP_Integer                              7
7244#define OP_Int64                                8
7245#define OP_Real                               130   /* same as TK_FLOAT    */
7246#define OP_String8                             94   /* same as TK_STRING   */
7247#define OP_String                               9
7248#define OP_Null                                10
7249#define OP_Blob                                11
7250#define OP_Variable                            12
7251#define OP_Move                                13
7252#define OP_Copy                                14
7253#define OP_SCopy                               15
7254#define OP_ResultRow                           16
7255#define OP_Concat                              91   /* same as TK_CONCAT   */
7256#define OP_Add                                 86   /* same as TK_PLUS     */
7257#define OP_Subtract                            87   /* same as TK_MINUS    */
7258#define OP_Multiply                            88   /* same as TK_STAR     */
7259#define OP_Divide                              89   /* same as TK_SLASH    */
7260#define OP_Remainder                           90   /* same as TK_REM      */
7261#define OP_CollSeq                             17
7262#define OP_Function                            18
7263#define OP_BitAnd                              82   /* same as TK_BITAND   */
7264#define OP_BitOr                               83   /* same as TK_BITOR    */
7265#define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
7266#define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
7267#define OP_AddImm                              20
7268#define OP_MustBeInt                           21
7269#define OP_RealAffinity                        22
7270#define OP_ToText                             141   /* same as TK_TO_TEXT  */
7271#define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
7272#define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
7273#define OP_ToInt                              144   /* same as TK_TO_INT   */
7274#define OP_ToReal                             145   /* same as TK_TO_REAL  */
7275#define OP_Eq                                  76   /* same as TK_EQ       */
7276#define OP_Ne                                  75   /* same as TK_NE       */
7277#define OP_Lt                                  79   /* same as TK_LT       */
7278#define OP_Le                                  78   /* same as TK_LE       */
7279#define OP_Gt                                  77   /* same as TK_GT       */
7280#define OP_Ge                                  80   /* same as TK_GE       */
7281#define OP_Permutation                         23
7282#define OP_Compare                             24
7283#define OP_Jump                                25
7284#define OP_And                                 69   /* same as TK_AND      */
7285#define OP_Or                                  68   /* same as TK_OR       */
7286#define OP_Not                                 19   /* same as TK_NOT      */
7287#define OP_BitNot                              93   /* same as TK_BITNOT   */
7288#define OP_If                                  26
7289#define OP_IfNot                               27
7290#define OP_IsNull                              73   /* same as TK_ISNULL   */
7291#define OP_NotNull                             74   /* same as TK_NOTNULL  */
7292#define OP_Column                              28
7293#define OP_Affinity                            29
7294#define OP_MakeRecord                          30
7295#define OP_Count                               31
7296#define OP_Savepoint                           32
7297#define OP_AutoCommit                          33
7298#define OP_Transaction                         34
7299#define OP_ReadCookie                          35
7300#define OP_SetCookie                           36
7301#define OP_VerifyCookie                        37
7302#define OP_OpenRead                            38
7303#define OP_OpenWrite                           39
7304#define OP_OpenEphemeral                       40
7305#define OP_OpenPseudo                          41
7306#define OP_Close                               42
7307#define OP_SeekLt                              43
7308#define OP_SeekLe                              44
7309#define OP_SeekGe                              45
7310#define OP_SeekGt                              46
7311#define OP_Seek                                47
7312#define OP_NotFound                            48
7313#define OP_Found                               49
7314#define OP_IsUnique                            50
7315#define OP_NotExists                           51
7316#define OP_Sequence                            52
7317#define OP_NewRowid                            53
7318#define OP_Insert                              54
7319#define OP_InsertInt                           55
7320#define OP_Delete                              56
7321#define OP_ResetCount                          57
7322#define OP_RowKey                              58
7323#define OP_RowData                             59
7324#define OP_Rowid                               60
7325#define OP_NullRow                             61
7326#define OP_Last                                62
7327#define OP_Sort                                63
7328#define OP_Rewind                              64
7329#define OP_Prev                                65
7330#define OP_Next                                66
7331#define OP_IdxInsert                           67
7332#define OP_IdxDelete                           70
7333#define OP_IdxRowid                            71
7334#define OP_IdxLT                               72
7335#define OP_IdxGE                               81
7336#define OP_Destroy                             92
7337#define OP_Clear                               95
7338#define OP_CreateIndex                         96
7339#define OP_CreateTable                         97
7340#define OP_ParseSchema                         98
7341#define OP_LoadAnalysis                        99
7342#define OP_DropTable                          100
7343#define OP_DropIndex                          101
7344#define OP_DropTrigger                        102
7345#define OP_IntegrityCk                        103
7346#define OP_RowSetAdd                          104
7347#define OP_RowSetRead                         105
7348#define OP_RowSetTest                         106
7349#define OP_Program                            107
7350#define OP_Param                              108
7351#define OP_FkCounter                          109
7352#define OP_FkIfZero                           110
7353#define OP_MemMax                             111
7354#define OP_IfPos                              112
7355#define OP_IfNeg                              113
7356#define OP_IfZero                             114
7357#define OP_AggStep                            115
7358#define OP_AggFinal                           116
7359#define OP_Vacuum                             117
7360#define OP_IncrVacuum                         118
7361#define OP_Expire                             119
7362#define OP_TableLock                          120
7363#define OP_VBegin                             121
7364#define OP_VCreate                            122
7365#define OP_VDestroy                           123
7366#define OP_VOpen                              124
7367#define OP_VFilter                            125
7368#define OP_VColumn                            126
7369#define OP_VNext                              127
7370#define OP_VRename                            128
7371#define OP_VUpdate                            129
7372#define OP_Pagecount                          131
7373#define OP_Trace                              132
7374#define OP_Noop                               133
7375#define OP_Explain                            134
7376
7377/* The following opcode values are never used */
7378#define OP_NotUsed_135                        135
7379#define OP_NotUsed_136                        136
7380#define OP_NotUsed_137                        137
7381#define OP_NotUsed_138                        138
7382#define OP_NotUsed_139                        139
7383#define OP_NotUsed_140                        140
7384
7385
7386/* Properties such as "out2" or "jump" that are specified in
7387** comments following the "case" for each opcode in the vdbe.c
7388** are encoded into bitvectors as follows:
7389*/
7390#define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
7391#define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
7392#define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
7393#define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
7394#define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
7395#define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
7396#define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
7397#define OPFLG_INITIALIZER {\
7398/*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
7399/*   8 */ 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x24, 0x24,\
7400/*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
7401/*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
7402/*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
7403/*  40 */ 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, 0x08,\
7404/*  48 */ 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00, 0x00,\
7405/*  56 */ 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x01,\
7406/*  64 */ 0x01, 0x01, 0x01, 0x08, 0x4c, 0x4c, 0x00, 0x02,\
7407/*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
7408/*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
7409/*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x02, 0x24, 0x02, 0x00,\
7410/*  96 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
7411/* 104 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
7412/* 112 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00,\
7413/* 120 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01,\
7414/* 128 */ 0x00, 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00,\
7415/* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
7416/* 144 */ 0x04, 0x04,}
7417
7418/************** End of opcodes.h *********************************************/
7419/************** Continuing where we left off in vdbe.h ***********************/
7420
7421/*
7422** Prototypes for the VDBE interface.  See comments on the implementation
7423** for a description of what each of these routines does.
7424*/
7425SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
7426SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
7427SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
7428SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
7429SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
7430SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
7431SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
7432SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
7433SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
7434SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
7435SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
7436SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
7437SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
7438SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
7439SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
7440SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
7441SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
7442SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
7443SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
7444SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
7445SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
7446SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
7447SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
7448SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
7449#ifdef SQLITE_DEBUG
7450SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
7451SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
7452#endif
7453SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
7454SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
7455SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
7456SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
7457SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
7458SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
7459SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
7460SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
7461SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
7462SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *, SubProgram *, int);
7463SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
7464SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
7465#ifndef SQLITE_OMIT_TRACE
7466SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
7467#endif
7468
7469SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
7470SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
7471SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
7472
7473
7474#ifndef NDEBUG
7475SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
7476# define VdbeComment(X)  sqlite3VdbeComment X
7477SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
7478# define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
7479#else
7480# define VdbeComment(X)
7481# define VdbeNoopComment(X)
7482#endif
7483
7484#endif
7485
7486/************** End of vdbe.h ************************************************/
7487/************** Continuing where we left off in sqliteInt.h ******************/
7488/************** Include pager.h in the middle of sqliteInt.h *****************/
7489/************** Begin file pager.h *******************************************/
7490/*
7491** 2001 September 15
7492**
7493** The author disclaims copyright to this source code.  In place of
7494** a legal notice, here is a blessing:
7495**
7496**    May you do good and not evil.
7497**    May you find forgiveness for yourself and forgive others.
7498**    May you share freely, never taking more than you give.
7499**
7500*************************************************************************
7501** This header file defines the interface that the sqlite page cache
7502** subsystem.  The page cache subsystem reads and writes a file a page
7503** at a time and provides a journal for rollback.
7504*/
7505
7506#ifndef _PAGER_H_
7507#define _PAGER_H_
7508
7509/*
7510** Default maximum size for persistent journal files. A negative
7511** value means no limit. This value may be overridden using the
7512** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
7513*/
7514#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
7515  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
7516#endif
7517
7518/*
7519** The type used to represent a page number.  The first page in a file
7520** is called page 1.  0 is used to represent "not a page".
7521*/
7522typedef u32 Pgno;
7523
7524/*
7525** Each open file is managed by a separate instance of the "Pager" structure.
7526*/
7527typedef struct Pager Pager;
7528
7529/*
7530** Handle type for pages.
7531*/
7532typedef struct PgHdr DbPage;
7533
7534/*
7535** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
7536** reserved for working around a windows/posix incompatibility). It is
7537** used in the journal to signify that the remainder of the journal file
7538** is devoted to storing a master journal name - there are no more pages to
7539** roll back. See comments for function writeMasterJournal() in pager.c
7540** for details.
7541*/
7542#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
7543
7544/*
7545** Allowed values for the flags parameter to sqlite3PagerOpen().
7546**
7547** NOTE: These values must match the corresponding BTREE_ values in btree.h.
7548*/
7549#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
7550#define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
7551
7552/*
7553** Valid values for the second argument to sqlite3PagerLockingMode().
7554*/
7555#define PAGER_LOCKINGMODE_QUERY      -1
7556#define PAGER_LOCKINGMODE_NORMAL      0
7557#define PAGER_LOCKINGMODE_EXCLUSIVE   1
7558
7559/*
7560** Valid values for the second argument to sqlite3PagerJournalMode().
7561*/
7562#define PAGER_JOURNALMODE_QUERY      -1
7563#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
7564#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
7565#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
7566#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
7567#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
7568
7569/*
7570** The remainder of this file contains the declarations of the functions
7571** that make up the Pager sub-system API. See source code comments for
7572** a detailed description of each routine.
7573*/
7574
7575/* Open and close a Pager connection. */
7576SQLITE_PRIVATE int sqlite3PagerOpen(
7577  sqlite3_vfs*,
7578  Pager **ppPager,
7579  const char*,
7580  int,
7581  int,
7582  int,
7583  void(*)(DbPage*)
7584);
7585SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
7586SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
7587
7588/* Functions used to configure a Pager object. */
7589SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
7590SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*, int);
7591SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
7592SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
7593SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
7594SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
7595SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int);
7596SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
7597SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
7598
7599/* Functions used to obtain and release page references. */
7600SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
7601#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
7602SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
7603SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
7604SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
7605
7606/* Operations on page references. */
7607SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
7608SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
7609SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
7610SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
7611SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
7612SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
7613
7614/* Functions used to manage pager transactions and savepoints. */
7615SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
7616SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
7617SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
7618SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
7619SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
7620SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
7621SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
7622SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
7623SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
7624
7625/* Functions used to query pager state and configuration. */
7626SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
7627SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
7628SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
7629SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
7630SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
7631SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
7632SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
7633SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
7634SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
7635
7636/* Functions used to truncate the database file. */
7637SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
7638
7639/* Functions to support testing and debugging. */
7640#if !defined(NDEBUG) || defined(SQLITE_TEST)
7641SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
7642SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
7643#endif
7644#ifdef SQLITE_TEST
7645SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
7646SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
7647  void disable_simulated_io_errors(void);
7648  void enable_simulated_io_errors(void);
7649#else
7650# define disable_simulated_io_errors()
7651# define enable_simulated_io_errors()
7652#endif
7653
7654#endif /* _PAGER_H_ */
7655
7656/************** End of pager.h ***********************************************/
7657/************** Continuing where we left off in sqliteInt.h ******************/
7658/************** Include pcache.h in the middle of sqliteInt.h ****************/
7659/************** Begin file pcache.h ******************************************/
7660/*
7661** 2008 August 05
7662**
7663** The author disclaims copyright to this source code.  In place of
7664** a legal notice, here is a blessing:
7665**
7666**    May you do good and not evil.
7667**    May you find forgiveness for yourself and forgive others.
7668**    May you share freely, never taking more than you give.
7669**
7670*************************************************************************
7671** This header file defines the interface that the sqlite page cache
7672** subsystem.
7673*/
7674
7675#ifndef _PCACHE_H_
7676
7677typedef struct PgHdr PgHdr;
7678typedef struct PCache PCache;
7679
7680/*
7681** Every page in the cache is controlled by an instance of the following
7682** structure.
7683*/
7684struct PgHdr {
7685  void *pData;                   /* Content of this page */
7686  void *pExtra;                  /* Extra content */
7687  PgHdr *pDirty;                 /* Transient list of dirty pages */
7688  Pgno pgno;                     /* Page number for this page */
7689  Pager *pPager;                 /* The pager this page is part of */
7690#ifdef SQLITE_CHECK_PAGES
7691  u32 pageHash;                  /* Hash of page content */
7692#endif
7693  u16 flags;                     /* PGHDR flags defined below */
7694
7695  /**********************************************************************
7696  ** Elements above are public.  All that follows is private to pcache.c
7697  ** and should not be accessed by other modules.
7698  */
7699  i16 nRef;                      /* Number of users of this page */
7700  PCache *pCache;                /* Cache that owns this page */
7701
7702  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
7703  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
7704};
7705
7706/* Bit values for PgHdr.flags */
7707#define PGHDR_DIRTY             0x002  /* Page has changed */
7708#define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
7709                                       ** writing this page to the database */
7710#define PGHDR_NEED_READ         0x008  /* Content is unread */
7711#define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
7712#define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
7713
7714/* Initialize and shutdown the page cache subsystem */
7715SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
7716SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
7717
7718/* Page cache buffer management:
7719** These routines implement SQLITE_CONFIG_PAGECACHE.
7720*/
7721SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
7722
7723/* Create a new pager cache.
7724** Under memory stress, invoke xStress to try to make pages clean.
7725** Only clean and unpinned pages can be reclaimed.
7726*/
7727SQLITE_PRIVATE void sqlite3PcacheOpen(
7728  int szPage,                    /* Size of every page */
7729  int szExtra,                   /* Extra space associated with each page */
7730  int bPurgeable,                /* True if pages are on backing store */
7731  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
7732  void *pStress,                 /* Argument to xStress */
7733  PCache *pToInit                /* Preallocated space for the PCache */
7734);
7735
7736/* Modify the page-size after the cache has been created. */
7737SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
7738
7739/* Return the size in bytes of a PCache object.  Used to preallocate
7740** storage space.
7741*/
7742SQLITE_PRIVATE int sqlite3PcacheSize(void);
7743
7744/* One release per successful fetch.  Page is pinned until released.
7745** Reference counted.
7746*/
7747SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
7748SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
7749
7750SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
7751SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
7752SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
7753SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
7754
7755/* Change a page number.  Used by incr-vacuum. */
7756SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
7757
7758/* Remove all pages with pgno>x.  Reset the cache if x==0 */
7759SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
7760
7761/* Get a list of all dirty pages in the cache, sorted by page number */
7762SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
7763
7764/* Reset and close the cache object */
7765SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
7766
7767/* Clear flags from pages of the page cache */
7768SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
7769
7770/* Discard the contents of the cache */
7771SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
7772
7773/* Return the total number of outstanding page references */
7774SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
7775
7776/* Increment the reference count of an existing page */
7777SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
7778
7779SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
7780
7781/* Return the total number of pages stored in the cache */
7782SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
7783
7784#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
7785/* Iterate through all dirty pages currently stored in the cache. This
7786** interface is only available if SQLITE_CHECK_PAGES is defined when the
7787** library is built.
7788*/
7789SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
7790#endif
7791
7792/* Set and get the suggested cache-size for the specified pager-cache.
7793**
7794** If no global maximum is configured, then the system attempts to limit
7795** the total number of pages cached by purgeable pager-caches to the sum
7796** of the suggested cache-sizes.
7797*/
7798SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
7799#ifdef SQLITE_TEST
7800SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
7801#endif
7802
7803#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
7804/* Try to return memory used by the pcache module to the main memory heap */
7805SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
7806#endif
7807
7808#ifdef SQLITE_TEST
7809SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
7810#endif
7811
7812SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
7813
7814#endif /* _PCACHE_H_ */
7815
7816/************** End of pcache.h **********************************************/
7817/************** Continuing where we left off in sqliteInt.h ******************/
7818
7819/************** Include os.h in the middle of sqliteInt.h ********************/
7820/************** Begin file os.h **********************************************/
7821/*
7822** 2001 September 16
7823**
7824** The author disclaims copyright to this source code.  In place of
7825** a legal notice, here is a blessing:
7826**
7827**    May you do good and not evil.
7828**    May you find forgiveness for yourself and forgive others.
7829**    May you share freely, never taking more than you give.
7830**
7831******************************************************************************
7832**
7833** This header file (together with is companion C source-code file
7834** "os.c") attempt to abstract the underlying operating system so that
7835** the SQLite library will work on both POSIX and windows systems.
7836**
7837** This header file is #include-ed by sqliteInt.h and thus ends up
7838** being included by every source file.
7839*/
7840#ifndef _SQLITE_OS_H_
7841#define _SQLITE_OS_H_
7842
7843/*
7844** Figure out if we are dealing with Unix, Windows, or some other
7845** operating system.  After the following block of preprocess macros,
7846** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
7847** will defined to either 1 or 0.  One of the four will be 1.  The other
7848** three will be 0.
7849*/
7850#if defined(SQLITE_OS_OTHER)
7851# if SQLITE_OS_OTHER==1
7852#   undef SQLITE_OS_UNIX
7853#   define SQLITE_OS_UNIX 0
7854#   undef SQLITE_OS_WIN
7855#   define SQLITE_OS_WIN 0
7856#   undef SQLITE_OS_OS2
7857#   define SQLITE_OS_OS2 0
7858# else
7859#   undef SQLITE_OS_OTHER
7860# endif
7861#endif
7862#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
7863# define SQLITE_OS_OTHER 0
7864# ifndef SQLITE_OS_WIN
7865#   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
7866#     define SQLITE_OS_WIN 1
7867#     define SQLITE_OS_UNIX 0
7868#     define SQLITE_OS_OS2 0
7869#   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
7870#     define SQLITE_OS_WIN 0
7871#     define SQLITE_OS_UNIX 0
7872#     define SQLITE_OS_OS2 1
7873#   else
7874#     define SQLITE_OS_WIN 0
7875#     define SQLITE_OS_UNIX 1
7876#     define SQLITE_OS_OS2 0
7877#  endif
7878# else
7879#  define SQLITE_OS_UNIX 0
7880#  define SQLITE_OS_OS2 0
7881# endif
7882#else
7883# ifndef SQLITE_OS_WIN
7884#  define SQLITE_OS_WIN 0
7885# endif
7886#endif
7887
7888/*
7889** Determine if we are dealing with WindowsCE - which has a much
7890** reduced API.
7891*/
7892#if defined(_WIN32_WCE)
7893# define SQLITE_OS_WINCE 1
7894#else
7895# define SQLITE_OS_WINCE 0
7896#endif
7897
7898
7899/*
7900** Define the maximum size of a temporary filename
7901*/
7902#if SQLITE_OS_WIN
7903# include <windows.h>
7904# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
7905#elif SQLITE_OS_OS2
7906# if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
7907#  include <os2safe.h> /* has to be included before os2.h for linking to work */
7908# endif
7909# define INCL_DOSDATETIME
7910# define INCL_DOSFILEMGR
7911# define INCL_DOSERRORS
7912# define INCL_DOSMISC
7913# define INCL_DOSPROCESS
7914# define INCL_DOSMODULEMGR
7915# define INCL_DOSSEMAPHORES
7916# include <os2.h>
7917# include <uconv.h>
7918# define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
7919#else
7920# define SQLITE_TEMPNAME_SIZE 200
7921#endif
7922
7923/* If the SET_FULLSYNC macro is not defined above, then make it
7924** a no-op
7925*/
7926#ifndef SET_FULLSYNC
7927# define SET_FULLSYNC(x,y)
7928#endif
7929
7930/*
7931** The default size of a disk sector
7932*/
7933#ifndef SQLITE_DEFAULT_SECTOR_SIZE
7934# define SQLITE_DEFAULT_SECTOR_SIZE 512
7935#endif
7936
7937/*
7938** Temporary files are named starting with this prefix followed by 16 random
7939** alphanumeric characters, and no file extension. They are stored in the
7940** OS's standard temporary file directory, and are deleted prior to exit.
7941** If sqlite is being embedded in another program, you may wish to change the
7942** prefix to reflect your program's name, so that if your program exits
7943** prematurely, old temporary files can be easily identified. This can be done
7944** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
7945**
7946** 2006-10-31:  The default prefix used to be "sqlite_".  But then
7947** Mcafee started using SQLite in their anti-virus product and it
7948** started putting files with the "sqlite" name in the c:/temp folder.
7949** This annoyed many windows users.  Those users would then do a
7950** Google search for "sqlite", find the telephone numbers of the
7951** developers and call to wake them up at night and complain.
7952** For this reason, the default name prefix is changed to be "sqlite"
7953** spelled backwards.  So the temp files are still identified, but
7954** anybody smart enough to figure out the code is also likely smart
7955** enough to know that calling the developer will not help get rid
7956** of the file.
7957*/
7958#ifndef SQLITE_TEMP_FILE_PREFIX
7959# define SQLITE_TEMP_FILE_PREFIX "etilqs_"
7960#endif
7961
7962/*
7963** The following values may be passed as the second argument to
7964** sqlite3OsLock(). The various locks exhibit the following semantics:
7965**
7966** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
7967** RESERVED:  A single process may hold a RESERVED lock on a file at
7968**            any time. Other processes may hold and obtain new SHARED locks.
7969** PENDING:   A single process may hold a PENDING lock on a file at
7970**            any one time. Existing SHARED locks may persist, but no new
7971**            SHARED locks may be obtained by other processes.
7972** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
7973**
7974** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
7975** process that requests an EXCLUSIVE lock may actually obtain a PENDING
7976** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
7977** sqlite3OsLock().
7978*/
7979#define NO_LOCK         0
7980#define SHARED_LOCK     1
7981#define RESERVED_LOCK   2
7982#define PENDING_LOCK    3
7983#define EXCLUSIVE_LOCK  4
7984
7985/*
7986** File Locking Notes:  (Mostly about windows but also some info for Unix)
7987**
7988** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
7989** those functions are not available.  So we use only LockFile() and
7990** UnlockFile().
7991**
7992** LockFile() prevents not just writing but also reading by other processes.
7993** A SHARED_LOCK is obtained by locking a single randomly-chosen
7994** byte out of a specific range of bytes. The lock byte is obtained at
7995** random so two separate readers can probably access the file at the
7996** same time, unless they are unlucky and choose the same lock byte.
7997** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
7998** There can only be one writer.  A RESERVED_LOCK is obtained by locking
7999** a single byte of the file that is designated as the reserved lock byte.
8000** A PENDING_LOCK is obtained by locking a designated byte different from
8001** the RESERVED_LOCK byte.
8002**
8003** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
8004** which means we can use reader/writer locks.  When reader/writer locks
8005** are used, the lock is placed on the same range of bytes that is used
8006** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
8007** will support two or more Win95 readers or two or more WinNT readers.
8008** But a single Win95 reader will lock out all WinNT readers and a single
8009** WinNT reader will lock out all other Win95 readers.
8010**
8011** The following #defines specify the range of bytes used for locking.
8012** SHARED_SIZE is the number of bytes available in the pool from which
8013** a random byte is selected for a shared lock.  The pool of bytes for
8014** shared locks begins at SHARED_FIRST.
8015**
8016** The same locking strategy and
8017** byte ranges are used for Unix.  This leaves open the possiblity of having
8018** clients on win95, winNT, and unix all talking to the same shared file
8019** and all locking correctly.  To do so would require that samba (or whatever
8020** tool is being used for file sharing) implements locks correctly between
8021** windows and unix.  I'm guessing that isn't likely to happen, but by
8022** using the same locking range we are at least open to the possibility.
8023**
8024** Locking in windows is manditory.  For this reason, we cannot store
8025** actual data in the bytes used for locking.  The pager never allocates
8026** the pages involved in locking therefore.  SHARED_SIZE is selected so
8027** that all locks will fit on a single page even at the minimum page size.
8028** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
8029** is set high so that we don't have to allocate an unused page except
8030** for very large databases.  But one should test the page skipping logic
8031** by setting PENDING_BYTE low and running the entire regression suite.
8032**
8033** Changing the value of PENDING_BYTE results in a subtly incompatible
8034** file format.  Depending on how it is changed, you might not notice
8035** the incompatibility right away, even running a full regression test.
8036** The default location of PENDING_BYTE is the first byte past the
8037** 1GB boundary.
8038**
8039*/
8040#define PENDING_BYTE      sqlite3PendingByte
8041#define RESERVED_BYTE     (PENDING_BYTE+1)
8042#define SHARED_FIRST      (PENDING_BYTE+2)
8043#define SHARED_SIZE       510
8044
8045/*
8046** Wrapper around OS specific sqlite3_os_init() function.
8047*/
8048SQLITE_PRIVATE int sqlite3OsInit(void);
8049
8050/*
8051** Functions for accessing sqlite3_file methods
8052*/
8053SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8054SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8055SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8056SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8057SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8058SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8059SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8060SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8061SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8062SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8063#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
8064SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8065SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8066
8067/*
8068** Functions for accessing sqlite3_vfs methods
8069*/
8070SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8071SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8072SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8073SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8074#ifndef SQLITE_OMIT_LOAD_EXTENSION
8075SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8076SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8077SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
8078SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8079#endif /* SQLITE_OMIT_LOAD_EXTENSION */
8080SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8081SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8082SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);
8083
8084/*
8085** Convenience functions for opening and closing files using
8086** sqlite3_malloc() to obtain space for the file-handle structure.
8087*/
8088SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8089SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8090
8091#endif /* _SQLITE_OS_H_ */
8092
8093/************** End of os.h **************************************************/
8094/************** Continuing where we left off in sqliteInt.h ******************/
8095/************** Include mutex.h in the middle of sqliteInt.h *****************/
8096/************** Begin file mutex.h *******************************************/
8097/*
8098** 2007 August 28
8099**
8100** The author disclaims copyright to this source code.  In place of
8101** a legal notice, here is a blessing:
8102**
8103**    May you do good and not evil.
8104**    May you find forgiveness for yourself and forgive others.
8105**    May you share freely, never taking more than you give.
8106**
8107*************************************************************************
8108**
8109** This file contains the common header for all mutex implementations.
8110** The sqliteInt.h header #includes this file so that it is available
8111** to all source files.  We break it out in an effort to keep the code
8112** better organized.
8113**
8114** NOTE:  source files should *not* #include this header file directly.
8115** Source files should #include the sqliteInt.h file and let that file
8116** include this one indirectly.
8117*/
8118
8119
8120/*
8121** Figure out what version of the code to use.  The choices are
8122**
8123**   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
8124**                             mutexes implemention cannot be overridden
8125**                             at start-time.
8126**
8127**   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
8128**                             mutual exclusion is provided.  But this
8129**                             implementation can be overridden at
8130**                             start-time.
8131**
8132**   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
8133**
8134**   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
8135**
8136**   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
8137*/
8138#if !SQLITE_THREADSAFE
8139# define SQLITE_MUTEX_OMIT
8140#endif
8141#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
8142#  if SQLITE_OS_UNIX
8143#    define SQLITE_MUTEX_PTHREADS
8144#  elif SQLITE_OS_WIN
8145#    define SQLITE_MUTEX_W32
8146#  elif SQLITE_OS_OS2
8147#    define SQLITE_MUTEX_OS2
8148#  else
8149#    define SQLITE_MUTEX_NOOP
8150#  endif
8151#endif
8152
8153#ifdef SQLITE_MUTEX_OMIT
8154/*
8155** If this is a no-op implementation, implement everything as macros.
8156*/
8157#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
8158#define sqlite3_mutex_free(X)
8159#define sqlite3_mutex_enter(X)
8160#define sqlite3_mutex_try(X)      SQLITE_OK
8161#define sqlite3_mutex_leave(X)
8162#define sqlite3_mutex_held(X)     1
8163#define sqlite3_mutex_notheld(X)  1
8164#define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
8165#define sqlite3MutexInit()        SQLITE_OK
8166#define sqlite3MutexEnd()
8167#endif /* defined(SQLITE_MUTEX_OMIT) */
8168
8169/************** End of mutex.h ***********************************************/
8170/************** Continuing where we left off in sqliteInt.h ******************/
8171
8172
8173/*
8174** Each database file to be accessed by the system is an instance
8175** of the following structure.  There are normally two of these structures
8176** in the sqlite.aDb[] array.  aDb[0] is the main database file and
8177** aDb[1] is the database file used to hold temporary tables.  Additional
8178** databases may be attached.
8179*/
8180struct Db {
8181  char *zName;         /* Name of this database */
8182  Btree *pBt;          /* The B*Tree structure for this database file */
8183  u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
8184  u8 safety_level;     /* How aggressive at syncing data to disk */
8185  Schema *pSchema;     /* Pointer to database schema (possibly shared) */
8186};
8187
8188/*
8189** An instance of the following structure stores a database schema.
8190**
8191** If there are no virtual tables configured in this schema, the
8192** Schema.db variable is set to NULL. After the first virtual table
8193** has been added, it is set to point to the database connection
8194** used to create the connection. Once a virtual table has been
8195** added to the Schema structure and the Schema.db variable populated,
8196** only that database connection may use the Schema to prepare
8197** statements.
8198*/
8199struct Schema {
8200  int schema_cookie;   /* Database schema version number for this file */
8201  Hash tblHash;        /* All tables indexed by name */
8202  Hash idxHash;        /* All (named) indices indexed by name */
8203  Hash trigHash;       /* All triggers indexed by name */
8204  Hash fkeyHash;       /* All foreign keys by referenced table name */
8205  Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
8206  u8 file_format;      /* Schema format version for this file */
8207  u8 enc;              /* Text encoding used by this database */
8208  u16 flags;           /* Flags associated with this schema */
8209  int cache_size;      /* Number of pages to use in the cache */
8210#ifndef SQLITE_OMIT_VIRTUALTABLE
8211  sqlite3 *db;         /* "Owner" connection. See comment above */
8212#endif
8213};
8214
8215/*
8216** These macros can be used to test, set, or clear bits in the
8217** Db.flags field.
8218*/
8219#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
8220#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
8221#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
8222#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
8223
8224/*
8225** Allowed values for the DB.flags field.
8226**
8227** The DB_SchemaLoaded flag is set after the database schema has been
8228** read into internal hash tables.
8229**
8230** DB_UnresetViews means that one or more views have column names that
8231** have been filled out.  If the schema changes, these column names might
8232** changes and so the view will need to be reset.
8233*/
8234#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
8235#define DB_UnresetViews    0x0002  /* Some views have defined column names */
8236#define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
8237
8238/*
8239** The number of different kinds of things that can be limited
8240** using the sqlite3_limit() interface.
8241*/
8242#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
8243
8244/*
8245** Lookaside malloc is a set of fixed-size buffers that can be used
8246** to satisfy small transient memory allocation requests for objects
8247** associated with a particular database connection.  The use of
8248** lookaside malloc provides a significant performance enhancement
8249** (approx 10%) by avoiding numerous malloc/free requests while parsing
8250** SQL statements.
8251**
8252** The Lookaside structure holds configuration information about the
8253** lookaside malloc subsystem.  Each available memory allocation in
8254** the lookaside subsystem is stored on a linked list of LookasideSlot
8255** objects.
8256**
8257** Lookaside allocations are only allowed for objects that are associated
8258** with a particular database connection.  Hence, schema information cannot
8259** be stored in lookaside because in shared cache mode the schema information
8260** is shared by multiple database connections.  Therefore, while parsing
8261** schema information, the Lookaside.bEnabled flag is cleared so that
8262** lookaside allocations are not used to construct the schema objects.
8263*/
8264struct Lookaside {
8265  u16 sz;                 /* Size of each buffer in bytes */
8266  u8 bEnabled;            /* False to disable new lookaside allocations */
8267  u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
8268  int nOut;               /* Number of buffers currently checked out */
8269  int mxOut;              /* Highwater mark for nOut */
8270  LookasideSlot *pFree;   /* List of available buffers */
8271  void *pStart;           /* First byte of available memory space */
8272  void *pEnd;             /* First byte past end of available space */
8273};
8274struct LookasideSlot {
8275  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
8276};
8277
8278/*
8279** A hash table for function definitions.
8280**
8281** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
8282** Collisions are on the FuncDef.pHash chain.
8283*/
8284struct FuncDefHash {
8285  FuncDef *a[23];       /* Hash table for functions */
8286};
8287
8288/*
8289** Each database is an instance of the following structure.
8290**
8291** The sqlite.lastRowid records the last insert rowid generated by an
8292** insert statement.  Inserts on views do not affect its value.  Each
8293** trigger has its own context, so that lastRowid can be updated inside
8294** triggers as usual.  The previous value will be restored once the trigger
8295** exits.  Upon entering a before or instead of trigger, lastRowid is no
8296** longer (since after version 2.8.12) reset to -1.
8297**
8298** The sqlite.nChange does not count changes within triggers and keeps no
8299** context.  It is reset at start of sqlite3_exec.
8300** The sqlite.lsChange represents the number of changes made by the last
8301** insert, update, or delete statement.  It remains constant throughout the
8302** length of a statement and is then updated by OP_SetCounts.  It keeps a
8303** context stack just like lastRowid so that the count of changes
8304** within a trigger is not seen outside the trigger.  Changes to views do not
8305** affect the value of lsChange.
8306** The sqlite.csChange keeps track of the number of current changes (since
8307** the last statement) and is used to update sqlite_lsChange.
8308**
8309** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
8310** store the most recent error code and, if applicable, string. The
8311** internal function sqlite3Error() is used to set these variables
8312** consistently.
8313*/
8314struct sqlite3 {
8315  sqlite3_vfs *pVfs;            /* OS Interface */
8316  int nDb;                      /* Number of backends currently in use */
8317  Db *aDb;                      /* All backends */
8318  int flags;                    /* Miscellaneous flags. See below */
8319  int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
8320  int errCode;                  /* Most recent error code (SQLITE_*) */
8321  int errMask;                  /* & result codes with this before returning */
8322  u8 autoCommit;                /* The auto-commit flag. */
8323  u8 temp_store;                /* 1: file 2: memory 0: default */
8324  u8 mallocFailed;              /* True if we have seen a malloc failure */
8325  u8 dfltLockMode;              /* Default locking-mode for attached dbs */
8326  u8 dfltJournalMode;           /* Default journal mode for attached dbs */
8327  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
8328  u8 suppressErr;               /* Do not issue error messages if true */
8329  int nextPagesize;             /* Pagesize after VACUUM if >0 */
8330  int nTable;                   /* Number of tables in the database */
8331  CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
8332  i64 lastRowid;                /* ROWID of most recent insert (see above) */
8333  u32 magic;                    /* Magic number for detect library misuse */
8334  int nChange;                  /* Value returned by sqlite3_changes() */
8335  int nTotalChange;             /* Value returned by sqlite3_total_changes() */
8336  sqlite3_mutex *mutex;         /* Connection mutex */
8337  int aLimit[SQLITE_N_LIMIT];   /* Limits */
8338  struct sqlite3InitInfo {      /* Information used during initialization */
8339    int iDb;                    /* When back is being initialized */
8340    int newTnum;                /* Rootpage of table being initialized */
8341    u8 busy;                    /* TRUE if currently initializing */
8342    u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
8343  } init;
8344  int nExtension;               /* Number of loaded extensions */
8345  void **aExtension;            /* Array of shared library handles */
8346  struct Vdbe *pVdbe;           /* List of active virtual machines */
8347  int activeVdbeCnt;            /* Number of VDBEs currently executing */
8348  int writeVdbeCnt;             /* Number of active VDBEs that are writing */
8349  void (*xTrace)(void*,const char*);        /* Trace function */
8350  void *pTraceArg;                          /* Argument to the trace function */
8351  void (*xProfile)(void*,const char*,u64);  /* Profiling function */
8352  void *pProfileArg;                        /* Argument to profile function */
8353  void *pCommitArg;                 /* Argument to xCommitCallback() */
8354  int (*xCommitCallback)(void*);    /* Invoked at every commit. */
8355  void *pRollbackArg;               /* Argument to xRollbackCallback() */
8356  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
8357  void *pUpdateArg;
8358  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
8359  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
8360  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
8361  void *pCollNeededArg;
8362  sqlite3_value *pErr;          /* Most recent error message */
8363  char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
8364  char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
8365  union {
8366    volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
8367    double notUsed1;            /* Spacer */
8368  } u1;
8369  Lookaside lookaside;          /* Lookaside malloc configuration */
8370#ifndef SQLITE_OMIT_AUTHORIZATION
8371  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
8372                                /* Access authorization function */
8373  void *pAuthArg;               /* 1st argument to the access auth function */
8374#endif
8375#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8376  int (*xProgress)(void *);     /* The progress callback */
8377  void *pProgressArg;           /* Argument to the progress callback */
8378  int nProgressOps;             /* Number of opcodes for progress callback */
8379#endif
8380#ifndef SQLITE_OMIT_VIRTUALTABLE
8381  Hash aModule;                 /* populated by sqlite3_create_module() */
8382  Table *pVTab;                 /* vtab with active Connect/Create method */
8383  VTable **aVTrans;             /* Virtual tables with open transactions */
8384  int nVTrans;                  /* Allocated size of aVTrans */
8385  VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
8386#endif
8387  FuncDefHash aFunc;            /* Hash table of connection functions */
8388  Hash aCollSeq;                /* All collating sequences */
8389  BusyHandler busyHandler;      /* Busy callback */
8390  int busyTimeout;              /* Busy handler timeout, in msec */
8391  Db aDbStatic[2];              /* Static space for the 2 default backends */
8392  Savepoint *pSavepoint;        /* List of active savepoints */
8393  int nSavepoint;               /* Number of non-transaction savepoints */
8394  int nStatement;               /* Number of nested statement-transactions  */
8395  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
8396  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
8397
8398#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
8399  /* The following variables are all protected by the STATIC_MASTER
8400  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
8401  **
8402  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
8403  ** unlock so that it can proceed.
8404  **
8405  ** When X.pBlockingConnection==Y, that means that something that X tried
8406  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
8407  ** held by Y.
8408  */
8409  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
8410  sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
8411  void *pUnlockArg;                     /* Argument to xUnlockNotify */
8412  void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
8413  sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
8414#endif
8415};
8416
8417/*
8418** A macro to discover the encoding of a database.
8419*/
8420#define ENC(db) ((db)->aDb[0].pSchema->enc)
8421
8422/*
8423** Possible values for the sqlite3.flags.
8424*/
8425#define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
8426#define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
8427#define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
8428#define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
8429#define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
8430                                          /*   DELETE, or UPDATE and return */
8431                                          /*   the count using a callback. */
8432#define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
8433                                          /*   result set is empty */
8434#define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
8435#define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
8436#define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
8437#define SQLITE_NoReadlock     0x00020000  /* Readlocks are omitted when
8438                                          ** accessing read-only databases */
8439#define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
8440#define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
8441#define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
8442#define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
8443#define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
8444#define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
8445#define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
8446#define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
8447#define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
8448
8449/*
8450** Bits of the sqlite3.flags field that are used by the
8451** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
8452** These must be the low-order bits of the flags field.
8453*/
8454#define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
8455#define SQLITE_ColumnCache    0x02        /* Disable the column cache */
8456#define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
8457#define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
8458#define SQLITE_IndexCover     0x10        /* Disable index covering table */
8459#define SQLITE_OptMask        0x1f        /* Mask of all disablable opts */
8460
8461/*
8462** Possible values for the sqlite.magic field.
8463** The numbers are obtained at random and have no special meaning, other
8464** than being distinct from one another.
8465*/
8466#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
8467#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
8468#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
8469#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
8470#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
8471
8472/*
8473** Each SQL function is defined by an instance of the following
8474** structure.  A pointer to this structure is stored in the sqlite.aFunc
8475** hash table.  When multiple functions have the same name, the hash table
8476** points to a linked list of these structures.
8477*/
8478struct FuncDef {
8479  i16 nArg;            /* Number of arguments.  -1 means unlimited */
8480  u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
8481  u8 flags;            /* Some combination of SQLITE_FUNC_* */
8482  void *pUserData;     /* User data parameter */
8483  FuncDef *pNext;      /* Next function with same name */
8484  void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
8485  void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
8486  void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
8487  char *zName;         /* SQL name of the function. */
8488  FuncDef *pHash;      /* Next with a different name but the same hash */
8489};
8490
8491/*
8492** Possible values for FuncDef.flags
8493*/
8494#define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
8495#define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
8496#define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
8497#define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
8498#define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
8499#define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
8500#define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
8501
8502/*
8503** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
8504** used to create the initializers for the FuncDef structures.
8505**
8506**   FUNCTION(zName, nArg, iArg, bNC, xFunc)
8507**     Used to create a scalar function definition of a function zName
8508**     implemented by C function xFunc that accepts nArg arguments. The
8509**     value passed as iArg is cast to a (void*) and made available
8510**     as the user-data (sqlite3_user_data()) for the function. If
8511**     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
8512**
8513**   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
8514**     Used to create an aggregate function definition implemented by
8515**     the C functions xStep and xFinal. The first four parameters
8516**     are interpreted in the same way as the first 4 parameters to
8517**     FUNCTION().
8518**
8519**   LIKEFUNC(zName, nArg, pArg, flags)
8520**     Used to create a scalar function definition of a function zName
8521**     that accepts nArg arguments and is implemented by a call to C
8522**     function likeFunc. Argument pArg is cast to a (void *) and made
8523**     available as the function user-data (sqlite3_user_data()). The
8524**     FuncDef.flags variable is set to the value passed as the flags
8525**     parameter.
8526*/
8527#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
8528  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8529   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0}
8530#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
8531  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8532   pArg, 0, xFunc, 0, 0, #zName, 0}
8533#define LIKEFUNC(zName, nArg, arg, flags) \
8534  {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0}
8535#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
8536  {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
8537   SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0}
8538
8539/*
8540** All current savepoints are stored in a linked list starting at
8541** sqlite3.pSavepoint. The first element in the list is the most recently
8542** opened savepoint. Savepoints are added to the list by the vdbe
8543** OP_Savepoint instruction.
8544*/
8545struct Savepoint {
8546  char *zName;                        /* Savepoint name (nul-terminated) */
8547  i64 nDeferredCons;                  /* Number of deferred fk violations */
8548  Savepoint *pNext;                   /* Parent savepoint (if any) */
8549};
8550
8551/*
8552** The following are used as the second parameter to sqlite3Savepoint(),
8553** and as the P1 argument to the OP_Savepoint instruction.
8554*/
8555#define SAVEPOINT_BEGIN      0
8556#define SAVEPOINT_RELEASE    1
8557#define SAVEPOINT_ROLLBACK   2
8558
8559
8560/*
8561** Each SQLite module (virtual table definition) is defined by an
8562** instance of the following structure, stored in the sqlite3.aModule
8563** hash table.
8564*/
8565struct Module {
8566  const sqlite3_module *pModule;       /* Callback pointers */
8567  const char *zName;                   /* Name passed to create_module() */
8568  void *pAux;                          /* pAux passed to create_module() */
8569  void (*xDestroy)(void *);            /* Module destructor function */
8570};
8571
8572/*
8573** information about each column of an SQL table is held in an instance
8574** of this structure.
8575*/
8576struct Column {
8577  char *zName;     /* Name of this column */
8578  Expr *pDflt;     /* Default value of this column */
8579  char *zDflt;     /* Original text of the default value */
8580  char *zType;     /* Data type for this column */
8581  char *zColl;     /* Collating sequence.  If NULL, use the default */
8582  u8 notNull;      /* True if there is a NOT NULL constraint */
8583  u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
8584  char affinity;   /* One of the SQLITE_AFF_... values */
8585#ifndef SQLITE_OMIT_VIRTUALTABLE
8586  u8 isHidden;     /* True if this column is 'hidden' */
8587#endif
8588};
8589
8590/*
8591** A "Collating Sequence" is defined by an instance of the following
8592** structure. Conceptually, a collating sequence consists of a name and
8593** a comparison routine that defines the order of that sequence.
8594**
8595** There may two separate implementations of the collation function, one
8596** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
8597** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
8598** native byte order. When a collation sequence is invoked, SQLite selects
8599** the version that will require the least expensive encoding
8600** translations, if any.
8601**
8602** The CollSeq.pUser member variable is an extra parameter that passed in
8603** as the first argument to the UTF-8 comparison function, xCmp.
8604** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
8605** xCmp16.
8606**
8607** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
8608** collating sequence is undefined.  Indices built on an undefined
8609** collating sequence may not be read or written.
8610*/
8611struct CollSeq {
8612  char *zName;          /* Name of the collating sequence, UTF-8 encoded */
8613  u8 enc;               /* Text encoding handled by xCmp() */
8614  u8 type;              /* One of the SQLITE_COLL_... values below */
8615  void *pUser;          /* First argument to xCmp() */
8616  int (*xCmp)(void*,int, const void*, int, const void*);
8617  void (*xDel)(void*);  /* Destructor for pUser */
8618};
8619
8620/*
8621** Allowed values of CollSeq.type:
8622*/
8623#define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
8624#define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
8625#define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
8626#define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
8627
8628/*
8629** A sort order can be either ASC or DESC.
8630*/
8631#define SQLITE_SO_ASC       0  /* Sort in ascending order */
8632#define SQLITE_SO_DESC      1  /* Sort in ascending order */
8633
8634/*
8635** Column affinity types.
8636**
8637** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
8638** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
8639** the speed a little by numbering the values consecutively.
8640**
8641** But rather than start with 0 or 1, we begin with 'a'.  That way,
8642** when multiple affinity types are concatenated into a string and
8643** used as the P4 operand, they will be more readable.
8644**
8645** Note also that the numeric types are grouped together so that testing
8646** for a numeric type is a single comparison.
8647*/
8648#define SQLITE_AFF_TEXT     'a'
8649#define SQLITE_AFF_NONE     'b'
8650#define SQLITE_AFF_NUMERIC  'c'
8651#define SQLITE_AFF_INTEGER  'd'
8652#define SQLITE_AFF_REAL     'e'
8653
8654#define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
8655
8656/*
8657** The SQLITE_AFF_MASK values masks off the significant bits of an
8658** affinity value.
8659*/
8660#define SQLITE_AFF_MASK     0x67
8661
8662/*
8663** Additional bit values that can be ORed with an affinity without
8664** changing the affinity.
8665*/
8666#define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
8667#define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
8668#define SQLITE_NULLEQ       0x80  /* NULL=NULL */
8669
8670/*
8671** An object of this type is created for each virtual table present in
8672** the database schema.
8673**
8674** If the database schema is shared, then there is one instance of this
8675** structure for each database connection (sqlite3*) that uses the shared
8676** schema. This is because each database connection requires its own unique
8677** instance of the sqlite3_vtab* handle used to access the virtual table
8678** implementation. sqlite3_vtab* handles can not be shared between
8679** database connections, even when the rest of the in-memory database
8680** schema is shared, as the implementation often stores the database
8681** connection handle passed to it via the xConnect() or xCreate() method
8682** during initialization internally. This database connection handle may
8683** then used by the virtual table implementation to access real tables
8684** within the database. So that they appear as part of the callers
8685** transaction, these accesses need to be made via the same database
8686** connection as that used to execute SQL operations on the virtual table.
8687**
8688** All VTable objects that correspond to a single table in a shared
8689** database schema are initially stored in a linked-list pointed to by
8690** the Table.pVTable member variable of the corresponding Table object.
8691** When an sqlite3_prepare() operation is required to access the virtual
8692** table, it searches the list for the VTable that corresponds to the
8693** database connection doing the preparing so as to use the correct
8694** sqlite3_vtab* handle in the compiled query.
8695**
8696** When an in-memory Table object is deleted (for example when the
8697** schema is being reloaded for some reason), the VTable objects are not
8698** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
8699** immediately. Instead, they are moved from the Table.pVTable list to
8700** another linked list headed by the sqlite3.pDisconnect member of the
8701** corresponding sqlite3 structure. They are then deleted/xDisconnected
8702** next time a statement is prepared using said sqlite3*. This is done
8703** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
8704** Refer to comments above function sqlite3VtabUnlockList() for an
8705** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
8706** list without holding the corresponding sqlite3.mutex mutex.
8707**
8708** The memory for objects of this type is always allocated by
8709** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
8710** the first argument.
8711*/
8712struct VTable {
8713  sqlite3 *db;              /* Database connection associated with this table */
8714  Module *pMod;             /* Pointer to module implementation */
8715  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
8716  int nRef;                 /* Number of pointers to this structure */
8717  VTable *pNext;            /* Next in linked list (see above) */
8718};
8719
8720/*
8721** Each SQL table is represented in memory by an instance of the
8722** following structure.
8723**
8724** Table.zName is the name of the table.  The case of the original
8725** CREATE TABLE statement is stored, but case is not significant for
8726** comparisons.
8727**
8728** Table.nCol is the number of columns in this table.  Table.aCol is a
8729** pointer to an array of Column structures, one for each column.
8730**
8731** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
8732** the column that is that key.   Otherwise Table.iPKey is negative.  Note
8733** that the datatype of the PRIMARY KEY must be INTEGER for this field to
8734** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
8735** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
8736** is generated for each row of the table.  TF_HasPrimaryKey is set if
8737** the table has any PRIMARY KEY, INTEGER or otherwise.
8738**
8739** Table.tnum is the page number for the root BTree page of the table in the
8740** database file.  If Table.iDb is the index of the database table backend
8741** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
8742** holds temporary tables and indices.  If TF_Ephemeral is set
8743** then the table is stored in a file that is automatically deleted
8744** when the VDBE cursor to the table is closed.  In this case Table.tnum
8745** refers VDBE cursor number that holds the table open, not to the root
8746** page number.  Transient tables are used to hold the results of a
8747** sub-query that appears instead of a real table name in the FROM clause
8748** of a SELECT statement.
8749*/
8750struct Table {
8751  sqlite3 *dbMem;      /* DB connection used for lookaside allocations. */
8752  char *zName;         /* Name of the table or view */
8753  int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
8754  int nCol;            /* Number of columns in this table */
8755  Column *aCol;        /* Information about each column */
8756  Index *pIndex;       /* List of SQL indexes on this table. */
8757  int tnum;            /* Root BTree node for this table (see note above) */
8758  Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
8759  u16 nRef;            /* Number of pointers to this Table */
8760  u8 tabFlags;         /* Mask of TF_* values */
8761  u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
8762  FKey *pFKey;         /* Linked list of all foreign keys in this table */
8763  char *zColAff;       /* String defining the affinity of each column */
8764#ifndef SQLITE_OMIT_CHECK
8765  Expr *pCheck;        /* The AND of all CHECK constraints */
8766#endif
8767#ifndef SQLITE_OMIT_ALTERTABLE
8768  int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
8769#endif
8770#ifndef SQLITE_OMIT_VIRTUALTABLE
8771  VTable *pVTable;     /* List of VTable objects. */
8772  int nModuleArg;      /* Number of arguments to the module */
8773  char **azModuleArg;  /* Text of all module args. [0] is module name */
8774#endif
8775  Trigger *pTrigger;   /* List of triggers stored in pSchema */
8776  Schema *pSchema;     /* Schema that contains this table */
8777  Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
8778};
8779
8780/*
8781** Allowed values for Tabe.tabFlags.
8782*/
8783#define TF_Readonly        0x01    /* Read-only system table */
8784#define TF_Ephemeral       0x02    /* An ephemeral table */
8785#define TF_HasPrimaryKey   0x04    /* Table has a primary key */
8786#define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
8787#define TF_Virtual         0x10    /* Is a virtual table */
8788#define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
8789
8790
8791
8792/*
8793** Test to see whether or not a table is a virtual table.  This is
8794** done as a macro so that it will be optimized out when virtual
8795** table support is omitted from the build.
8796*/
8797#ifndef SQLITE_OMIT_VIRTUALTABLE
8798#  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
8799#  define IsHiddenColumn(X) ((X)->isHidden)
8800#else
8801#  define IsVirtual(X)      0
8802#  define IsHiddenColumn(X) 0
8803#endif
8804
8805/*
8806** Each foreign key constraint is an instance of the following structure.
8807**
8808** A foreign key is associated with two tables.  The "from" table is
8809** the table that contains the REFERENCES clause that creates the foreign
8810** key.  The "to" table is the table that is named in the REFERENCES clause.
8811** Consider this example:
8812**
8813**     CREATE TABLE ex1(
8814**       a INTEGER PRIMARY KEY,
8815**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
8816**     );
8817**
8818** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
8819**
8820** Each REFERENCES clause generates an instance of the following structure
8821** which is attached to the from-table.  The to-table need not exist when
8822** the from-table is created.  The existence of the to-table is not checked.
8823*/
8824struct FKey {
8825  Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
8826  FKey *pNextFrom;  /* Next foreign key in pFrom */
8827  char *zTo;        /* Name of table that the key points to (aka: Parent) */
8828  FKey *pNextTo;    /* Next foreign key on table named zTo */
8829  FKey *pPrevTo;    /* Previous foreign key on table named zTo */
8830  int nCol;         /* Number of columns in this key */
8831  /* EV: R-30323-21917 */
8832  u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
8833  u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
8834  Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
8835  struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
8836    int iFrom;         /* Index of column in pFrom */
8837    char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
8838  } aCol[1];        /* One entry for each of nCol column s */
8839};
8840
8841/*
8842** SQLite supports many different ways to resolve a constraint
8843** error.  ROLLBACK processing means that a constraint violation
8844** causes the operation in process to fail and for the current transaction
8845** to be rolled back.  ABORT processing means the operation in process
8846** fails and any prior changes from that one operation are backed out,
8847** but the transaction is not rolled back.  FAIL processing means that
8848** the operation in progress stops and returns an error code.  But prior
8849** changes due to the same operation are not backed out and no rollback
8850** occurs.  IGNORE means that the particular row that caused the constraint
8851** error is not inserted or updated.  Processing continues and no error
8852** is returned.  REPLACE means that preexisting database rows that caused
8853** a UNIQUE constraint violation are removed so that the new insert or
8854** update can proceed.  Processing continues and no error is reported.
8855**
8856** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
8857** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
8858** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
8859** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
8860** referenced table row is propagated into the row that holds the
8861** foreign key.
8862**
8863** The following symbolic values are used to record which type
8864** of action to take.
8865*/
8866#define OE_None     0   /* There is no constraint to check */
8867#define OE_Rollback 1   /* Fail the operation and rollback the transaction */
8868#define OE_Abort    2   /* Back out changes but do no rollback transaction */
8869#define OE_Fail     3   /* Stop the operation but leave all prior changes */
8870#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
8871#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
8872
8873#define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
8874#define OE_SetNull  7   /* Set the foreign key value to NULL */
8875#define OE_SetDflt  8   /* Set the foreign key value to its default */
8876#define OE_Cascade  9   /* Cascade the changes */
8877
8878#define OE_Default  99  /* Do whatever the default action is */
8879
8880
8881/*
8882** An instance of the following structure is passed as the first
8883** argument to sqlite3VdbeKeyCompare and is used to control the
8884** comparison of the two index keys.
8885*/
8886struct KeyInfo {
8887  sqlite3 *db;        /* The database connection */
8888  u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
8889  u16 nField;         /* Number of entries in aColl[] */
8890  u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
8891  CollSeq *aColl[1];  /* Collating sequence for each term of the key */
8892};
8893
8894/*
8895** An instance of the following structure holds information about a
8896** single index record that has already been parsed out into individual
8897** values.
8898**
8899** A record is an object that contains one or more fields of data.
8900** Records are used to store the content of a table row and to store
8901** the key of an index.  A blob encoding of a record is created by
8902** the OP_MakeRecord opcode of the VDBE and is disassembled by the
8903** OP_Column opcode.
8904**
8905** This structure holds a record that has already been disassembled
8906** into its constituent fields.
8907*/
8908struct UnpackedRecord {
8909  KeyInfo *pKeyInfo;  /* Collation and sort-order information */
8910  u16 nField;         /* Number of entries in apMem[] */
8911  u16 flags;          /* Boolean settings.  UNPACKED_... below */
8912  i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
8913  Mem *aMem;          /* Values */
8914};
8915
8916/*
8917** Allowed values of UnpackedRecord.flags
8918*/
8919#define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
8920#define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
8921#define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
8922#define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
8923#define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
8924#define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
8925
8926/*
8927** Each SQL index is represented in memory by an
8928** instance of the following structure.
8929**
8930** The columns of the table that are to be indexed are described
8931** by the aiColumn[] field of this structure.  For example, suppose
8932** we have the following table and index:
8933**
8934**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
8935**     CREATE INDEX Ex2 ON Ex1(c3,c1);
8936**
8937** In the Table structure describing Ex1, nCol==3 because there are
8938** three columns in the table.  In the Index structure describing
8939** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
8940** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
8941** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
8942** The second column to be indexed (c1) has an index of 0 in
8943** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
8944**
8945** The Index.onError field determines whether or not the indexed columns
8946** must be unique and what to do if they are not.  When Index.onError=OE_None,
8947** it means this is not a unique index.  Otherwise it is a unique index
8948** and the value of Index.onError indicate the which conflict resolution
8949** algorithm to employ whenever an attempt is made to insert a non-unique
8950** element.
8951*/
8952struct Index {
8953  char *zName;     /* Name of this index */
8954  int nColumn;     /* Number of columns in the table used by this index */
8955  int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
8956  unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
8957  Table *pTable;   /* The SQL table being indexed */
8958  int tnum;        /* Page containing root of this index in database file */
8959  u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
8960  u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
8961  char *zColAff;   /* String defining the affinity of each column */
8962  Index *pNext;    /* The next index associated with the same table */
8963  Schema *pSchema; /* Schema containing this index */
8964  u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
8965  char **azColl;   /* Array of collation sequence names for index */
8966  IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
8967};
8968
8969/*
8970** Each sample stored in the sqlite_stat2 table is represented in memory
8971** using a structure of this type.
8972*/
8973struct IndexSample {
8974  union {
8975    char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
8976    double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
8977  } u;
8978  u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
8979  u8 nByte;         /* Size in byte of text or blob. */
8980};
8981
8982/*
8983** Each token coming out of the lexer is an instance of
8984** this structure.  Tokens are also used as part of an expression.
8985**
8986** Note if Token.z==0 then Token.dyn and Token.n are undefined and
8987** may contain random values.  Do not make any assumptions about Token.dyn
8988** and Token.n when Token.z==0.
8989*/
8990struct Token {
8991  const char *z;     /* Text of the token.  Not NULL-terminated! */
8992  unsigned int n;    /* Number of characters in this token */
8993};
8994
8995/*
8996** An instance of this structure contains information needed to generate
8997** code for a SELECT that contains aggregate functions.
8998**
8999** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
9000** pointer to this structure.  The Expr.iColumn field is the index in
9001** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
9002** code for that node.
9003**
9004** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
9005** original Select structure that describes the SELECT statement.  These
9006** fields do not need to be freed when deallocating the AggInfo structure.
9007*/
9008struct AggInfo {
9009  u8 directMode;          /* Direct rendering mode means take data directly
9010                          ** from source tables rather than from accumulators */
9011  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
9012                          ** than the source table */
9013  int sortingIdx;         /* Cursor number of the sorting index */
9014  ExprList *pGroupBy;     /* The group by clause */
9015  int nSortingColumn;     /* Number of columns in the sorting index */
9016  struct AggInfo_col {    /* For each column used in source tables */
9017    Table *pTab;             /* Source table */
9018    int iTable;              /* Cursor number of the source table */
9019    int iColumn;             /* Column number within the source table */
9020    int iSorterColumn;       /* Column number in the sorting index */
9021    int iMem;                /* Memory location that acts as accumulator */
9022    Expr *pExpr;             /* The original expression */
9023  } *aCol;
9024  int nColumn;            /* Number of used entries in aCol[] */
9025  int nColumnAlloc;       /* Number of slots allocated for aCol[] */
9026  int nAccumulator;       /* Number of columns that show through to the output.
9027                          ** Additional columns are used only as parameters to
9028                          ** aggregate functions */
9029  struct AggInfo_func {   /* For each aggregate function */
9030    Expr *pExpr;             /* Expression encoding the function */
9031    FuncDef *pFunc;          /* The aggregate function implementation */
9032    int iMem;                /* Memory location that acts as accumulator */
9033    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
9034  } *aFunc;
9035  int nFunc;              /* Number of entries in aFunc[] */
9036  int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
9037};
9038
9039/*
9040** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
9041** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
9042** than 32767 we have to make it 32-bit.  16-bit is preferred because
9043** it uses less memory in the Expr object, which is a big memory user
9044** in systems with lots of prepared statements.  And few applications
9045** need more than about 10 or 20 variables.  But some extreme users want
9046** to have prepared statements with over 32767 variables, and for them
9047** the option is available (at compile-time).
9048*/
9049#if SQLITE_MAX_VARIABLE_NUMBER<=32767
9050typedef i16 ynVar;
9051#else
9052typedef int ynVar;
9053#endif
9054
9055/*
9056** Each node of an expression in the parse tree is an instance
9057** of this structure.
9058**
9059** Expr.op is the opcode. The integer parser token codes are reused
9060** as opcodes here. For example, the parser defines TK_GE to be an integer
9061** code representing the ">=" operator. This same integer code is reused
9062** to represent the greater-than-or-equal-to operator in the expression
9063** tree.
9064**
9065** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
9066** or TK_STRING), then Expr.token contains the text of the SQL literal. If
9067** the expression is a variable (TK_VARIABLE), then Expr.token contains the
9068** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
9069** then Expr.token contains the name of the function.
9070**
9071** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
9072** binary operator. Either or both may be NULL.
9073**
9074** Expr.x.pList is a list of arguments if the expression is an SQL function,
9075** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
9076** Expr.x.pSelect is used if the expression is a sub-select or an expression of
9077** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
9078** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
9079** valid.
9080**
9081** An expression of the form ID or ID.ID refers to a column in a table.
9082** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9083** the integer cursor number of a VDBE cursor pointing to that table and
9084** Expr.iColumn is the column number for the specific column.  If the
9085** expression is used as a result in an aggregate SELECT, then the
9086** value is also stored in the Expr.iAgg column in the aggregate so that
9087** it can be accessed after all aggregates are computed.
9088**
9089** If the expression is an unbound variable marker (a question mark
9090** character '?' in the original SQL) then the Expr.iTable holds the index
9091** number for that variable.
9092**
9093** If the expression is a subquery then Expr.iColumn holds an integer
9094** register number containing the result of the subquery.  If the
9095** subquery gives a constant result, then iTable is -1.  If the subquery
9096** gives a different answer at different times during statement processing
9097** then iTable is the address of a subroutine that computes the subquery.
9098**
9099** If the Expr is of type OP_Column, and the table it is selecting from
9100** is a disk table or the "old.*" pseudo-table, then pTab points to the
9101** corresponding table definition.
9102**
9103** ALLOCATION NOTES:
9104**
9105** Expr objects can use a lot of memory space in database schema.  To
9106** help reduce memory requirements, sometimes an Expr object will be
9107** truncated.  And to reduce the number of memory allocations, sometimes
9108** two or more Expr objects will be stored in a single memory allocation,
9109** together with Expr.zToken strings.
9110**
9111** If the EP_Reduced and EP_TokenOnly flags are set when
9112** an Expr object is truncated.  When EP_Reduced is set, then all
9113** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
9114** are contained within the same memory allocation.  Note, however, that
9115** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
9116** allocated, regardless of whether or not EP_Reduced is set.
9117*/
9118struct Expr {
9119  u8 op;                 /* Operation performed by this node */
9120  char affinity;         /* The affinity of the column or 0 if not a column */
9121  u16 flags;             /* Various flags.  EP_* See below */
9122  union {
9123    char *zToken;          /* Token value. Zero terminated and dequoted */
9124    int iValue;            /* Integer value if EP_IntValue */
9125  } u;
9126
9127  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
9128  ** space is allocated for the fields below this point. An attempt to
9129  ** access them will result in a segfault or malfunction.
9130  *********************************************************************/
9131
9132  Expr *pLeft;           /* Left subnode */
9133  Expr *pRight;          /* Right subnode */
9134  union {
9135    ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
9136    Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
9137  } x;
9138  CollSeq *pColl;        /* The collation type of the column or 0 */
9139
9140  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
9141  ** space is allocated for the fields below this point. An attempt to
9142  ** access them will result in a segfault or malfunction.
9143  *********************************************************************/
9144
9145  int iTable;            /* TK_COLUMN: cursor number of table holding column
9146                         ** TK_REGISTER: register number
9147                         ** TK_TRIGGER: 1 -> new, 0 -> old */
9148  ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
9149                         ** TK_VARIABLE: variable number (always >= 1). */
9150  i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
9151  i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
9152  u8 flags2;             /* Second set of flags.  EP2_... */
9153  u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
9154  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
9155  Table *pTab;           /* Table for TK_COLUMN expressions. */
9156#if SQLITE_MAX_EXPR_DEPTH>0
9157  int nHeight;           /* Height of the tree headed by this node */
9158#endif
9159};
9160
9161/*
9162** The following are the meanings of bits in the Expr.flags field.
9163*/
9164#define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
9165#define EP_Agg        0x0002  /* Contains one or more aggregate functions */
9166#define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
9167#define EP_Error      0x0008  /* Expression contains one or more errors */
9168#define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
9169#define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
9170#define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
9171#define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
9172#define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
9173#define EP_FixedDest  0x0200  /* Result needed in a specific register */
9174#define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
9175#define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
9176
9177#define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
9178#define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
9179#define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
9180
9181/*
9182** The following are the meanings of bits in the Expr.flags2 field.
9183*/
9184#define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
9185#define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
9186
9187/*
9188** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
9189** flag on an expression structure.  This flag is used for VV&A only.  The
9190** routine is implemented as a macro that only works when in debugging mode,
9191** so as not to burden production code.
9192*/
9193#ifdef SQLITE_DEBUG
9194# define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
9195#else
9196# define ExprSetIrreducible(X)
9197#endif
9198
9199/*
9200** These macros can be used to test, set, or clear bits in the
9201** Expr.flags field.
9202*/
9203#define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
9204#define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
9205#define ExprSetProperty(E,P)     (E)->flags|=(P)
9206#define ExprClearProperty(E,P)   (E)->flags&=~(P)
9207
9208/*
9209** Macros to determine the number of bytes required by a normal Expr
9210** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
9211** and an Expr struct with the EP_TokenOnly flag set.
9212*/
9213#define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
9214#define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
9215#define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
9216
9217/*
9218** Flags passed to the sqlite3ExprDup() function. See the header comment
9219** above sqlite3ExprDup() for details.
9220*/
9221#define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
9222
9223/*
9224** A list of expressions.  Each expression may optionally have a
9225** name.  An expr/name combination can be used in several ways, such
9226** as the list of "expr AS ID" fields following a "SELECT" or in the
9227** list of "ID = expr" items in an UPDATE.  A list of expressions can
9228** also be used as the argument to a function, in which case the a.zName
9229** field is not used.
9230*/
9231struct ExprList {
9232  int nExpr;             /* Number of expressions on the list */
9233  int nAlloc;            /* Number of entries allocated below */
9234  int iECursor;          /* VDBE Cursor associated with this ExprList */
9235  struct ExprList_item {
9236    Expr *pExpr;           /* The list of expressions */
9237    char *zName;           /* Token associated with this expression */
9238    char *zSpan;           /* Original text of the expression */
9239    u8 sortOrder;          /* 1 for DESC or 0 for ASC */
9240    u8 done;               /* A flag to indicate when processing is finished */
9241    u16 iCol;              /* For ORDER BY, column number in result set */
9242    u16 iAlias;            /* Index into Parse.aAlias[] for zName */
9243  } *a;                  /* One entry for each expression */
9244};
9245
9246/*
9247** An instance of this structure is used by the parser to record both
9248** the parse tree for an expression and the span of input text for an
9249** expression.
9250*/
9251struct ExprSpan {
9252  Expr *pExpr;          /* The expression parse tree */
9253  const char *zStart;   /* First character of input text */
9254  const char *zEnd;     /* One character past the end of input text */
9255};
9256
9257/*
9258** An instance of this structure can hold a simple list of identifiers,
9259** such as the list "a,b,c" in the following statements:
9260**
9261**      INSERT INTO t(a,b,c) VALUES ...;
9262**      CREATE INDEX idx ON t(a,b,c);
9263**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
9264**
9265** The IdList.a.idx field is used when the IdList represents the list of
9266** column names after a table name in an INSERT statement.  In the statement
9267**
9268**     INSERT INTO t(a,b,c) ...
9269**
9270** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
9271*/
9272struct IdList {
9273  struct IdList_item {
9274    char *zName;      /* Name of the identifier */
9275    int idx;          /* Index in some Table.aCol[] of a column named zName */
9276  } *a;
9277  int nId;         /* Number of identifiers on the list */
9278  int nAlloc;      /* Number of entries allocated for a[] below */
9279};
9280
9281/*
9282** The bitmask datatype defined below is used for various optimizations.
9283**
9284** Changing this from a 64-bit to a 32-bit type limits the number of
9285** tables in a join to 32 instead of 64.  But it also reduces the size
9286** of the library by 738 bytes on ix86.
9287*/
9288typedef u64 Bitmask;
9289
9290/*
9291** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
9292*/
9293#define BMS  ((int)(sizeof(Bitmask)*8))
9294
9295/*
9296** The following structure describes the FROM clause of a SELECT statement.
9297** Each table or subquery in the FROM clause is a separate element of
9298** the SrcList.a[] array.
9299**
9300** With the addition of multiple database support, the following structure
9301** can also be used to describe a particular table such as the table that
9302** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
9303** such a table must be a simple name: ID.  But in SQLite, the table can
9304** now be identified by a database name, a dot, then the table name: ID.ID.
9305**
9306** The jointype starts out showing the join type between the current table
9307** and the next table on the list.  The parser builds the list this way.
9308** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
9309** jointype expresses the join between the table and the previous table.
9310*/
9311struct SrcList {
9312  i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
9313  i16 nAlloc;      /* Number of entries allocated in a[] below */
9314  struct SrcList_item {
9315    char *zDatabase;  /* Name of database holding this table */
9316    char *zName;      /* Name of the table */
9317    char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
9318    Table *pTab;      /* An SQL table corresponding to zName */
9319    Select *pSelect;  /* A SELECT statement used in place of a table name */
9320    u8 isPopulated;   /* Temporary table associated with SELECT is populated */
9321    u8 jointype;      /* Type of join between this able and the previous */
9322    u8 notIndexed;    /* True if there is a NOT INDEXED clause */
9323    int iCursor;      /* The VDBE cursor number used to access this table */
9324    Expr *pOn;        /* The ON clause of a join */
9325    IdList *pUsing;   /* The USING clause of a join */
9326    Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
9327    char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
9328    Index *pIndex;    /* Index structure corresponding to zIndex, if any */
9329  } a[1];             /* One entry for each identifier on the list */
9330};
9331
9332/*
9333** Permitted values of the SrcList.a.jointype field
9334*/
9335#define JT_INNER     0x0001    /* Any kind of inner or cross join */
9336#define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
9337#define JT_NATURAL   0x0004    /* True for a "natural" join */
9338#define JT_LEFT      0x0008    /* Left outer join */
9339#define JT_RIGHT     0x0010    /* Right outer join */
9340#define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
9341#define JT_ERROR     0x0040    /* unknown or unsupported join type */
9342
9343
9344/*
9345** A WherePlan object holds information that describes a lookup
9346** strategy.
9347**
9348** This object is intended to be opaque outside of the where.c module.
9349** It is included here only so that that compiler will know how big it
9350** is.  None of the fields in this object should be used outside of
9351** the where.c module.
9352**
9353** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
9354** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
9355** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
9356** case that more than one of these conditions is true.
9357*/
9358struct WherePlan {
9359  u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
9360  u32 nEq;                       /* Number of == constraints */
9361  union {
9362    Index *pIdx;                   /* Index when WHERE_INDEXED is true */
9363    struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
9364    sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
9365  } u;
9366};
9367
9368/*
9369** For each nested loop in a WHERE clause implementation, the WhereInfo
9370** structure contains a single instance of this structure.  This structure
9371** is intended to be private the the where.c module and should not be
9372** access or modified by other modules.
9373**
9374** The pIdxInfo field is used to help pick the best index on a
9375** virtual table.  The pIdxInfo pointer contains indexing
9376** information for the i-th table in the FROM clause before reordering.
9377** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
9378** All other information in the i-th WhereLevel object for the i-th table
9379** after FROM clause ordering.
9380*/
9381struct WhereLevel {
9382  WherePlan plan;       /* query plan for this element of the FROM clause */
9383  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
9384  int iTabCur;          /* The VDBE cursor used to access the table */
9385  int iIdxCur;          /* The VDBE cursor used to access pIdx */
9386  int addrBrk;          /* Jump here to break out of the loop */
9387  int addrNxt;          /* Jump here to start the next IN combination */
9388  int addrCont;         /* Jump here to continue with the next loop cycle */
9389  int addrFirst;        /* First instruction of interior of the loop */
9390  u8 iFrom;             /* Which entry in the FROM clause */
9391  u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
9392  int p1, p2;           /* Operands of the opcode used to ends the loop */
9393  union {               /* Information that depends on plan.wsFlags */
9394    struct {
9395      int nIn;              /* Number of entries in aInLoop[] */
9396      struct InLoop {
9397        int iCur;              /* The VDBE cursor used by this IN operator */
9398        int addrInTop;         /* Top of the IN loop */
9399      } *aInLoop;           /* Information about each nested IN operator */
9400    } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
9401  } u;
9402
9403  /* The following field is really not part of the current level.  But
9404  ** we need a place to cache virtual table index information for each
9405  ** virtual table in the FROM clause and the WhereLevel structure is
9406  ** a convenient place since there is one WhereLevel for each FROM clause
9407  ** element.
9408  */
9409  sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
9410};
9411
9412/*
9413** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
9414** and the WhereInfo.wctrlFlags member.
9415*/
9416#define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
9417#define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
9418#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
9419#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
9420#define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
9421#define WHERE_OMIT_OPEN        0x0010 /* Table cursor are already open */
9422#define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
9423#define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
9424#define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
9425
9426/*
9427** The WHERE clause processing routine has two halves.  The
9428** first part does the start of the WHERE loop and the second
9429** half does the tail of the WHERE loop.  An instance of
9430** this structure is returned by the first half and passed
9431** into the second half to give some continuity.
9432*/
9433struct WhereInfo {
9434  Parse *pParse;       /* Parsing and code generating context */
9435  u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
9436  u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
9437  u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
9438  SrcList *pTabList;             /* List of tables in the join */
9439  int iTop;                      /* The very beginning of the WHERE loop */
9440  int iContinue;                 /* Jump here to continue with next record */
9441  int iBreak;                    /* Jump here to break out of the loop */
9442  int nLevel;                    /* Number of nested loop */
9443  struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
9444  WhereLevel a[1];               /* Information about each nest loop in WHERE */
9445};
9446
9447/*
9448** A NameContext defines a context in which to resolve table and column
9449** names.  The context consists of a list of tables (the pSrcList) field and
9450** a list of named expression (pEList).  The named expression list may
9451** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
9452** to the table being operated on by INSERT, UPDATE, or DELETE.  The
9453** pEList corresponds to the result set of a SELECT and is NULL for
9454** other statements.
9455**
9456** NameContexts can be nested.  When resolving names, the inner-most
9457** context is searched first.  If no match is found, the next outer
9458** context is checked.  If there is still no match, the next context
9459** is checked.  This process continues until either a match is found
9460** or all contexts are check.  When a match is found, the nRef member of
9461** the context containing the match is incremented.
9462**
9463** Each subquery gets a new NameContext.  The pNext field points to the
9464** NameContext in the parent query.  Thus the process of scanning the
9465** NameContext list corresponds to searching through successively outer
9466** subqueries looking for a match.
9467*/
9468struct NameContext {
9469  Parse *pParse;       /* The parser */
9470  SrcList *pSrcList;   /* One or more tables used to resolve names */
9471  ExprList *pEList;    /* Optional list of named expressions */
9472  int nRef;            /* Number of names resolved by this context */
9473  int nErr;            /* Number of errors encountered while resolving names */
9474  u8 allowAgg;         /* Aggregate functions allowed here */
9475  u8 hasAgg;           /* True if aggregates are seen */
9476  u8 isCheck;          /* True if resolving names in a CHECK constraint */
9477  int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
9478  AggInfo *pAggInfo;   /* Information about aggregates at this level */
9479  NameContext *pNext;  /* Next outer name context.  NULL for outermost */
9480};
9481
9482/*
9483** An instance of the following structure contains all information
9484** needed to generate code for a single SELECT statement.
9485**
9486** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
9487** If there is a LIMIT clause, the parser sets nLimit to the value of the
9488** limit and nOffset to the value of the offset (or 0 if there is not
9489** offset).  But later on, nLimit and nOffset become the memory locations
9490** in the VDBE that record the limit and offset counters.
9491**
9492** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
9493** These addresses must be stored so that we can go back and fill in
9494** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
9495** the number of columns in P2 can be computed at the same time
9496** as the OP_OpenEphm instruction is coded because not
9497** enough information about the compound query is known at that point.
9498** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
9499** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
9500** sequences for the ORDER BY clause.
9501*/
9502struct Select {
9503  ExprList *pEList;      /* The fields of the result */
9504  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
9505  char affinity;         /* MakeRecord with this affinity for SRT_Set */
9506  u16 selFlags;          /* Various SF_* values */
9507  SrcList *pSrc;         /* The FROM clause */
9508  Expr *pWhere;          /* The WHERE clause */
9509  ExprList *pGroupBy;    /* The GROUP BY clause */
9510  Expr *pHaving;         /* The HAVING clause */
9511  ExprList *pOrderBy;    /* The ORDER BY clause */
9512  Select *pPrior;        /* Prior select in a compound select statement */
9513  Select *pNext;         /* Next select to the left in a compound */
9514  Select *pRightmost;    /* Right-most select in a compound select statement */
9515  Expr *pLimit;          /* LIMIT expression. NULL means not used. */
9516  Expr *pOffset;         /* OFFSET expression. NULL means not used. */
9517  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
9518  int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
9519};
9520
9521/*
9522** Allowed values for Select.selFlags.  The "SF" prefix stands for
9523** "Select Flag".
9524*/
9525#define SF_Distinct        0x0001  /* Output should be DISTINCT */
9526#define SF_Resolved        0x0002  /* Identifiers have been resolved */
9527#define SF_Aggregate       0x0004  /* Contains aggregate functions */
9528#define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
9529#define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
9530#define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
9531
9532
9533/*
9534** The results of a select can be distributed in several ways.  The
9535** "SRT" prefix means "SELECT Result Type".
9536*/
9537#define SRT_Union        1  /* Store result as keys in an index */
9538#define SRT_Except       2  /* Remove result from a UNION index */
9539#define SRT_Exists       3  /* Store 1 if the result is not empty */
9540#define SRT_Discard      4  /* Do not save the results anywhere */
9541
9542/* The ORDER BY clause is ignored for all of the above */
9543#define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
9544
9545#define SRT_Output       5  /* Output each row of result */
9546#define SRT_Mem          6  /* Store result in a memory cell */
9547#define SRT_Set          7  /* Store results as keys in an index */
9548#define SRT_Table        8  /* Store result as data with an automatic rowid */
9549#define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
9550#define SRT_Coroutine   10  /* Generate a single row of result */
9551
9552/*
9553** A structure used to customize the behavior of sqlite3Select(). See
9554** comments above sqlite3Select() for details.
9555*/
9556typedef struct SelectDest SelectDest;
9557struct SelectDest {
9558  u8 eDest;         /* How to dispose of the results */
9559  u8 affinity;      /* Affinity used when eDest==SRT_Set */
9560  int iParm;        /* A parameter used by the eDest disposal method */
9561  int iMem;         /* Base register where results are written */
9562  int nMem;         /* Number of registers allocated */
9563};
9564
9565/*
9566** During code generation of statements that do inserts into AUTOINCREMENT
9567** tables, the following information is attached to the Table.u.autoInc.p
9568** pointer of each autoincrement table to record some side information that
9569** the code generator needs.  We have to keep per-table autoincrement
9570** information in case inserts are down within triggers.  Triggers do not
9571** normally coordinate their activities, but we do need to coordinate the
9572** loading and saving of autoincrement information.
9573*/
9574struct AutoincInfo {
9575  AutoincInfo *pNext;   /* Next info block in a list of them all */
9576  Table *pTab;          /* Table this info block refers to */
9577  int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
9578  int regCtr;           /* Memory register holding the rowid counter */
9579};
9580
9581/*
9582** Size of the column cache
9583*/
9584#ifndef SQLITE_N_COLCACHE
9585# define SQLITE_N_COLCACHE 10
9586#endif
9587
9588/*
9589** At least one instance of the following structure is created for each
9590** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
9591** statement. All such objects are stored in the linked list headed at
9592** Parse.pTriggerPrg and deleted once statement compilation has been
9593** completed.
9594**
9595** A Vdbe sub-program that implements the body and WHEN clause of trigger
9596** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
9597** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
9598** The Parse.pTriggerPrg list never contains two entries with the same
9599** values for both pTrigger and orconf.
9600**
9601** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
9602** accessed (or set to 0 for triggers fired as a result of INSERT
9603** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
9604** a mask of new.* columns used by the program.
9605*/
9606struct TriggerPrg {
9607  Trigger *pTrigger;      /* Trigger this program was coded from */
9608  int orconf;             /* Default ON CONFLICT policy */
9609  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
9610  u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
9611  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
9612};
9613
9614/*
9615** An SQL parser context.  A copy of this structure is passed through
9616** the parser and down into all the parser action routine in order to
9617** carry around information that is global to the entire parse.
9618**
9619** The structure is divided into two parts.  When the parser and code
9620** generate call themselves recursively, the first part of the structure
9621** is constant but the second part is reset at the beginning and end of
9622** each recursion.
9623**
9624** The nTableLock and aTableLock variables are only used if the shared-cache
9625** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
9626** used to store the set of table-locks required by the statement being
9627** compiled. Function sqlite3TableLock() is used to add entries to the
9628** list.
9629*/
9630struct Parse {
9631  sqlite3 *db;         /* The main database structure */
9632  int rc;              /* Return code from execution */
9633  char *zErrMsg;       /* An error message */
9634  Vdbe *pVdbe;         /* An engine for executing database bytecode */
9635  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
9636  u8 nameClash;        /* A permanent table name clashes with temp table name */
9637  u8 checkSchema;      /* Causes schema cookie check after an error */
9638  u8 nested;           /* Number of nested calls to the parser/code generator */
9639  u8 parseError;       /* True after a parsing error.  Ticket #1794 */
9640  u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
9641  u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
9642  int aTempReg[8];     /* Holding area for temporary registers */
9643  int nRangeReg;       /* Size of the temporary register block */
9644  int iRangeReg;       /* First register in temporary register block */
9645  int nErr;            /* Number of errors seen */
9646  int nTab;            /* Number of previously allocated VDBE cursors */
9647  int nMem;            /* Number of memory cells used so far */
9648  int nSet;            /* Number of sets used so far */
9649  int ckBase;          /* Base register of data during check constraints */
9650  int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
9651  int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
9652  u8 nColCache;        /* Number of entries in the column cache */
9653  u8 iColCache;        /* Next entry of the cache to replace */
9654  struct yColCache {
9655    int iTable;           /* Table cursor number */
9656    int iColumn;          /* Table column number */
9657    u8 tempReg;           /* iReg is a temp register that needs to be freed */
9658    int iLevel;           /* Nesting level */
9659    int iReg;             /* Reg with value of this column. 0 means none. */
9660    int lru;              /* Least recently used entry has the smallest value */
9661  } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
9662  u32 writeMask;       /* Start a write transaction on these databases */
9663  u32 cookieMask;      /* Bitmask of schema verified databases */
9664  u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
9665  u8 mayAbort;         /* True if statement may throw an ABORT exception */
9666  int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
9667  int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
9668#ifndef SQLITE_OMIT_SHARED_CACHE
9669  int nTableLock;        /* Number of locks in aTableLock */
9670  TableLock *aTableLock; /* Required table locks for shared-cache mode */
9671#endif
9672  int regRowid;        /* Register holding rowid of CREATE TABLE entry */
9673  int regRoot;         /* Register holding root page number for new objects */
9674  AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
9675  int nMaxArg;         /* Max args passed to user function by sub-program */
9676
9677  /* Information used while coding trigger programs. */
9678  Parse *pToplevel;    /* Parse structure for main program (or NULL) */
9679  Table *pTriggerTab;  /* Table triggers are being coded for */
9680  u32 oldmask;         /* Mask of old.* columns referenced */
9681  u32 newmask;         /* Mask of new.* columns referenced */
9682  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
9683  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
9684  u8 disableTriggers;  /* True to disable triggers */
9685
9686  /* Above is constant between recursions.  Below is reset before and after
9687  ** each recursion */
9688
9689  int nVar;            /* Number of '?' variables seen in the SQL so far */
9690  int nVarExpr;        /* Number of used slots in apVarExpr[] */
9691  int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
9692  Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
9693  Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
9694  int nAlias;          /* Number of aliased result set columns */
9695  int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
9696  int *aAlias;         /* Register used to hold aliased result */
9697  u8 explain;          /* True if the EXPLAIN flag is found on the query */
9698  Token sNameToken;    /* Token with unqualified schema object name */
9699  Token sLastToken;    /* The last token parsed */
9700  const char *zTail;   /* All SQL text past the last semicolon parsed */
9701  Table *pNewTable;    /* A table being constructed by CREATE TABLE */
9702  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
9703  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
9704#ifndef SQLITE_OMIT_VIRTUALTABLE
9705  Token sArg;                /* Complete text of a module argument */
9706  u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
9707  int nVtabLock;             /* Number of virtual tables to lock */
9708  Table **apVtabLock;        /* Pointer to virtual tables needing locking */
9709#endif
9710  int nHeight;            /* Expression tree height of current sub-select */
9711  Table *pZombieTab;      /* List of Table objects to delete after code gen */
9712  TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
9713};
9714
9715#ifdef SQLITE_OMIT_VIRTUALTABLE
9716  #define IN_DECLARE_VTAB 0
9717#else
9718  #define IN_DECLARE_VTAB (pParse->declareVtab)
9719#endif
9720
9721/*
9722** An instance of the following structure can be declared on a stack and used
9723** to save the Parse.zAuthContext value so that it can be restored later.
9724*/
9725struct AuthContext {
9726  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
9727  Parse *pParse;              /* The Parse structure */
9728};
9729
9730/*
9731** Bitfield flags for P5 value in OP_Insert and OP_Delete
9732*/
9733#define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
9734#define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
9735#define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
9736#define OPFLAG_APPEND        0x08    /* This is likely to be an append */
9737#define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
9738#define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
9739
9740/*
9741 * Each trigger present in the database schema is stored as an instance of
9742 * struct Trigger.
9743 *
9744 * Pointers to instances of struct Trigger are stored in two ways.
9745 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
9746 *    database). This allows Trigger structures to be retrieved by name.
9747 * 2. All triggers associated with a single table form a linked list, using the
9748 *    pNext member of struct Trigger. A pointer to the first element of the
9749 *    linked list is stored as the "pTrigger" member of the associated
9750 *    struct Table.
9751 *
9752 * The "step_list" member points to the first element of a linked list
9753 * containing the SQL statements specified as the trigger program.
9754 */
9755struct Trigger {
9756  char *zName;            /* The name of the trigger                        */
9757  char *table;            /* The table or view to which the trigger applies */
9758  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
9759  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
9760  Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
9761  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
9762                             the <column-list> is stored here */
9763  Schema *pSchema;        /* Schema containing the trigger */
9764  Schema *pTabSchema;     /* Schema containing the table */
9765  TriggerStep *step_list; /* Link list of trigger program steps             */
9766  Trigger *pNext;         /* Next trigger associated with the table */
9767};
9768
9769/*
9770** A trigger is either a BEFORE or an AFTER trigger.  The following constants
9771** determine which.
9772**
9773** If there are multiple triggers, you might of some BEFORE and some AFTER.
9774** In that cases, the constants below can be ORed together.
9775*/
9776#define TRIGGER_BEFORE  1
9777#define TRIGGER_AFTER   2
9778
9779/*
9780 * An instance of struct TriggerStep is used to store a single SQL statement
9781 * that is a part of a trigger-program.
9782 *
9783 * Instances of struct TriggerStep are stored in a singly linked list (linked
9784 * using the "pNext" member) referenced by the "step_list" member of the
9785 * associated struct Trigger instance. The first element of the linked list is
9786 * the first step of the trigger-program.
9787 *
9788 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
9789 * "SELECT" statement. The meanings of the other members is determined by the
9790 * value of "op" as follows:
9791 *
9792 * (op == TK_INSERT)
9793 * orconf    -> stores the ON CONFLICT algorithm
9794 * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
9795 *              this stores a pointer to the SELECT statement. Otherwise NULL.
9796 * target    -> A token holding the quoted name of the table to insert into.
9797 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
9798 *              this stores values to be inserted. Otherwise NULL.
9799 * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
9800 *              statement, then this stores the column-names to be
9801 *              inserted into.
9802 *
9803 * (op == TK_DELETE)
9804 * target    -> A token holding the quoted name of the table to delete from.
9805 * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
9806 *              Otherwise NULL.
9807 *
9808 * (op == TK_UPDATE)
9809 * target    -> A token holding the quoted name of the table to update rows of.
9810 * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
9811 *              Otherwise NULL.
9812 * pExprList -> A list of the columns to update and the expressions to update
9813 *              them to. See sqlite3Update() documentation of "pChanges"
9814 *              argument.
9815 *
9816 */
9817struct TriggerStep {
9818  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
9819  u8 orconf;           /* OE_Rollback etc. */
9820  Trigger *pTrig;      /* The trigger that this step is a part of */
9821  Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
9822  Token target;        /* Target table for DELETE, UPDATE, INSERT */
9823  Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
9824  ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
9825  IdList *pIdList;     /* Column names for INSERT */
9826  TriggerStep *pNext;  /* Next in the link-list */
9827  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
9828};
9829
9830/*
9831** The following structure contains information used by the sqliteFix...
9832** routines as they walk the parse tree to make database references
9833** explicit.
9834*/
9835typedef struct DbFixer DbFixer;
9836struct DbFixer {
9837  Parse *pParse;      /* The parsing context.  Error messages written here */
9838  const char *zDb;    /* Make sure all objects are contained in this database */
9839  const char *zType;  /* Type of the container - used for error messages */
9840  const Token *pName; /* Name of the container - used for error messages */
9841};
9842
9843/*
9844** An objected used to accumulate the text of a string where we
9845** do not necessarily know how big the string will be in the end.
9846*/
9847struct StrAccum {
9848  sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
9849  char *zBase;         /* A base allocation.  Not from malloc. */
9850  char *zText;         /* The string collected so far */
9851  int  nChar;          /* Length of the string so far */
9852  int  nAlloc;         /* Amount of space allocated in zText */
9853  int  mxAlloc;        /* Maximum allowed string length */
9854  u8   mallocFailed;   /* Becomes true if any memory allocation fails */
9855  u8   useMalloc;      /* True if zText is enlargeable using realloc */
9856  u8   tooBig;         /* Becomes true if string size exceeds limits */
9857};
9858
9859/*
9860** A pointer to this structure is used to communicate information
9861** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
9862*/
9863typedef struct {
9864  sqlite3 *db;        /* The database being initialized */
9865  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
9866  char **pzErrMsg;    /* Error message stored here */
9867  int rc;             /* Result code stored here */
9868} InitData;
9869
9870/*
9871** Structure containing global configuration data for the SQLite library.
9872**
9873** This structure also contains some state information.
9874*/
9875struct Sqlite3Config {
9876  int bMemstat;                     /* True to enable memory status */
9877  int bCoreMutex;                   /* True to enable core mutexing */
9878  int bFullMutex;                   /* True to enable full mutexing */
9879  int mxStrlen;                     /* Maximum string length */
9880  int szLookaside;                  /* Default lookaside buffer size */
9881  int nLookaside;                   /* Default lookaside buffer count */
9882  sqlite3_mem_methods m;            /* Low-level memory allocation interface */
9883  sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
9884  sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
9885  void *pHeap;                      /* Heap storage space */
9886  int nHeap;                        /* Size of pHeap[] */
9887  int mnReq, mxReq;                 /* Min and max heap requests sizes */
9888  void *pScratch;                   /* Scratch memory */
9889  int szScratch;                    /* Size of each scratch buffer */
9890  int nScratch;                     /* Number of scratch buffers */
9891  void *pPage;                      /* Page cache memory */
9892  int szPage;                       /* Size of each page in pPage[] */
9893  int nPage;                        /* Number of pages in pPage[] */
9894  int mxParserStack;                /* maximum depth of the parser stack */
9895  int sharedCacheEnabled;           /* true if shared-cache mode enabled */
9896  /* The above might be initialized to non-zero.  The following need to always
9897  ** initially be zero, however. */
9898  int isInit;                       /* True after initialization has finished */
9899  int inProgress;                   /* True while initialization in progress */
9900  int isMutexInit;                  /* True after mutexes are initialized */
9901  int isMallocInit;                 /* True after malloc is initialized */
9902  int isPCacheInit;                 /* True after malloc is initialized */
9903  sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
9904  int nRefInitMutex;                /* Number of users of pInitMutex */
9905  void (*xLog)(void*,int,const char*); /* Function for logging */
9906  void *pLogArg;                       /* First argument to xLog() */
9907};
9908
9909/*
9910** Context pointer passed down through the tree-walk.
9911*/
9912struct Walker {
9913  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
9914  int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
9915  Parse *pParse;                            /* Parser context.  */
9916  union {                                   /* Extra data for callback */
9917    NameContext *pNC;                          /* Naming context */
9918    int i;                                     /* Integer value */
9919  } u;
9920};
9921
9922/* Forward declarations */
9923SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
9924SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
9925SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
9926SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
9927SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
9928
9929/*
9930** Return code from the parse-tree walking primitives and their
9931** callbacks.
9932*/
9933#define WRC_Continue    0   /* Continue down into children */
9934#define WRC_Prune       1   /* Omit children but continue walking siblings */
9935#define WRC_Abort       2   /* Abandon the tree walk */
9936
9937/*
9938** Assuming zIn points to the first byte of a UTF-8 character,
9939** advance zIn to point to the first byte of the next UTF-8 character.
9940*/
9941#define SQLITE_SKIP_UTF8(zIn) {                        \
9942  if( (*(zIn++))>=0xc0 ){                              \
9943    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
9944  }                                                    \
9945}
9946
9947/*
9948** The SQLITE_*_BKPT macros are substitutes for the error codes with
9949** the same name but without the _BKPT suffix.  These macros invoke
9950** routines that report the line-number on which the error originated
9951** using sqlite3_log().  The routines also provide a convenient place
9952** to set a debugger breakpoint.
9953*/
9954SQLITE_PRIVATE int sqlite3CorruptError(int);
9955SQLITE_PRIVATE int sqlite3MisuseError(int);
9956SQLITE_PRIVATE int sqlite3CantopenError(int);
9957#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
9958#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
9959#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
9960
9961
9962/*
9963** The ctype.h header is needed for non-ASCII systems.  It is also
9964** needed by FTS3 when FTS3 is included in the amalgamation.
9965*/
9966#if !defined(SQLITE_ASCII) || \
9967    (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
9968# include <ctype.h>
9969#endif
9970
9971/*
9972** The following macros mimic the standard library functions toupper(),
9973** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
9974** sqlite versions only work for ASCII characters, regardless of locale.
9975*/
9976#ifdef SQLITE_ASCII
9977# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
9978# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
9979# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
9980# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
9981# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
9982# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
9983# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
9984#else
9985# define sqlite3Toupper(x)   toupper((unsigned char)(x))
9986# define sqlite3Isspace(x)   isspace((unsigned char)(x))
9987# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
9988# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
9989# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
9990# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
9991# define sqlite3Tolower(x)   tolower((unsigned char)(x))
9992#endif
9993
9994/*
9995** Internal function prototypes
9996*/
9997SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
9998SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
9999SQLITE_PRIVATE int sqlite3Strlen30(const char*);
10000#define sqlite3StrNICmp sqlite3_strnicmp
10001
10002SQLITE_PRIVATE int sqlite3MallocInit(void);
10003SQLITE_PRIVATE void sqlite3MallocEnd(void);
10004SQLITE_PRIVATE void *sqlite3Malloc(int);
10005SQLITE_PRIVATE void *sqlite3MallocZero(int);
10006SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
10007SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
10008SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
10009SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
10010SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
10011SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
10012SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
10013SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
10014SQLITE_PRIVATE int sqlite3MallocSize(void*);
10015SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
10016SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
10017SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10018SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10019SQLITE_PRIVATE void sqlite3PageFree(void*);
10020SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10021SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10022SQLITE_PRIVATE int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
10023
10024/*
10025** On systems with ample stack space and that support alloca(), make
10026** use of alloca() to obtain space for large automatic objects.  By default,
10027** obtain space from malloc().
10028**
10029** The alloca() routine never returns NULL.  This will cause code paths
10030** that deal with sqlite3StackAlloc() failures to be unreachable.
10031*/
10032#ifdef SQLITE_USE_ALLOCA
10033# define sqlite3StackAllocRaw(D,N)   alloca(N)
10034# define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
10035# define sqlite3StackFree(D,P)
10036#else
10037# define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
10038# define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
10039# define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
10040#endif
10041
10042#ifdef SQLITE_ENABLE_MEMSYS3
10043SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10044#endif
10045#ifdef SQLITE_ENABLE_MEMSYS5
10046SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10047#endif
10048
10049
10050#ifndef SQLITE_MUTEX_OMIT
10051SQLITE_PRIVATE   sqlite3_mutex_methods *sqlite3DefaultMutex(void);
10052SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10053SQLITE_PRIVATE   int sqlite3MutexInit(void);
10054SQLITE_PRIVATE   int sqlite3MutexEnd(void);
10055#endif
10056
10057SQLITE_PRIVATE int sqlite3StatusValue(int);
10058SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10059SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10060
10061SQLITE_PRIVATE int sqlite3IsNaN(double);
10062
10063SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10064#ifndef SQLITE_OMIT_TRACE
10065SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
10066#endif
10067SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10068SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10069SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10070#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10071SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
10072#endif
10073#if defined(SQLITE_TEST)
10074SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
10075#endif
10076SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
10077SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
10078SQLITE_PRIVATE int sqlite3Dequote(char*);
10079SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
10080SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
10081SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
10082SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
10083SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
10084SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
10085SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
10086SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
10087SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
10088SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
10089SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
10090SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
10091SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
10092SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
10093SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
10094SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
10095SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
10096SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
10097SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
10098SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
10099SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
10100SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
10101SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
10102SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
10103SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
10104SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
10105SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
10106SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
10107SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
10108SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
10109SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
10110SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
10111SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
10112SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
10113SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
10114SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
10115
10116SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
10117SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
10118SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
10119SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
10120SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
10121SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
10122SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
10123
10124SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
10125SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
10126SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
10127SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
10128SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
10129
10130SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
10131
10132#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
10133SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
10134#else
10135# define sqlite3ViewGetColumnNames(A,B) 0
10136#endif
10137
10138SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
10139SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
10140#ifndef SQLITE_OMIT_AUTOINCREMENT
10141SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
10142SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
10143#else
10144# define sqlite3AutoincrementBegin(X)
10145# define sqlite3AutoincrementEnd(X)
10146#endif
10147SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
10148SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
10149SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
10150SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
10151SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
10152SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
10153SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
10154                                      Token*, Select*, Expr*, IdList*);
10155SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
10156SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
10157SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
10158SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
10159SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
10160SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
10161SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
10162                        Token*, int, int);
10163SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
10164SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
10165SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
10166                         Expr*,ExprList*,int,Expr*,Expr*);
10167SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
10168SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
10169SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
10170SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
10171#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
10172SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
10173#endif
10174SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
10175SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
10176SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
10177SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
10178SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
10179SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
10180SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
10181SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
10182SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
10183SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
10184SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
10185SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
10186SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
10187SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
10188SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
10189SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
10190SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
10191SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
10192SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
10193SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
10194SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
10195SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
10196SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
10197SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
10198SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
10199SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
10200SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
10201SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
10202SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
10203SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
10204SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
10205SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
10206SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
10207SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
10208SQLITE_PRIVATE void sqlite3PrngSaveState(void);
10209SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
10210SQLITE_PRIVATE void sqlite3PrngResetState(void);
10211SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
10212SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
10213SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
10214SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
10215SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
10216SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
10217SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
10218SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
10219SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
10220SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
10221SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
10222SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
10223SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
10224SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
10225SQLITE_PRIVATE int sqlite3IsRowid(const char*);
10226SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
10227SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
10228SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
10229SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
10230                                     int*,int,int,int,int,int*);
10231SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
10232SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
10233SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
10234SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
10235SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
10236SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
10237SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
10238SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
10239SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
10240SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
10241SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
10242SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
10243SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
10244SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
10245SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
10246SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
10247SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
10248SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
10249SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
10250
10251#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
10252SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
10253#endif
10254
10255#ifndef SQLITE_OMIT_TRIGGER
10256SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
10257                           Expr*,int, int);
10258SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
10259SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
10260SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
10261SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
10262SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
10263SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
10264                            int, int, int);
10265SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
10266  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
10267SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
10268SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
10269SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
10270                                        ExprList*,Select*,u8);
10271SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
10272SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
10273SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
10274SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
10275SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
10276# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
10277#else
10278# define sqlite3TriggersExist(B,C,D,E,F) 0
10279# define sqlite3DeleteTrigger(A,B)
10280# define sqlite3DropTriggerPtr(A,B)
10281# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
10282# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
10283# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
10284# define sqlite3TriggerList(X, Y) 0
10285# define sqlite3ParseToplevel(p) p
10286# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
10287#endif
10288
10289SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
10290SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
10291SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
10292#ifndef SQLITE_OMIT_AUTHORIZATION
10293SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
10294SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
10295SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
10296SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
10297SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
10298#else
10299# define sqlite3AuthRead(a,b,c,d)
10300# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
10301# define sqlite3AuthContextPush(a,b,c)
10302# define sqlite3AuthContextPop(a)  ((void)(a))
10303#endif
10304SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
10305SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
10306SQLITE_PRIVATE int sqlite3BtreeFactory(sqlite3 *db, const char *zFilename,
10307                       int omitJournal, int nCache, int flags, Btree **ppBtree);
10308SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
10309SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
10310SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
10311SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
10312SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
10313SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
10314SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
10315SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
10316SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
10317SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
10318SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
10319SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
10320
10321/*
10322** Routines to read and write variable-length integers.  These used to
10323** be defined locally, but now we use the varint routines in the util.c
10324** file.  Code should use the MACRO forms below, as the Varint32 versions
10325** are coded to assume the single byte case is already handled (which
10326** the MACRO form does).
10327*/
10328SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
10329SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
10330SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
10331SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
10332SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
10333
10334/*
10335** The header of a record consists of a sequence variable-length integers.
10336** These integers are almost always small and are encoded as a single byte.
10337** The following macros take advantage this fact to provide a fast encode
10338** and decode of the integers in a record header.  It is faster for the common
10339** case where the integer is a single byte.  It is a little slower when the
10340** integer is two or more bytes.  But overall it is faster.
10341**
10342** The following expressions are equivalent:
10343**
10344**     x = sqlite3GetVarint32( A, &B );
10345**     x = sqlite3PutVarint32( A, B );
10346**
10347**     x = getVarint32( A, B );
10348**     x = putVarint32( A, B );
10349**
10350*/
10351#define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
10352#define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
10353#define getVarint    sqlite3GetVarint
10354#define putVarint    sqlite3PutVarint
10355
10356
10357SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
10358SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
10359SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
10360SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
10361SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
10362SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
10363SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
10364SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
10365SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
10366SQLITE_PRIVATE const char *sqlite3ErrStr(int);
10367SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
10368SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
10369SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
10370SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
10371SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
10372SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
10373SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
10374SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
10375
10376SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
10377SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
10378SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
10379                        void(*)(void*));
10380SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
10381SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
10382SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int);
10383#ifdef SQLITE_ENABLE_STAT2
10384SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
10385#endif
10386SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
10387SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
10388#ifndef SQLITE_AMALGAMATION
10389SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
10390SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
10391SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
10392SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
10393SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10394SQLITE_PRIVATE int sqlite3PendingByte;
10395#endif
10396SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
10397SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
10398SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3*);
10399SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
10400SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
10401SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
10402SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
10403SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
10404SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
10405SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
10406SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
10407SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
10408SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
10409SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
10410SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
10411SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
10412SQLITE_PRIVATE char sqlite3AffinityType(const char*);
10413SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
10414SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
10415SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
10416SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
10417SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
10418SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index*);
10419SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
10420SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
10421SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
10422SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
10423SQLITE_PRIVATE void sqlite3SchemaFree(void *);
10424SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
10425SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
10426SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
10427SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
10428  void (*)(sqlite3_context*,int,sqlite3_value **),
10429  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
10430SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
10431SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
10432
10433SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
10434SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
10435SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
10436SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
10437SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
10438SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
10439
10440SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
10441SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
10442
10443/*
10444** The interface to the LEMON-generated parser
10445*/
10446SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
10447SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
10448SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
10449#ifdef YYTRACKMAXSTACKDEPTH
10450SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
10451#endif
10452
10453SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
10454#ifndef SQLITE_OMIT_LOAD_EXTENSION
10455SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
10456#else
10457# define sqlite3CloseExtensions(X)
10458#endif
10459
10460#ifndef SQLITE_OMIT_SHARED_CACHE
10461SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
10462#else
10463  #define sqlite3TableLock(v,w,x,y,z)
10464#endif
10465
10466#ifdef SQLITE_TEST
10467SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
10468#endif
10469
10470#ifdef SQLITE_OMIT_VIRTUALTABLE
10471#  define sqlite3VtabClear(Y)
10472#  define sqlite3VtabSync(X,Y) SQLITE_OK
10473#  define sqlite3VtabRollback(X)
10474#  define sqlite3VtabCommit(X)
10475#  define sqlite3VtabInSync(db) 0
10476#  define sqlite3VtabLock(X)
10477#  define sqlite3VtabUnlock(X)
10478#  define sqlite3VtabUnlockList(X)
10479#else
10480SQLITE_PRIVATE    void sqlite3VtabClear(Table*);
10481SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
10482SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
10483SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
10484SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
10485SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
10486SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
10487#  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
10488#endif
10489SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
10490SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
10491SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
10492SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
10493SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
10494SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
10495SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
10496SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
10497SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
10498SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
10499SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
10500SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
10501SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
10502SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
10503SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
10504SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
10505SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
10506SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
10507
10508/* Declarations for functions in fkey.c. All of these are replaced by
10509** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
10510** key functionality is available. If OMIT_TRIGGER is defined but
10511** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
10512** this case foreign keys are parsed, but no other functionality is
10513** provided (enforcement of FK constraints requires the triggers sub-system).
10514*/
10515#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
10516SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
10517SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
10518SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
10519SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
10520SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
10521SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
10522#else
10523  #define sqlite3FkActions(a,b,c,d)
10524  #define sqlite3FkCheck(a,b,c,d)
10525  #define sqlite3FkDropTable(a,b,c)
10526  #define sqlite3FkOldmask(a,b)      0
10527  #define sqlite3FkRequired(a,b,c,d) 0
10528#endif
10529#ifndef SQLITE_OMIT_FOREIGN_KEY
10530SQLITE_PRIVATE   void sqlite3FkDelete(Table*);
10531#else
10532  #define sqlite3FkDelete(a)
10533#endif
10534
10535
10536/*
10537** Available fault injectors.  Should be numbered beginning with 0.
10538*/
10539#define SQLITE_FAULTINJECTOR_MALLOC     0
10540#define SQLITE_FAULTINJECTOR_COUNT      1
10541
10542/*
10543** The interface to the code in fault.c used for identifying "benign"
10544** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
10545** is not defined.
10546*/
10547#ifndef SQLITE_OMIT_BUILTIN_TEST
10548SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
10549SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
10550#else
10551  #define sqlite3BeginBenignMalloc()
10552  #define sqlite3EndBenignMalloc()
10553#endif
10554
10555#define IN_INDEX_ROWID           1
10556#define IN_INDEX_EPH             2
10557#define IN_INDEX_INDEX           3
10558SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
10559
10560#ifdef SQLITE_ENABLE_ATOMIC_WRITE
10561SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
10562SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
10563SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
10564#else
10565  #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
10566#endif
10567
10568SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
10569SQLITE_PRIVATE int sqlite3MemJournalSize(void);
10570SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
10571
10572#if SQLITE_MAX_EXPR_DEPTH>0
10573SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
10574SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
10575SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
10576#else
10577  #define sqlite3ExprSetHeight(x,y)
10578  #define sqlite3SelectExprHeight(x) 0
10579  #define sqlite3ExprCheckHeight(x,y)
10580#endif
10581
10582SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
10583SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
10584
10585#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10586SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
10587SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
10588SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
10589#else
10590  #define sqlite3ConnectionBlocked(x,y)
10591  #define sqlite3ConnectionUnlocked(x)
10592  #define sqlite3ConnectionClosed(x)
10593#endif
10594
10595#ifdef SQLITE_DEBUG
10596SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
10597#endif
10598
10599/*
10600** If the SQLITE_ENABLE IOTRACE exists then the global variable
10601** sqlite3IoTrace is a pointer to a printf-like routine used to
10602** print I/O tracing messages.
10603*/
10604#ifdef SQLITE_ENABLE_IOTRACE
10605# define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
10606SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
10607SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
10608#else
10609# define IOTRACE(A)
10610# define sqlite3VdbeIOTraceSql(X)
10611#endif
10612
10613#endif
10614
10615/************** End of sqliteInt.h *******************************************/
10616/************** Begin file global.c ******************************************/
10617/*
10618** 2008 June 13
10619**
10620** The author disclaims copyright to this source code.  In place of
10621** a legal notice, here is a blessing:
10622**
10623**    May you do good and not evil.
10624**    May you find forgiveness for yourself and forgive others.
10625**    May you share freely, never taking more than you give.
10626**
10627*************************************************************************
10628**
10629** This file contains definitions of global variables and contants.
10630*/
10631
10632/* An array to map all upper-case characters into their corresponding
10633** lower-case character.
10634**
10635** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
10636** handle case conversions for the UTF character set since the tables
10637** involved are nearly as big or bigger than SQLite itself.
10638*/
10639SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
10640#ifdef SQLITE_ASCII
10641      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
10642     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
10643     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
10644     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
10645    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
10646    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
10647    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
10648    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
10649    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
10650    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
10651    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
10652    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
10653    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
10654    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
10655    252,253,254,255
10656#endif
10657#ifdef SQLITE_EBCDIC
10658      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
10659     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
10660     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
10661     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
10662     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
10663     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
10664     96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
10665    112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
10666    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
10667    144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
10668    160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
10669    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
10670    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
10671    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
10672    224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
10673    239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
10674#endif
10675};
10676
10677/*
10678** The following 256 byte lookup table is used to support SQLites built-in
10679** equivalents to the following standard library functions:
10680**
10681**   isspace()                        0x01
10682**   isalpha()                        0x02
10683**   isdigit()                        0x04
10684**   isalnum()                        0x06
10685**   isxdigit()                       0x08
10686**   toupper()                        0x20
10687**   SQLite identifier character      0x40
10688**
10689** Bit 0x20 is set if the mapped character requires translation to upper
10690** case. i.e. if the character is a lower-case ASCII character.
10691** If x is a lower-case ASCII character, then its upper-case equivalent
10692** is (x - 0x20). Therefore toupper() can be implemented as:
10693**
10694**   (x & ~(map[x]&0x20))
10695**
10696** Standard function tolower() is implemented using the sqlite3UpperToLower[]
10697** array. tolower() is used more often than toupper() by SQLite.
10698**
10699** Bit 0x40 is set if the character non-alphanumeric and can be used in an
10700** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
10701** non-ASCII UTF character. Hence the test for whether or not a character is
10702** part of an identifier is 0x46.
10703**
10704** SQLite's versions are identical to the standard versions assuming a
10705** locale of "C". They are implemented as macros in sqliteInt.h.
10706*/
10707#ifdef SQLITE_ASCII
10708SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
10709  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
10710  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
10711  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
10712  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
10713  0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
10714  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
10715  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
10716  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
10717
10718  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
10719  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
10720  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
10721  0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
10722  0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
10723  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
10724  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
10725  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
10726
10727  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
10728  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
10729  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
10730  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
10731  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
10732  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
10733  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
10734  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
10735
10736  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
10737  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
10738  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
10739  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
10740  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
10741  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
10742  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
10743  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
10744};
10745#endif
10746
10747
10748
10749/*
10750** The following singleton contains the global configuration for
10751** the SQLite library.
10752*/
10753SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
10754   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
10755   1,                         /* bCoreMutex */
10756   SQLITE_THREADSAFE==1,      /* bFullMutex */
10757   0x7ffffffe,                /* mxStrlen */
10758   100,                       /* szLookaside */
10759   500,                       /* nLookaside */
10760   {0,0,0,0,0,0,0,0},         /* m */
10761   {0,0,0,0,0,0,0,0,0},       /* mutex */
10762   {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
10763   (void*)0,                  /* pHeap */
10764   0,                         /* nHeap */
10765   0, 0,                      /* mnHeap, mxHeap */
10766   (void*)0,                  /* pScratch */
10767   0,                         /* szScratch */
10768   0,                         /* nScratch */
10769   (void*)0,                  /* pPage */
10770   0,                         /* szPage */
10771   0,                         /* nPage */
10772   0,                         /* mxParserStack */
10773   0,                         /* sharedCacheEnabled */
10774   /* All the rest should always be initialized to zero */
10775   0,                         /* isInit */
10776   0,                         /* inProgress */
10777   0,                         /* isMutexInit */
10778   0,                         /* isMallocInit */
10779   0,                         /* isPCacheInit */
10780   0,                         /* pInitMutex */
10781   0,                         /* nRefInitMutex */
10782   0,                         /* xLog */
10783   0,                         /* pLogArg */
10784};
10785
10786
10787/*
10788** Hash table for global functions - functions common to all
10789** database connections.  After initialization, this table is
10790** read-only.
10791*/
10792SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10793
10794/*
10795** The value of the "pending" byte must be 0x40000000 (1 byte past the
10796** 1-gibabyte boundary) in a compatible database.  SQLite never uses
10797** the database page that contains the pending byte.  It never attempts
10798** to read or write that page.  The pending byte page is set assign
10799** for use by the VFS layers as space for managing file locks.
10800**
10801** During testing, it is often desirable to move the pending byte to
10802** a different position in the file.  This allows code that has to
10803** deal with the pending byte to run on files that are much smaller
10804** than 1 GiB.  The sqlite3_test_control() interface can be used to
10805** move the pending byte.
10806**
10807** IMPORTANT:  Changing the pending byte to any value other than
10808** 0x40000000 results in an incompatible database file format!
10809** Changing the pending byte during operating results in undefined
10810** and dileterious behavior.
10811*/
10812SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
10813
10814/*
10815** Properties of opcodes.  The OPFLG_INITIALIZER macro is
10816** created by mkopcodeh.awk during compilation.  Data is obtained
10817** from the comments following the "case OP_xxxx:" statements in
10818** the vdbe.c file.
10819*/
10820SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
10821
10822/************** End of global.c **********************************************/
10823/************** Begin file status.c ******************************************/
10824/*
10825** 2008 June 18
10826**
10827** The author disclaims copyright to this source code.  In place of
10828** a legal notice, here is a blessing:
10829**
10830**    May you do good and not evil.
10831**    May you find forgiveness for yourself and forgive others.
10832**    May you share freely, never taking more than you give.
10833**
10834*************************************************************************
10835**
10836** This module implements the sqlite3_status() interface and related
10837** functionality.
10838*/
10839
10840/*
10841** Variables in which to record status information.
10842*/
10843typedef struct sqlite3StatType sqlite3StatType;
10844static SQLITE_WSD struct sqlite3StatType {
10845  int nowValue[9];         /* Current value */
10846  int mxValue[9];          /* Maximum value */
10847} sqlite3Stat = { {0,}, {0,} };
10848
10849
10850/* The "wsdStat" macro will resolve to the status information
10851** state vector.  If writable static data is unsupported on the target,
10852** we have to locate the state vector at run-time.  In the more common
10853** case where writable static data is supported, wsdStat can refer directly
10854** to the "sqlite3Stat" state vector declared above.
10855*/
10856#ifdef SQLITE_OMIT_WSD
10857# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
10858# define wsdStat x[0]
10859#else
10860# define wsdStatInit
10861# define wsdStat sqlite3Stat
10862#endif
10863
10864/*
10865** Return the current value of a status parameter.
10866*/
10867SQLITE_PRIVATE int sqlite3StatusValue(int op){
10868  wsdStatInit;
10869  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
10870  return wsdStat.nowValue[op];
10871}
10872
10873/*
10874** Add N to the value of a status record.  It is assumed that the
10875** caller holds appropriate locks.
10876*/
10877SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
10878  wsdStatInit;
10879  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
10880  wsdStat.nowValue[op] += N;
10881  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
10882    wsdStat.mxValue[op] = wsdStat.nowValue[op];
10883  }
10884}
10885
10886/*
10887** Set the value of a status to X.
10888*/
10889SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
10890  wsdStatInit;
10891  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
10892  wsdStat.nowValue[op] = X;
10893  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
10894    wsdStat.mxValue[op] = wsdStat.nowValue[op];
10895  }
10896}
10897
10898/*
10899** Query status information.
10900**
10901** This implementation assumes that reading or writing an aligned
10902** 32-bit integer is an atomic operation.  If that assumption is not true,
10903** then this routine is not threadsafe.
10904*/
10905SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
10906  wsdStatInit;
10907  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
10908    return SQLITE_MISUSE_BKPT;
10909  }
10910  *pCurrent = wsdStat.nowValue[op];
10911  *pHighwater = wsdStat.mxValue[op];
10912  if( resetFlag ){
10913    wsdStat.mxValue[op] = wsdStat.nowValue[op];
10914  }
10915  return SQLITE_OK;
10916}
10917
10918/*
10919** Query status information for a single database connection
10920*/
10921SQLITE_API int sqlite3_db_status(
10922  sqlite3 *db,          /* The database connection whose status is desired */
10923  int op,               /* Status verb */
10924  int *pCurrent,        /* Write current value here */
10925  int *pHighwater,      /* Write high-water mark here */
10926  int resetFlag         /* Reset high-water mark if true */
10927){
10928  switch( op ){
10929    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
10930      *pCurrent = db->lookaside.nOut;
10931      *pHighwater = db->lookaside.mxOut;
10932      if( resetFlag ){
10933        db->lookaside.mxOut = db->lookaside.nOut;
10934      }
10935      break;
10936    }
10937    default: {
10938      return SQLITE_ERROR;
10939    }
10940  }
10941  return SQLITE_OK;
10942}
10943
10944/************** End of status.c **********************************************/
10945/************** Begin file date.c ********************************************/
10946/*
10947** 2003 October 31
10948**
10949** The author disclaims copyright to this source code.  In place of
10950** a legal notice, here is a blessing:
10951**
10952**    May you do good and not evil.
10953**    May you find forgiveness for yourself and forgive others.
10954**    May you share freely, never taking more than you give.
10955**
10956*************************************************************************
10957** This file contains the C functions that implement date and time
10958** functions for SQLite.
10959**
10960** There is only one exported symbol in this file - the function
10961** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
10962** All other code has file scope.
10963**
10964** SQLite processes all times and dates as Julian Day numbers.  The
10965** dates and times are stored as the number of days since noon
10966** in Greenwich on November 24, 4714 B.C. according to the Gregorian
10967** calendar system.
10968**
10969** 1970-01-01 00:00:00 is JD 2440587.5
10970** 2000-01-01 00:00:00 is JD 2451544.5
10971**
10972** This implemention requires years to be expressed as a 4-digit number
10973** which means that only dates between 0000-01-01 and 9999-12-31 can
10974** be represented, even though julian day numbers allow a much wider
10975** range of dates.
10976**
10977** The Gregorian calendar system is used for all dates and times,
10978** even those that predate the Gregorian calendar.  Historians usually
10979** use the Julian calendar for dates prior to 1582-10-15 and for some
10980** dates afterwards, depending on locale.  Beware of this difference.
10981**
10982** The conversion algorithms are implemented based on descriptions
10983** in the following text:
10984**
10985**      Jean Meeus
10986**      Astronomical Algorithms, 2nd Edition, 1998
10987**      ISBM 0-943396-61-1
10988**      Willmann-Bell, Inc
10989**      Richmond, Virginia (USA)
10990*/
10991#include <time.h>
10992
10993#ifndef SQLITE_OMIT_DATETIME_FUNCS
10994
10995/*
10996** On recent Windows platforms, the localtime_s() function is available
10997** as part of the "Secure CRT". It is essentially equivalent to
10998** localtime_r() available under most POSIX platforms, except that the
10999** order of the parameters is reversed.
11000**
11001** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
11002**
11003** If the user has not indicated to use localtime_r() or localtime_s()
11004** already, check for an MSVC build environment that provides
11005** localtime_s().
11006*/
11007#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
11008     defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
11009#define HAVE_LOCALTIME_S 1
11010#endif
11011
11012/*
11013** A structure for holding a single date and time.
11014*/
11015typedef struct DateTime DateTime;
11016struct DateTime {
11017  sqlite3_int64 iJD; /* The julian day number times 86400000 */
11018  int Y, M, D;       /* Year, month, and day */
11019  int h, m;          /* Hour and minutes */
11020  int tz;            /* Timezone offset in minutes */
11021  double s;          /* Seconds */
11022  char validYMD;     /* True (1) if Y,M,D are valid */
11023  char validHMS;     /* True (1) if h,m,s are valid */
11024  char validJD;      /* True (1) if iJD is valid */
11025  char validTZ;      /* True (1) if tz is valid */
11026};
11027
11028
11029/*
11030** Convert zDate into one or more integers.  Additional arguments
11031** come in groups of 5 as follows:
11032**
11033**       N       number of digits in the integer
11034**       min     minimum allowed value of the integer
11035**       max     maximum allowed value of the integer
11036**       nextC   first character after the integer
11037**       pVal    where to write the integers value.
11038**
11039** Conversions continue until one with nextC==0 is encountered.
11040** The function returns the number of successful conversions.
11041*/
11042static int getDigits(const char *zDate, ...){
11043  va_list ap;
11044  int val;
11045  int N;
11046  int min;
11047  int max;
11048  int nextC;
11049  int *pVal;
11050  int cnt = 0;
11051  va_start(ap, zDate);
11052  do{
11053    N = va_arg(ap, int);
11054    min = va_arg(ap, int);
11055    max = va_arg(ap, int);
11056    nextC = va_arg(ap, int);
11057    pVal = va_arg(ap, int*);
11058    val = 0;
11059    while( N-- ){
11060      if( !sqlite3Isdigit(*zDate) ){
11061        goto end_getDigits;
11062      }
11063      val = val*10 + *zDate - '0';
11064      zDate++;
11065    }
11066    if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
11067      goto end_getDigits;
11068    }
11069    *pVal = val;
11070    zDate++;
11071    cnt++;
11072  }while( nextC );
11073end_getDigits:
11074  va_end(ap);
11075  return cnt;
11076}
11077
11078/*
11079** Read text from z[] and convert into a floating point number.  Return
11080** the number of digits converted.
11081*/
11082#define getValue sqlite3AtoF
11083
11084/*
11085** Parse a timezone extension on the end of a date-time.
11086** The extension is of the form:
11087**
11088**        (+/-)HH:MM
11089**
11090** Or the "zulu" notation:
11091**
11092**        Z
11093**
11094** If the parse is successful, write the number of minutes
11095** of change in p->tz and return 0.  If a parser error occurs,
11096** return non-zero.
11097**
11098** A missing specifier is not considered an error.
11099*/
11100static int parseTimezone(const char *zDate, DateTime *p){
11101  int sgn = 0;
11102  int nHr, nMn;
11103  int c;
11104  while( sqlite3Isspace(*zDate) ){ zDate++; }
11105  p->tz = 0;
11106  c = *zDate;
11107  if( c=='-' ){
11108    sgn = -1;
11109  }else if( c=='+' ){
11110    sgn = +1;
11111  }else if( c=='Z' || c=='z' ){
11112    zDate++;
11113    goto zulu_time;
11114  }else{
11115    return c!=0;
11116  }
11117  zDate++;
11118  if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
11119    return 1;
11120  }
11121  zDate += 5;
11122  p->tz = sgn*(nMn + nHr*60);
11123zulu_time:
11124  while( sqlite3Isspace(*zDate) ){ zDate++; }
11125  return *zDate!=0;
11126}
11127
11128/*
11129** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
11130** The HH, MM, and SS must each be exactly 2 digits.  The
11131** fractional seconds FFFF can be one or more digits.
11132**
11133** Return 1 if there is a parsing error and 0 on success.
11134*/
11135static int parseHhMmSs(const char *zDate, DateTime *p){
11136  int h, m, s;
11137  double ms = 0.0;
11138  if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
11139    return 1;
11140  }
11141  zDate += 5;
11142  if( *zDate==':' ){
11143    zDate++;
11144    if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
11145      return 1;
11146    }
11147    zDate += 2;
11148    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
11149      double rScale = 1.0;
11150      zDate++;
11151      while( sqlite3Isdigit(*zDate) ){
11152        ms = ms*10.0 + *zDate - '0';
11153        rScale *= 10.0;
11154        zDate++;
11155      }
11156      ms /= rScale;
11157    }
11158  }else{
11159    s = 0;
11160  }
11161  p->validJD = 0;
11162  p->validHMS = 1;
11163  p->h = h;
11164  p->m = m;
11165  p->s = s + ms;
11166  if( parseTimezone(zDate, p) ) return 1;
11167  p->validTZ = (p->tz!=0)?1:0;
11168  return 0;
11169}
11170
11171/*
11172** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
11173** that the YYYY-MM-DD is according to the Gregorian calendar.
11174**
11175** Reference:  Meeus page 61
11176*/
11177static void computeJD(DateTime *p){
11178  int Y, M, D, A, B, X1, X2;
11179
11180  if( p->validJD ) return;
11181  if( p->validYMD ){
11182    Y = p->Y;
11183    M = p->M;
11184    D = p->D;
11185  }else{
11186    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
11187    M = 1;
11188    D = 1;
11189  }
11190  if( M<=2 ){
11191    Y--;
11192    M += 12;
11193  }
11194  A = Y/100;
11195  B = 2 - A + (A/4);
11196  X1 = 36525*(Y+4716)/100;
11197  X2 = 306001*(M+1)/10000;
11198  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
11199  p->validJD = 1;
11200  if( p->validHMS ){
11201    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
11202    if( p->validTZ ){
11203      p->iJD -= p->tz*60000;
11204      p->validYMD = 0;
11205      p->validHMS = 0;
11206      p->validTZ = 0;
11207    }
11208  }
11209}
11210
11211/*
11212** Parse dates of the form
11213**
11214**     YYYY-MM-DD HH:MM:SS.FFF
11215**     YYYY-MM-DD HH:MM:SS
11216**     YYYY-MM-DD HH:MM
11217**     YYYY-MM-DD
11218**
11219** Write the result into the DateTime structure and return 0
11220** on success and 1 if the input string is not a well-formed
11221** date.
11222*/
11223static int parseYyyyMmDd(const char *zDate, DateTime *p){
11224  int Y, M, D, neg;
11225
11226  if( zDate[0]=='-' ){
11227    zDate++;
11228    neg = 1;
11229  }else{
11230    neg = 0;
11231  }
11232  if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
11233    return 1;
11234  }
11235  zDate += 10;
11236  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
11237  if( parseHhMmSs(zDate, p)==0 ){
11238    /* We got the time */
11239  }else if( *zDate==0 ){
11240    p->validHMS = 0;
11241  }else{
11242    return 1;
11243  }
11244  p->validJD = 0;
11245  p->validYMD = 1;
11246  p->Y = neg ? -Y : Y;
11247  p->M = M;
11248  p->D = D;
11249  if( p->validTZ ){
11250    computeJD(p);
11251  }
11252  return 0;
11253}
11254
11255/*
11256** Set the time to the current time reported by the VFS
11257*/
11258static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
11259  double r;
11260  sqlite3 *db = sqlite3_context_db_handle(context);
11261  sqlite3OsCurrentTime(db->pVfs, &r);
11262  p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
11263  p->validJD = 1;
11264}
11265
11266/*
11267** Attempt to parse the given string into a Julian Day Number.  Return
11268** the number of errors.
11269**
11270** The following are acceptable forms for the input string:
11271**
11272**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
11273**      DDDD.DD
11274**      now
11275**
11276** In the first form, the +/-HH:MM is always optional.  The fractional
11277** seconds extension (the ".FFF") is optional.  The seconds portion
11278** (":SS.FFF") is option.  The year and date can be omitted as long
11279** as there is a time string.  The time string can be omitted as long
11280** as there is a year and date.
11281*/
11282static int parseDateOrTime(
11283  sqlite3_context *context,
11284  const char *zDate,
11285  DateTime *p
11286){
11287  int isRealNum;    /* Return from sqlite3IsNumber().  Not used */
11288  if( parseYyyyMmDd(zDate,p)==0 ){
11289    return 0;
11290  }else if( parseHhMmSs(zDate, p)==0 ){
11291    return 0;
11292  }else if( sqlite3StrICmp(zDate,"now")==0){
11293    setDateTimeToCurrent(context, p);
11294    return 0;
11295  }else if( sqlite3IsNumber(zDate, &isRealNum, SQLITE_UTF8) ){
11296    double r;
11297    getValue(zDate, &r);
11298    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
11299    p->validJD = 1;
11300    return 0;
11301  }
11302  return 1;
11303}
11304
11305/*
11306** Compute the Year, Month, and Day from the julian day number.
11307*/
11308static void computeYMD(DateTime *p){
11309  int Z, A, B, C, D, E, X1;
11310  if( p->validYMD ) return;
11311  if( !p->validJD ){
11312    p->Y = 2000;
11313    p->M = 1;
11314    p->D = 1;
11315  }else{
11316    Z = (int)((p->iJD + 43200000)/86400000);
11317    A = (int)((Z - 1867216.25)/36524.25);
11318    A = Z + 1 + A - (A/4);
11319    B = A + 1524;
11320    C = (int)((B - 122.1)/365.25);
11321    D = (36525*C)/100;
11322    E = (int)((B-D)/30.6001);
11323    X1 = (int)(30.6001*E);
11324    p->D = B - D - X1;
11325    p->M = E<14 ? E-1 : E-13;
11326    p->Y = p->M>2 ? C - 4716 : C - 4715;
11327  }
11328  p->validYMD = 1;
11329}
11330
11331/*
11332** Compute the Hour, Minute, and Seconds from the julian day number.
11333*/
11334static void computeHMS(DateTime *p){
11335  int s;
11336  if( p->validHMS ) return;
11337  computeJD(p);
11338  s = (int)((p->iJD + 43200000) % 86400000);
11339  p->s = s/1000.0;
11340  s = (int)p->s;
11341  p->s -= s;
11342  p->h = s/3600;
11343  s -= p->h*3600;
11344  p->m = s/60;
11345  p->s += s - p->m*60;
11346  p->validHMS = 1;
11347}
11348
11349/*
11350** Compute both YMD and HMS
11351*/
11352static void computeYMD_HMS(DateTime *p){
11353  computeYMD(p);
11354  computeHMS(p);
11355}
11356
11357/*
11358** Clear the YMD and HMS and the TZ
11359*/
11360static void clearYMD_HMS_TZ(DateTime *p){
11361  p->validYMD = 0;
11362  p->validHMS = 0;
11363  p->validTZ = 0;
11364}
11365
11366#ifndef SQLITE_OMIT_LOCALTIME
11367/*
11368** Compute the difference (in milliseconds)
11369** between localtime and UTC (a.k.a. GMT)
11370** for the time value p where p is in UTC.
11371*/
11372static sqlite3_int64 localtimeOffset(DateTime *p){
11373  DateTime x, y;
11374  time_t t;
11375  x = *p;
11376  computeYMD_HMS(&x);
11377  if( x.Y<1971 || x.Y>=2038 ){
11378    x.Y = 2000;
11379    x.M = 1;
11380    x.D = 1;
11381    x.h = 0;
11382    x.m = 0;
11383    x.s = 0.0;
11384  } else {
11385    int s = (int)(x.s + 0.5);
11386    x.s = s;
11387  }
11388  x.tz = 0;
11389  x.validJD = 0;
11390  computeJD(&x);
11391  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
11392#ifdef HAVE_LOCALTIME_R
11393  {
11394    struct tm sLocal;
11395    localtime_r(&t, &sLocal);
11396    y.Y = sLocal.tm_year + 1900;
11397    y.M = sLocal.tm_mon + 1;
11398    y.D = sLocal.tm_mday;
11399    y.h = sLocal.tm_hour;
11400    y.m = sLocal.tm_min;
11401    y.s = sLocal.tm_sec;
11402  }
11403#elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
11404  {
11405    struct tm sLocal;
11406    localtime_s(&sLocal, &t);
11407    y.Y = sLocal.tm_year + 1900;
11408    y.M = sLocal.tm_mon + 1;
11409    y.D = sLocal.tm_mday;
11410    y.h = sLocal.tm_hour;
11411    y.m = sLocal.tm_min;
11412    y.s = sLocal.tm_sec;
11413  }
11414#else
11415  {
11416    struct tm *pTm;
11417    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11418    pTm = localtime(&t);
11419    y.Y = pTm->tm_year + 1900;
11420    y.M = pTm->tm_mon + 1;
11421    y.D = pTm->tm_mday;
11422    y.h = pTm->tm_hour;
11423    y.m = pTm->tm_min;
11424    y.s = pTm->tm_sec;
11425    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11426  }
11427#endif
11428  y.validYMD = 1;
11429  y.validHMS = 1;
11430  y.validJD = 0;
11431  y.validTZ = 0;
11432  computeJD(&y);
11433  return y.iJD - x.iJD;
11434}
11435#endif /* SQLITE_OMIT_LOCALTIME */
11436
11437/*
11438** Process a modifier to a date-time stamp.  The modifiers are
11439** as follows:
11440**
11441**     NNN days
11442**     NNN hours
11443**     NNN minutes
11444**     NNN.NNNN seconds
11445**     NNN months
11446**     NNN years
11447**     start of month
11448**     start of year
11449**     start of week
11450**     start of day
11451**     weekday N
11452**     unixepoch
11453**     localtime
11454**     utc
11455**
11456** Return 0 on success and 1 if there is any kind of error.
11457*/
11458static int parseModifier(const char *zMod, DateTime *p){
11459  int rc = 1;
11460  int n;
11461  double r;
11462  char *z, zBuf[30];
11463  z = zBuf;
11464  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
11465    z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
11466  }
11467  z[n] = 0;
11468  switch( z[0] ){
11469#ifndef SQLITE_OMIT_LOCALTIME
11470    case 'l': {
11471      /*    localtime
11472      **
11473      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
11474      ** show local time.
11475      */
11476      if( strcmp(z, "localtime")==0 ){
11477        computeJD(p);
11478        p->iJD += localtimeOffset(p);
11479        clearYMD_HMS_TZ(p);
11480        rc = 0;
11481      }
11482      break;
11483    }
11484#endif
11485    case 'u': {
11486      /*
11487      **    unixepoch
11488      **
11489      ** Treat the current value of p->iJD as the number of
11490      ** seconds since 1970.  Convert to a real julian day number.
11491      */
11492      if( strcmp(z, "unixepoch")==0 && p->validJD ){
11493        p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
11494        clearYMD_HMS_TZ(p);
11495        rc = 0;
11496      }
11497#ifndef SQLITE_OMIT_LOCALTIME
11498      else if( strcmp(z, "utc")==0 ){
11499        sqlite3_int64 c1;
11500        computeJD(p);
11501        c1 = localtimeOffset(p);
11502        p->iJD -= c1;
11503        clearYMD_HMS_TZ(p);
11504        p->iJD += c1 - localtimeOffset(p);
11505        rc = 0;
11506      }
11507#endif
11508      break;
11509    }
11510    case 'w': {
11511      /*
11512      **    weekday N
11513      **
11514      ** Move the date to the same time on the next occurrence of
11515      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
11516      ** date is already on the appropriate weekday, this is a no-op.
11517      */
11518      if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
11519                 && (n=(int)r)==r && n>=0 && r<7 ){
11520        sqlite3_int64 Z;
11521        computeYMD_HMS(p);
11522        p->validTZ = 0;
11523        p->validJD = 0;
11524        computeJD(p);
11525        Z = ((p->iJD + 129600000)/86400000) % 7;
11526        if( Z>n ) Z -= 7;
11527        p->iJD += (n - Z)*86400000;
11528        clearYMD_HMS_TZ(p);
11529        rc = 0;
11530      }
11531      break;
11532    }
11533    case 's': {
11534      /*
11535      **    start of TTTTT
11536      **
11537      ** Move the date backwards to the beginning of the current day,
11538      ** or month or year.
11539      */
11540      if( strncmp(z, "start of ", 9)!=0 ) break;
11541      z += 9;
11542      computeYMD(p);
11543      p->validHMS = 1;
11544      p->h = p->m = 0;
11545      p->s = 0.0;
11546      p->validTZ = 0;
11547      p->validJD = 0;
11548      if( strcmp(z,"month")==0 ){
11549        p->D = 1;
11550        rc = 0;
11551      }else if( strcmp(z,"year")==0 ){
11552        computeYMD(p);
11553        p->M = 1;
11554        p->D = 1;
11555        rc = 0;
11556      }else if( strcmp(z,"day")==0 ){
11557        rc = 0;
11558      }
11559      break;
11560    }
11561    case '+':
11562    case '-':
11563    case '0':
11564    case '1':
11565    case '2':
11566    case '3':
11567    case '4':
11568    case '5':
11569    case '6':
11570    case '7':
11571    case '8':
11572    case '9': {
11573      double rRounder;
11574      n = getValue(z, &r);
11575      assert( n>=1 );
11576      if( z[n]==':' ){
11577        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
11578        ** specified number of hours, minutes, seconds, and fractional seconds
11579        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
11580        ** omitted.
11581        */
11582        const char *z2 = z;
11583        DateTime tx;
11584        sqlite3_int64 day;
11585        if( !sqlite3Isdigit(*z2) ) z2++;
11586        memset(&tx, 0, sizeof(tx));
11587        if( parseHhMmSs(z2, &tx) ) break;
11588        computeJD(&tx);
11589        tx.iJD -= 43200000;
11590        day = tx.iJD/86400000;
11591        tx.iJD -= day*86400000;
11592        if( z[0]=='-' ) tx.iJD = -tx.iJD;
11593        computeJD(p);
11594        clearYMD_HMS_TZ(p);
11595        p->iJD += tx.iJD;
11596        rc = 0;
11597        break;
11598      }
11599      z += n;
11600      while( sqlite3Isspace(*z) ) z++;
11601      n = sqlite3Strlen30(z);
11602      if( n>10 || n<3 ) break;
11603      if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
11604      computeJD(p);
11605      rc = 0;
11606      rRounder = r<0 ? -0.5 : +0.5;
11607      if( n==3 && strcmp(z,"day")==0 ){
11608        p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
11609      }else if( n==4 && strcmp(z,"hour")==0 ){
11610        p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
11611      }else if( n==6 && strcmp(z,"minute")==0 ){
11612        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
11613      }else if( n==6 && strcmp(z,"second")==0 ){
11614        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
11615      }else if( n==5 && strcmp(z,"month")==0 ){
11616        int x, y;
11617        computeYMD_HMS(p);
11618        p->M += (int)r;
11619        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
11620        p->Y += x;
11621        p->M -= x*12;
11622        p->validJD = 0;
11623        computeJD(p);
11624        y = (int)r;
11625        if( y!=r ){
11626          p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
11627        }
11628      }else if( n==4 && strcmp(z,"year")==0 ){
11629        int y = (int)r;
11630        computeYMD_HMS(p);
11631        p->Y += y;
11632        p->validJD = 0;
11633        computeJD(p);
11634        if( y!=r ){
11635          p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
11636        }
11637      }else{
11638        rc = 1;
11639      }
11640      clearYMD_HMS_TZ(p);
11641      break;
11642    }
11643    default: {
11644      break;
11645    }
11646  }
11647  return rc;
11648}
11649
11650/*
11651** Process time function arguments.  argv[0] is a date-time stamp.
11652** argv[1] and following are modifiers.  Parse them all and write
11653** the resulting time into the DateTime structure p.  Return 0
11654** on success and 1 if there are any errors.
11655**
11656** If there are zero parameters (if even argv[0] is undefined)
11657** then assume a default value of "now" for argv[0].
11658*/
11659static int isDate(
11660  sqlite3_context *context,
11661  int argc,
11662  sqlite3_value **argv,
11663  DateTime *p
11664){
11665  int i;
11666  const unsigned char *z;
11667  int eType;
11668  memset(p, 0, sizeof(*p));
11669  if( argc==0 ){
11670    setDateTimeToCurrent(context, p);
11671  }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
11672                   || eType==SQLITE_INTEGER ){
11673    p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
11674    p->validJD = 1;
11675  }else{
11676    z = sqlite3_value_text(argv[0]);
11677    if( !z || parseDateOrTime(context, (char*)z, p) ){
11678      return 1;
11679    }
11680  }
11681  for(i=1; i<argc; i++){
11682    if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
11683      return 1;
11684    }
11685  }
11686  return 0;
11687}
11688
11689
11690/*
11691** The following routines implement the various date and time functions
11692** of SQLite.
11693*/
11694
11695/*
11696**    julianday( TIMESTRING, MOD, MOD, ...)
11697**
11698** Return the julian day number of the date specified in the arguments
11699*/
11700static void juliandayFunc(
11701  sqlite3_context *context,
11702  int argc,
11703  sqlite3_value **argv
11704){
11705  DateTime x;
11706  if( isDate(context, argc, argv, &x)==0 ){
11707    computeJD(&x);
11708    sqlite3_result_double(context, x.iJD/86400000.0);
11709  }
11710}
11711
11712/*
11713**    datetime( TIMESTRING, MOD, MOD, ...)
11714**
11715** Return YYYY-MM-DD HH:MM:SS
11716*/
11717static void datetimeFunc(
11718  sqlite3_context *context,
11719  int argc,
11720  sqlite3_value **argv
11721){
11722  DateTime x;
11723  if( isDate(context, argc, argv, &x)==0 ){
11724    char zBuf[100];
11725    computeYMD_HMS(&x);
11726    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
11727                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
11728    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11729  }
11730}
11731
11732/*
11733**    time( TIMESTRING, MOD, MOD, ...)
11734**
11735** Return HH:MM:SS
11736*/
11737static void timeFunc(
11738  sqlite3_context *context,
11739  int argc,
11740  sqlite3_value **argv
11741){
11742  DateTime x;
11743  if( isDate(context, argc, argv, &x)==0 ){
11744    char zBuf[100];
11745    computeHMS(&x);
11746    sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
11747    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11748  }
11749}
11750
11751/*
11752**    date( TIMESTRING, MOD, MOD, ...)
11753**
11754** Return YYYY-MM-DD
11755*/
11756static void dateFunc(
11757  sqlite3_context *context,
11758  int argc,
11759  sqlite3_value **argv
11760){
11761  DateTime x;
11762  if( isDate(context, argc, argv, &x)==0 ){
11763    char zBuf[100];
11764    computeYMD(&x);
11765    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
11766    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11767  }
11768}
11769
11770/*
11771**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
11772**
11773** Return a string described by FORMAT.  Conversions as follows:
11774**
11775**   %d  day of month
11776**   %f  ** fractional seconds  SS.SSS
11777**   %H  hour 00-24
11778**   %j  day of year 000-366
11779**   %J  ** Julian day number
11780**   %m  month 01-12
11781**   %M  minute 00-59
11782**   %s  seconds since 1970-01-01
11783**   %S  seconds 00-59
11784**   %w  day of week 0-6  sunday==0
11785**   %W  week of year 00-53
11786**   %Y  year 0000-9999
11787**   %%  %
11788*/
11789static void strftimeFunc(
11790  sqlite3_context *context,
11791  int argc,
11792  sqlite3_value **argv
11793){
11794  DateTime x;
11795  u64 n;
11796  size_t i,j;
11797  char *z;
11798  sqlite3 *db;
11799  const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
11800  char zBuf[100];
11801  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
11802  db = sqlite3_context_db_handle(context);
11803  for(i=0, n=1; zFmt[i]; i++, n++){
11804    if( zFmt[i]=='%' ){
11805      switch( zFmt[i+1] ){
11806        case 'd':
11807        case 'H':
11808        case 'm':
11809        case 'M':
11810        case 'S':
11811        case 'W':
11812          n++;
11813          /* fall thru */
11814        case 'w':
11815        case '%':
11816          break;
11817        case 'f':
11818          n += 8;
11819          break;
11820        case 'j':
11821          n += 3;
11822          break;
11823        case 'Y':
11824          n += 8;
11825          break;
11826        case 's':
11827        case 'J':
11828          n += 50;
11829          break;
11830        default:
11831          return;  /* ERROR.  return a NULL */
11832      }
11833      i++;
11834    }
11835  }
11836  testcase( n==sizeof(zBuf)-1 );
11837  testcase( n==sizeof(zBuf) );
11838  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
11839  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
11840  if( n<sizeof(zBuf) ){
11841    z = zBuf;
11842  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
11843    sqlite3_result_error_toobig(context);
11844    return;
11845  }else{
11846    z = sqlite3DbMallocRaw(db, (int)n);
11847    if( z==0 ){
11848      sqlite3_result_error_nomem(context);
11849      return;
11850    }
11851  }
11852  computeJD(&x);
11853  computeYMD_HMS(&x);
11854  for(i=j=0; zFmt[i]; i++){
11855    if( zFmt[i]!='%' ){
11856      z[j++] = zFmt[i];
11857    }else{
11858      i++;
11859      switch( zFmt[i] ){
11860        case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
11861        case 'f': {
11862          double s = x.s;
11863          if( s>59.999 ) s = 59.999;
11864          sqlite3_snprintf(7, &z[j],"%06.3f", s);
11865          j += sqlite3Strlen30(&z[j]);
11866          break;
11867        }
11868        case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
11869        case 'W': /* Fall thru */
11870        case 'j': {
11871          int nDay;             /* Number of days since 1st day of year */
11872          DateTime y = x;
11873          y.validJD = 0;
11874          y.M = 1;
11875          y.D = 1;
11876          computeJD(&y);
11877          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
11878          if( zFmt[i]=='W' ){
11879            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
11880            wd = (int)(((x.iJD+43200000)/86400000)%7);
11881            sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
11882            j += 2;
11883          }else{
11884            sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
11885            j += 3;
11886          }
11887          break;
11888        }
11889        case 'J': {
11890          sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
11891          j+=sqlite3Strlen30(&z[j]);
11892          break;
11893        }
11894        case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
11895        case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
11896        case 's': {
11897          sqlite3_snprintf(30,&z[j],"%lld",
11898                           (i64)(x.iJD/1000 - 21086676*(i64)10000));
11899          j += sqlite3Strlen30(&z[j]);
11900          break;
11901        }
11902        case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
11903        case 'w': {
11904          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
11905          break;
11906        }
11907        case 'Y': {
11908          sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
11909          break;
11910        }
11911        default:   z[j++] = '%'; break;
11912      }
11913    }
11914  }
11915  z[j] = 0;
11916  sqlite3_result_text(context, z, -1,
11917                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
11918}
11919
11920/*
11921** current_time()
11922**
11923** This function returns the same value as time('now').
11924*/
11925static void ctimeFunc(
11926  sqlite3_context *context,
11927  int NotUsed,
11928  sqlite3_value **NotUsed2
11929){
11930  UNUSED_PARAMETER2(NotUsed, NotUsed2);
11931  timeFunc(context, 0, 0);
11932}
11933
11934/*
11935** current_date()
11936**
11937** This function returns the same value as date('now').
11938*/
11939static void cdateFunc(
11940  sqlite3_context *context,
11941  int NotUsed,
11942  sqlite3_value **NotUsed2
11943){
11944  UNUSED_PARAMETER2(NotUsed, NotUsed2);
11945  dateFunc(context, 0, 0);
11946}
11947
11948/*
11949** current_timestamp()
11950**
11951** This function returns the same value as datetime('now').
11952*/
11953static void ctimestampFunc(
11954  sqlite3_context *context,
11955  int NotUsed,
11956  sqlite3_value **NotUsed2
11957){
11958  UNUSED_PARAMETER2(NotUsed, NotUsed2);
11959  datetimeFunc(context, 0, 0);
11960}
11961#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
11962
11963#ifdef SQLITE_OMIT_DATETIME_FUNCS
11964/*
11965** If the library is compiled to omit the full-scale date and time
11966** handling (to get a smaller binary), the following minimal version
11967** of the functions current_time(), current_date() and current_timestamp()
11968** are included instead. This is to support column declarations that
11969** include "DEFAULT CURRENT_TIME" etc.
11970**
11971** This function uses the C-library functions time(), gmtime()
11972** and strftime(). The format string to pass to strftime() is supplied
11973** as the user-data for the function.
11974*/
11975static void currentTimeFunc(
11976  sqlite3_context *context,
11977  int argc,
11978  sqlite3_value **argv
11979){
11980  time_t t;
11981  char *zFormat = (char *)sqlite3_user_data(context);
11982  sqlite3 *db;
11983  double rT;
11984  char zBuf[20];
11985
11986  UNUSED_PARAMETER(argc);
11987  UNUSED_PARAMETER(argv);
11988
11989  db = sqlite3_context_db_handle(context);
11990  sqlite3OsCurrentTime(db->pVfs, &rT);
11991#ifndef SQLITE_OMIT_FLOATING_POINT
11992  t = 86400.0*(rT - 2440587.5) + 0.5;
11993#else
11994  /* without floating point support, rT will have
11995  ** already lost fractional day precision.
11996  */
11997  t = 86400 * (rT - 2440587) - 43200;
11998#endif
11999#ifdef HAVE_GMTIME_R
12000  {
12001    struct tm sNow;
12002    gmtime_r(&t, &sNow);
12003    strftime(zBuf, 20, zFormat, &sNow);
12004  }
12005#else
12006  {
12007    struct tm *pTm;
12008    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12009    pTm = gmtime(&t);
12010    strftime(zBuf, 20, zFormat, pTm);
12011    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12012  }
12013#endif
12014
12015  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12016}
12017#endif
12018
12019/*
12020** This function registered all of the above C functions as SQL
12021** functions.  This should be the only routine in this file with
12022** external linkage.
12023*/
12024SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
12025  static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
12026#ifndef SQLITE_OMIT_DATETIME_FUNCS
12027    FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
12028    FUNCTION(date,             -1, 0, 0, dateFunc      ),
12029    FUNCTION(time,             -1, 0, 0, timeFunc      ),
12030    FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
12031    FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
12032    FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
12033    FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
12034    FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
12035#else
12036    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
12037    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d",          0, currentTimeFunc),
12038    STR_FUNCTION(current_date,      0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
12039#endif
12040  };
12041  int i;
12042  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
12043  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
12044
12045  for(i=0; i<ArraySize(aDateTimeFuncs); i++){
12046    sqlite3FuncDefInsert(pHash, &aFunc[i]);
12047  }
12048}
12049
12050/************** End of date.c ************************************************/
12051/************** Begin file os.c **********************************************/
12052/*
12053** 2005 November 29
12054**
12055** The author disclaims copyright to this source code.  In place of
12056** a legal notice, here is a blessing:
12057**
12058**    May you do good and not evil.
12059**    May you find forgiveness for yourself and forgive others.
12060**    May you share freely, never taking more than you give.
12061**
12062******************************************************************************
12063**
12064** This file contains OS interface code that is common to all
12065** architectures.
12066*/
12067#define _SQLITE_OS_C_ 1
12068#undef _SQLITE_OS_C_
12069
12070/*
12071** The default SQLite sqlite3_vfs implementations do not allocate
12072** memory (actually, os_unix.c allocates a small amount of memory
12073** from within OsOpen()), but some third-party implementations may.
12074** So we test the effects of a malloc() failing and the sqlite3OsXXX()
12075** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
12076**
12077** The following functions are instrumented for malloc() failure
12078** testing:
12079**
12080**     sqlite3OsOpen()
12081**     sqlite3OsRead()
12082**     sqlite3OsWrite()
12083**     sqlite3OsSync()
12084**     sqlite3OsLock()
12085**
12086*/
12087#if defined(SQLITE_TEST) && (SQLITE_OS_WIN==0)
12088  #define DO_OS_MALLOC_TEST(x) if (!x || !sqlite3IsMemJournal(x)) {     \
12089    void *pTstAlloc = sqlite3Malloc(10);                             \
12090    if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
12091    sqlite3_free(pTstAlloc);                                         \
12092  }
12093#else
12094  #define DO_OS_MALLOC_TEST(x)
12095#endif
12096
12097/*
12098** The following routines are convenience wrappers around methods
12099** of the sqlite3_file object.  This is mostly just syntactic sugar. All
12100** of this would be completely automatic if SQLite were coded using
12101** C++ instead of plain old C.
12102*/
12103SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
12104  int rc = SQLITE_OK;
12105  if( pId->pMethods ){
12106    rc = pId->pMethods->xClose(pId);
12107    pId->pMethods = 0;
12108  }
12109  return rc;
12110}
12111SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
12112  DO_OS_MALLOC_TEST(id);
12113  return id->pMethods->xRead(id, pBuf, amt, offset);
12114}
12115SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
12116  DO_OS_MALLOC_TEST(id);
12117  return id->pMethods->xWrite(id, pBuf, amt, offset);
12118}
12119SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
12120  return id->pMethods->xTruncate(id, size);
12121}
12122SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
12123  DO_OS_MALLOC_TEST(id);
12124  return id->pMethods->xSync(id, flags);
12125}
12126SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
12127  DO_OS_MALLOC_TEST(id);
12128  return id->pMethods->xFileSize(id, pSize);
12129}
12130SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
12131  DO_OS_MALLOC_TEST(id);
12132  return id->pMethods->xLock(id, lockType);
12133}
12134SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
12135  return id->pMethods->xUnlock(id, lockType);
12136}
12137SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
12138  DO_OS_MALLOC_TEST(id);
12139  return id->pMethods->xCheckReservedLock(id, pResOut);
12140}
12141SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
12142  return id->pMethods->xFileControl(id, op, pArg);
12143}
12144SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
12145  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
12146  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
12147}
12148SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
12149  return id->pMethods->xDeviceCharacteristics(id);
12150}
12151
12152/*
12153** The next group of routines are convenience wrappers around the
12154** VFS methods.
12155*/
12156SQLITE_PRIVATE int sqlite3OsOpen(
12157  sqlite3_vfs *pVfs,
12158  const char *zPath,
12159  sqlite3_file *pFile,
12160  int flags,
12161  int *pFlagsOut
12162){
12163  int rc;
12164  DO_OS_MALLOC_TEST(0);
12165  /* 0x7f1f is a mask of SQLITE_OPEN_ flags that are valid to be passed
12166  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
12167  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
12168  ** reaching the VFS. */
12169  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x7f1f, pFlagsOut);
12170  assert( rc==SQLITE_OK || pFile->pMethods==0 );
12171  return rc;
12172}
12173SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
12174  return pVfs->xDelete(pVfs, zPath, dirSync);
12175}
12176SQLITE_PRIVATE int sqlite3OsAccess(
12177  sqlite3_vfs *pVfs,
12178  const char *zPath,
12179  int flags,
12180  int *pResOut
12181){
12182  DO_OS_MALLOC_TEST(0);
12183  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
12184}
12185SQLITE_PRIVATE int sqlite3OsFullPathname(
12186  sqlite3_vfs *pVfs,
12187  const char *zPath,
12188  int nPathOut,
12189  char *zPathOut
12190){
12191  zPathOut[0] = 0;
12192  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
12193}
12194#ifndef SQLITE_OMIT_LOAD_EXTENSION
12195SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
12196  return pVfs->xDlOpen(pVfs, zPath);
12197}
12198SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12199  pVfs->xDlError(pVfs, nByte, zBufOut);
12200}
12201SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
12202  return pVfs->xDlSym(pVfs, pHdle, zSym);
12203}
12204SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
12205  pVfs->xDlClose(pVfs, pHandle);
12206}
12207#endif /* SQLITE_OMIT_LOAD_EXTENSION */
12208SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12209  return pVfs->xRandomness(pVfs, nByte, zBufOut);
12210}
12211SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
12212  return pVfs->xSleep(pVfs, nMicro);
12213}
12214SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
12215  return pVfs->xCurrentTime(pVfs, pTimeOut);
12216}
12217
12218SQLITE_PRIVATE int sqlite3OsOpenMalloc(
12219  sqlite3_vfs *pVfs,
12220  const char *zFile,
12221  sqlite3_file **ppFile,
12222  int flags,
12223  int *pOutFlags
12224){
12225  int rc = SQLITE_NOMEM;
12226  sqlite3_file *pFile;
12227  pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
12228  if( pFile ){
12229    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
12230    if( rc!=SQLITE_OK ){
12231      sqlite3_free(pFile);
12232    }else{
12233      *ppFile = pFile;
12234    }
12235  }
12236  return rc;
12237}
12238SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
12239  int rc = SQLITE_OK;
12240  assert( pFile );
12241  rc = sqlite3OsClose(pFile);
12242  sqlite3_free(pFile);
12243  return rc;
12244}
12245
12246/*
12247** This function is a wrapper around the OS specific implementation of
12248** sqlite3_os_init(). The purpose of the wrapper is to provide the
12249** ability to simulate a malloc failure, so that the handling of an
12250** error in sqlite3_os_init() by the upper layers can be tested.
12251*/
12252SQLITE_PRIVATE int sqlite3OsInit(void){
12253  void *p = sqlite3_malloc(10);
12254  if( p==0 ) return SQLITE_NOMEM;
12255  sqlite3_free(p);
12256  return sqlite3_os_init();
12257}
12258
12259/*
12260** The list of all registered VFS implementations.
12261*/
12262static sqlite3_vfs * SQLITE_WSD vfsList = 0;
12263#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
12264
12265/*
12266** Locate a VFS by name.  If no name is given, simply return the
12267** first VFS on the list.
12268*/
12269SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
12270  sqlite3_vfs *pVfs = 0;
12271#if SQLITE_THREADSAFE
12272  sqlite3_mutex *mutex;
12273#endif
12274#ifndef SQLITE_OMIT_AUTOINIT
12275  int rc = sqlite3_initialize();
12276  if( rc ) return 0;
12277#endif
12278#if SQLITE_THREADSAFE
12279  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12280#endif
12281  sqlite3_mutex_enter(mutex);
12282  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
12283    if( zVfs==0 ) break;
12284    if( strcmp(zVfs, pVfs->zName)==0 ) break;
12285  }
12286  sqlite3_mutex_leave(mutex);
12287  return pVfs;
12288}
12289
12290/*
12291** Unlink a VFS from the linked list
12292*/
12293static void vfsUnlink(sqlite3_vfs *pVfs){
12294  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
12295  if( pVfs==0 ){
12296    /* No-op */
12297  }else if( vfsList==pVfs ){
12298    vfsList = pVfs->pNext;
12299  }else if( vfsList ){
12300    sqlite3_vfs *p = vfsList;
12301    while( p->pNext && p->pNext!=pVfs ){
12302      p = p->pNext;
12303    }
12304    if( p->pNext==pVfs ){
12305      p->pNext = pVfs->pNext;
12306    }
12307  }
12308}
12309
12310/*
12311** Register a VFS with the system.  It is harmless to register the same
12312** VFS multiple times.  The new VFS becomes the default if makeDflt is
12313** true.
12314*/
12315SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
12316  sqlite3_mutex *mutex = 0;
12317#ifndef SQLITE_OMIT_AUTOINIT
12318  int rc = sqlite3_initialize();
12319  if( rc ) return rc;
12320#endif
12321  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12322  sqlite3_mutex_enter(mutex);
12323  vfsUnlink(pVfs);
12324  if( makeDflt || vfsList==0 ){
12325    pVfs->pNext = vfsList;
12326    vfsList = pVfs;
12327  }else{
12328    pVfs->pNext = vfsList->pNext;
12329    vfsList->pNext = pVfs;
12330  }
12331  assert(vfsList);
12332  sqlite3_mutex_leave(mutex);
12333  return SQLITE_OK;
12334}
12335
12336/*
12337** Unregister a VFS so that it is no longer accessible.
12338*/
12339SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
12340#if SQLITE_THREADSAFE
12341  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12342#endif
12343  sqlite3_mutex_enter(mutex);
12344  vfsUnlink(pVfs);
12345  sqlite3_mutex_leave(mutex);
12346  return SQLITE_OK;
12347}
12348
12349/************** End of os.c **************************************************/
12350/************** Begin file fault.c *******************************************/
12351/*
12352** 2008 Jan 22
12353**
12354** The author disclaims copyright to this source code.  In place of
12355** a legal notice, here is a blessing:
12356**
12357**    May you do good and not evil.
12358**    May you find forgiveness for yourself and forgive others.
12359**    May you share freely, never taking more than you give.
12360**
12361*************************************************************************
12362**
12363** This file contains code to support the concept of "benign"
12364** malloc failures (when the xMalloc() or xRealloc() method of the
12365** sqlite3_mem_methods structure fails to allocate a block of memory
12366** and returns 0).
12367**
12368** Most malloc failures are non-benign. After they occur, SQLite
12369** abandons the current operation and returns an error code (usually
12370** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
12371** fatal. For example, if a malloc fails while resizing a hash table, this
12372** is completely recoverable simply by not carrying out the resize. The
12373** hash table will continue to function normally.  So a malloc failure
12374** during a hash table resize is a benign fault.
12375*/
12376
12377
12378#ifndef SQLITE_OMIT_BUILTIN_TEST
12379
12380/*
12381** Global variables.
12382*/
12383typedef struct BenignMallocHooks BenignMallocHooks;
12384static SQLITE_WSD struct BenignMallocHooks {
12385  void (*xBenignBegin)(void);
12386  void (*xBenignEnd)(void);
12387} sqlite3Hooks = { 0, 0 };
12388
12389/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
12390** structure.  If writable static data is unsupported on the target,
12391** we have to locate the state vector at run-time.  In the more common
12392** case where writable static data is supported, wsdHooks can refer directly
12393** to the "sqlite3Hooks" state vector declared above.
12394*/
12395#ifdef SQLITE_OMIT_WSD
12396# define wsdHooksInit \
12397  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
12398# define wsdHooks x[0]
12399#else
12400# define wsdHooksInit
12401# define wsdHooks sqlite3Hooks
12402#endif
12403
12404
12405/*
12406** Register hooks to call when sqlite3BeginBenignMalloc() and
12407** sqlite3EndBenignMalloc() are called, respectively.
12408*/
12409SQLITE_PRIVATE void sqlite3BenignMallocHooks(
12410  void (*xBenignBegin)(void),
12411  void (*xBenignEnd)(void)
12412){
12413  wsdHooksInit;
12414  wsdHooks.xBenignBegin = xBenignBegin;
12415  wsdHooks.xBenignEnd = xBenignEnd;
12416}
12417
12418/*
12419** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
12420** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
12421** indicates that subsequent malloc failures are non-benign.
12422*/
12423SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
12424  wsdHooksInit;
12425  if( wsdHooks.xBenignBegin ){
12426    wsdHooks.xBenignBegin();
12427  }
12428}
12429SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
12430  wsdHooksInit;
12431  if( wsdHooks.xBenignEnd ){
12432    wsdHooks.xBenignEnd();
12433  }
12434}
12435
12436#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
12437
12438/************** End of fault.c ***********************************************/
12439/************** Begin file mem0.c ********************************************/
12440/*
12441** 2008 October 28
12442**
12443** The author disclaims copyright to this source code.  In place of
12444** a legal notice, here is a blessing:
12445**
12446**    May you do good and not evil.
12447**    May you find forgiveness for yourself and forgive others.
12448**    May you share freely, never taking more than you give.
12449**
12450*************************************************************************
12451**
12452** This file contains a no-op memory allocation drivers for use when
12453** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
12454** here always fail.  SQLite will not operate with these drivers.  These
12455** are merely placeholders.  Real drivers must be substituted using
12456** sqlite3_config() before SQLite will operate.
12457*/
12458
12459/*
12460** This version of the memory allocator is the default.  It is
12461** used when no other memory allocator is specified using compile-time
12462** macros.
12463*/
12464#ifdef SQLITE_ZERO_MALLOC
12465
12466/*
12467** No-op versions of all memory allocation routines
12468*/
12469static void *sqlite3MemMalloc(int nByte){ return 0; }
12470static void sqlite3MemFree(void *pPrior){ return; }
12471static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
12472static int sqlite3MemSize(void *pPrior){ return 0; }
12473static int sqlite3MemRoundup(int n){ return n; }
12474static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
12475static void sqlite3MemShutdown(void *NotUsed){ return; }
12476
12477/*
12478** This routine is the only routine in this file with external linkage.
12479**
12480** Populate the low-level memory allocation function pointers in
12481** sqlite3GlobalConfig.m with pointers to the routines in this file.
12482*/
12483SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12484  static const sqlite3_mem_methods defaultMethods = {
12485     sqlite3MemMalloc,
12486     sqlite3MemFree,
12487     sqlite3MemRealloc,
12488     sqlite3MemSize,
12489     sqlite3MemRoundup,
12490     sqlite3MemInit,
12491     sqlite3MemShutdown,
12492     0
12493  };
12494  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
12495}
12496
12497#endif /* SQLITE_ZERO_MALLOC */
12498
12499/************** End of mem0.c ************************************************/
12500/************** Begin file mem1.c ********************************************/
12501/*
12502** 2007 August 14
12503**
12504** The author disclaims copyright to this source code.  In place of
12505** a legal notice, here is a blessing:
12506**
12507**    May you do good and not evil.
12508**    May you find forgiveness for yourself and forgive others.
12509**    May you share freely, never taking more than you give.
12510**
12511*************************************************************************
12512**
12513** This file contains low-level memory allocation drivers for when
12514** SQLite will use the standard C-library malloc/realloc/free interface
12515** to obtain the memory it needs.
12516**
12517** This file contains implementations of the low-level memory allocation
12518** routines specified in the sqlite3_mem_methods object.
12519*/
12520
12521/*
12522** This version of the memory allocator is the default.  It is
12523** used when no other memory allocator is specified using compile-time
12524** macros.
12525*/
12526#ifdef SQLITE_SYSTEM_MALLOC
12527
12528/*
12529** Like malloc(), but remember the size of the allocation
12530** so that we can find it later using sqlite3MemSize().
12531**
12532** For this low-level routine, we are guaranteed that nByte>0 because
12533** cases of nByte<=0 will be intercepted and dealt with by higher level
12534** routines.
12535*/
12536static void *sqlite3MemMalloc(int nByte){
12537  sqlite3_int64 *p;
12538  assert( nByte>0 );
12539  nByte = ROUND8(nByte);
12540  p = malloc( nByte+8 );
12541  if( p ){
12542    p[0] = nByte;
12543    p++;
12544  }else{
12545    testcase( sqlite3GlobalConfig.xLog!=0 );
12546    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
12547  }
12548  return (void *)p;
12549}
12550
12551/*
12552** Like free() but works for allocations obtained from sqlite3MemMalloc()
12553** or sqlite3MemRealloc().
12554**
12555** For this low-level routine, we already know that pPrior!=0 since
12556** cases where pPrior==0 will have been intecepted and dealt with
12557** by higher-level routines.
12558*/
12559static void sqlite3MemFree(void *pPrior){
12560  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
12561  assert( pPrior!=0 );
12562  p--;
12563  free(p);
12564}
12565
12566/*
12567** Report the allocated size of a prior return from xMalloc()
12568** or xRealloc().
12569*/
12570static int sqlite3MemSize(void *pPrior){
12571  sqlite3_int64 *p;
12572  if( pPrior==0 ) return 0;
12573  p = (sqlite3_int64*)pPrior;
12574  p--;
12575  return (int)p[0];
12576}
12577
12578/*
12579** Like realloc().  Resize an allocation previously obtained from
12580** sqlite3MemMalloc().
12581**
12582** For this low-level interface, we know that pPrior!=0.  Cases where
12583** pPrior==0 while have been intercepted by higher-level routine and
12584** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
12585** cases where nByte<=0 will have been intercepted by higher-level
12586** routines and redirected to xFree.
12587*/
12588static void *sqlite3MemRealloc(void *pPrior, int nByte){
12589  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
12590  assert( pPrior!=0 && nByte>0 );
12591  nByte = ROUND8(nByte);
12592  p = (sqlite3_int64*)pPrior;
12593  p--;
12594  p = realloc(p, nByte+8 );
12595  if( p ){
12596    p[0] = nByte;
12597    p++;
12598  }else{
12599    testcase( sqlite3GlobalConfig.xLog!=0 );
12600    sqlite3_log(SQLITE_NOMEM,
12601      "failed memory resize %u to %u bytes",
12602      sqlite3MemSize(pPrior), nByte);
12603  }
12604  return (void*)p;
12605}
12606
12607/*
12608** Round up a request size to the next valid allocation size.
12609*/
12610static int sqlite3MemRoundup(int n){
12611  return ROUND8(n);
12612}
12613
12614/*
12615** Initialize this module.
12616*/
12617static int sqlite3MemInit(void *NotUsed){
12618  UNUSED_PARAMETER(NotUsed);
12619  return SQLITE_OK;
12620}
12621
12622/*
12623** Deinitialize this module.
12624*/
12625static void sqlite3MemShutdown(void *NotUsed){
12626  UNUSED_PARAMETER(NotUsed);
12627  return;
12628}
12629
12630/*
12631** This routine is the only routine in this file with external linkage.
12632**
12633** Populate the low-level memory allocation function pointers in
12634** sqlite3GlobalConfig.m with pointers to the routines in this file.
12635*/
12636SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12637  static const sqlite3_mem_methods defaultMethods = {
12638     sqlite3MemMalloc,
12639     sqlite3MemFree,
12640     sqlite3MemRealloc,
12641     sqlite3MemSize,
12642     sqlite3MemRoundup,
12643     sqlite3MemInit,
12644     sqlite3MemShutdown,
12645     0
12646  };
12647  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
12648}
12649
12650#endif /* SQLITE_SYSTEM_MALLOC */
12651
12652/************** End of mem1.c ************************************************/
12653/************** Begin file mem2.c ********************************************/
12654/*
12655** 2007 August 15
12656**
12657** The author disclaims copyright to this source code.  In place of
12658** a legal notice, here is a blessing:
12659**
12660**    May you do good and not evil.
12661**    May you find forgiveness for yourself and forgive others.
12662**    May you share freely, never taking more than you give.
12663**
12664*************************************************************************
12665**
12666** This file contains low-level memory allocation drivers for when
12667** SQLite will use the standard C-library malloc/realloc/free interface
12668** to obtain the memory it needs while adding lots of additional debugging
12669** information to each allocation in order to help detect and fix memory
12670** leaks and memory usage errors.
12671**
12672** This file contains implementations of the low-level memory allocation
12673** routines specified in the sqlite3_mem_methods object.
12674*/
12675
12676/*
12677** This version of the memory allocator is used only if the
12678** SQLITE_MEMDEBUG macro is defined
12679*/
12680#ifdef SQLITE_MEMDEBUG
12681
12682/*
12683** The backtrace functionality is only available with GLIBC
12684*/
12685#ifdef __GLIBC__
12686  extern int backtrace(void**,int);
12687  extern void backtrace_symbols_fd(void*const*,int,int);
12688#else
12689# define backtrace(A,B) 1
12690# define backtrace_symbols_fd(A,B,C)
12691#endif
12692
12693/*
12694** Each memory allocation looks like this:
12695**
12696**  ------------------------------------------------------------------------
12697**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
12698**  ------------------------------------------------------------------------
12699**
12700** The application code sees only a pointer to the allocation.  We have
12701** to back up from the allocation pointer to find the MemBlockHdr.  The
12702** MemBlockHdr tells us the size of the allocation and the number of
12703** backtrace pointers.  There is also a guard word at the end of the
12704** MemBlockHdr.
12705*/
12706struct MemBlockHdr {
12707  i64 iSize;                          /* Size of this allocation */
12708  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
12709  char nBacktrace;                    /* Number of backtraces on this alloc */
12710  char nBacktraceSlots;               /* Available backtrace slots */
12711  short nTitle;                       /* Bytes of title; includes '\0' */
12712  int iForeGuard;                     /* Guard word for sanity */
12713};
12714
12715/*
12716** Guard words
12717*/
12718#define FOREGUARD 0x80F5E153
12719#define REARGUARD 0xE4676B53
12720
12721/*
12722** Number of malloc size increments to track.
12723*/
12724#define NCSIZE  1000
12725
12726/*
12727** All of the static variables used by this module are collected
12728** into a single structure named "mem".  This is to keep the
12729** static variables organized and to reduce namespace pollution
12730** when this module is combined with other in the amalgamation.
12731*/
12732static struct {
12733
12734  /*
12735  ** Mutex to control access to the memory allocation subsystem.
12736  */
12737  sqlite3_mutex *mutex;
12738
12739  /*
12740  ** Head and tail of a linked list of all outstanding allocations
12741  */
12742  struct MemBlockHdr *pFirst;
12743  struct MemBlockHdr *pLast;
12744
12745  /*
12746  ** The number of levels of backtrace to save in new allocations.
12747  */
12748  int nBacktrace;
12749  void (*xBacktrace)(int, int, void **);
12750
12751  /*
12752  ** Title text to insert in front of each block
12753  */
12754  int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
12755  char zTitle[100];  /* The title text */
12756
12757  /*
12758  ** sqlite3MallocDisallow() increments the following counter.
12759  ** sqlite3MallocAllow() decrements it.
12760  */
12761  int disallow; /* Do not allow memory allocation */
12762
12763  /*
12764  ** Gather statistics on the sizes of memory allocations.
12765  ** nAlloc[i] is the number of allocation attempts of i*8
12766  ** bytes.  i==NCSIZE is the number of allocation attempts for
12767  ** sizes more than NCSIZE*8 bytes.
12768  */
12769  int nAlloc[NCSIZE];      /* Total number of allocations */
12770  int nCurrent[NCSIZE];    /* Current number of allocations */
12771  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
12772
12773} mem;
12774
12775
12776/*
12777** Adjust memory usage statistics
12778*/
12779static void adjustStats(int iSize, int increment){
12780  int i = ROUND8(iSize)/8;
12781  if( i>NCSIZE-1 ){
12782    i = NCSIZE - 1;
12783  }
12784  if( increment>0 ){
12785    mem.nAlloc[i]++;
12786    mem.nCurrent[i]++;
12787    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
12788      mem.mxCurrent[i] = mem.nCurrent[i];
12789    }
12790  }else{
12791    mem.nCurrent[i]--;
12792    assert( mem.nCurrent[i]>=0 );
12793  }
12794}
12795
12796/*
12797** Given an allocation, find the MemBlockHdr for that allocation.
12798**
12799** This routine checks the guards at either end of the allocation and
12800** if they are incorrect it asserts.
12801*/
12802static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
12803  struct MemBlockHdr *p;
12804  int *pInt;
12805  u8 *pU8;
12806  int nReserve;
12807
12808  p = (struct MemBlockHdr*)pAllocation;
12809  p--;
12810  assert( p->iForeGuard==(int)FOREGUARD );
12811  nReserve = ROUND8(p->iSize);
12812  pInt = (int*)pAllocation;
12813  pU8 = (u8*)pAllocation;
12814  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
12815  /* This checks any of the "extra" bytes allocated due
12816  ** to rounding up to an 8 byte boundary to ensure
12817  ** they haven't been overwritten.
12818  */
12819  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
12820  return p;
12821}
12822
12823/*
12824** Return the number of bytes currently allocated at address p.
12825*/
12826static int sqlite3MemSize(void *p){
12827  struct MemBlockHdr *pHdr;
12828  if( !p ){
12829    return 0;
12830  }
12831  pHdr = sqlite3MemsysGetHeader(p);
12832  return pHdr->iSize;
12833}
12834
12835/*
12836** Initialize the memory allocation subsystem.
12837*/
12838static int sqlite3MemInit(void *NotUsed){
12839  UNUSED_PARAMETER(NotUsed);
12840  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
12841  if( !sqlite3GlobalConfig.bMemstat ){
12842    /* If memory status is enabled, then the malloc.c wrapper will already
12843    ** hold the STATIC_MEM mutex when the routines here are invoked. */
12844    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
12845  }
12846  return SQLITE_OK;
12847}
12848
12849/*
12850** Deinitialize the memory allocation subsystem.
12851*/
12852static void sqlite3MemShutdown(void *NotUsed){
12853  UNUSED_PARAMETER(NotUsed);
12854  mem.mutex = 0;
12855}
12856
12857/*
12858** Round up a request size to the next valid allocation size.
12859*/
12860static int sqlite3MemRoundup(int n){
12861  return ROUND8(n);
12862}
12863
12864/*
12865** Fill a buffer with pseudo-random bytes.  This is used to preset
12866** the content of a new memory allocation to unpredictable values and
12867** to clear the content of a freed allocation to unpredictable values.
12868*/
12869static void randomFill(char *pBuf, int nByte){
12870  unsigned int x, y, r;
12871  x = SQLITE_PTR_TO_INT(pBuf);
12872  y = nByte | 1;
12873  while( nByte >= 4 ){
12874    x = (x>>1) ^ (-(x&1) & 0xd0000001);
12875    y = y*1103515245 + 12345;
12876    r = x ^ y;
12877    *(int*)pBuf = r;
12878    pBuf += 4;
12879    nByte -= 4;
12880  }
12881  while( nByte-- > 0 ){
12882    x = (x>>1) ^ (-(x&1) & 0xd0000001);
12883    y = y*1103515245 + 12345;
12884    r = x ^ y;
12885    *(pBuf++) = r & 0xff;
12886  }
12887}
12888
12889/*
12890** Allocate nByte bytes of memory.
12891*/
12892static void *sqlite3MemMalloc(int nByte){
12893  struct MemBlockHdr *pHdr;
12894  void **pBt;
12895  char *z;
12896  int *pInt;
12897  void *p = 0;
12898  int totalSize;
12899  int nReserve;
12900  sqlite3_mutex_enter(mem.mutex);
12901  assert( mem.disallow==0 );
12902  nReserve = ROUND8(nByte);
12903  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
12904               mem.nBacktrace*sizeof(void*) + mem.nTitle;
12905  p = malloc(totalSize);
12906  if( p ){
12907    z = p;
12908    pBt = (void**)&z[mem.nTitle];
12909    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
12910    pHdr->pNext = 0;
12911    pHdr->pPrev = mem.pLast;
12912    if( mem.pLast ){
12913      mem.pLast->pNext = pHdr;
12914    }else{
12915      mem.pFirst = pHdr;
12916    }
12917    mem.pLast = pHdr;
12918    pHdr->iForeGuard = FOREGUARD;
12919    pHdr->nBacktraceSlots = mem.nBacktrace;
12920    pHdr->nTitle = mem.nTitle;
12921    if( mem.nBacktrace ){
12922      void *aAddr[40];
12923      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
12924      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
12925      assert(pBt[0]);
12926      if( mem.xBacktrace ){
12927        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
12928      }
12929    }else{
12930      pHdr->nBacktrace = 0;
12931    }
12932    if( mem.nTitle ){
12933      memcpy(z, mem.zTitle, mem.nTitle);
12934    }
12935    pHdr->iSize = nByte;
12936    adjustStats(nByte, +1);
12937    pInt = (int*)&pHdr[1];
12938    pInt[nReserve/sizeof(int)] = REARGUARD;
12939    randomFill((char*)pInt, nByte);
12940    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
12941    p = (void*)pInt;
12942  }
12943  sqlite3_mutex_leave(mem.mutex);
12944  return p;
12945}
12946
12947/*
12948** Free memory.
12949*/
12950static void sqlite3MemFree(void *pPrior){
12951  struct MemBlockHdr *pHdr;
12952  void **pBt;
12953  char *z;
12954  assert( sqlite3GlobalConfig.bMemstat || mem.mutex!=0 );
12955  pHdr = sqlite3MemsysGetHeader(pPrior);
12956  pBt = (void**)pHdr;
12957  pBt -= pHdr->nBacktraceSlots;
12958  sqlite3_mutex_enter(mem.mutex);
12959  if( pHdr->pPrev ){
12960    assert( pHdr->pPrev->pNext==pHdr );
12961    pHdr->pPrev->pNext = pHdr->pNext;
12962  }else{
12963    assert( mem.pFirst==pHdr );
12964    mem.pFirst = pHdr->pNext;
12965  }
12966  if( pHdr->pNext ){
12967    assert( pHdr->pNext->pPrev==pHdr );
12968    pHdr->pNext->pPrev = pHdr->pPrev;
12969  }else{
12970    assert( mem.pLast==pHdr );
12971    mem.pLast = pHdr->pPrev;
12972  }
12973  z = (char*)pBt;
12974  z -= pHdr->nTitle;
12975  adjustStats(pHdr->iSize, -1);
12976  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
12977                pHdr->iSize + sizeof(int) + pHdr->nTitle);
12978  free(z);
12979  sqlite3_mutex_leave(mem.mutex);
12980}
12981
12982/*
12983** Change the size of an existing memory allocation.
12984**
12985** For this debugging implementation, we *always* make a copy of the
12986** allocation into a new place in memory.  In this way, if the
12987** higher level code is using pointer to the old allocation, it is
12988** much more likely to break and we are much more liking to find
12989** the error.
12990*/
12991static void *sqlite3MemRealloc(void *pPrior, int nByte){
12992  struct MemBlockHdr *pOldHdr;
12993  void *pNew;
12994  assert( mem.disallow==0 );
12995  pOldHdr = sqlite3MemsysGetHeader(pPrior);
12996  pNew = sqlite3MemMalloc(nByte);
12997  if( pNew ){
12998    memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
12999    if( nByte>pOldHdr->iSize ){
13000      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
13001    }
13002    sqlite3MemFree(pPrior);
13003  }
13004  return pNew;
13005}
13006
13007/*
13008** Populate the low-level memory allocation function pointers in
13009** sqlite3GlobalConfig.m with pointers to the routines in this file.
13010*/
13011SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13012  static const sqlite3_mem_methods defaultMethods = {
13013     sqlite3MemMalloc,
13014     sqlite3MemFree,
13015     sqlite3MemRealloc,
13016     sqlite3MemSize,
13017     sqlite3MemRoundup,
13018     sqlite3MemInit,
13019     sqlite3MemShutdown,
13020     0
13021  };
13022  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13023}
13024
13025/*
13026** Set the number of backtrace levels kept for each allocation.
13027** A value of zero turns off backtracing.  The number is always rounded
13028** up to a multiple of 2.
13029*/
13030SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
13031  if( depth<0 ){ depth = 0; }
13032  if( depth>20 ){ depth = 20; }
13033  depth = (depth+1)&0xfe;
13034  mem.nBacktrace = depth;
13035}
13036
13037SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
13038  mem.xBacktrace = xBacktrace;
13039}
13040
13041/*
13042** Set the title string for subsequent allocations.
13043*/
13044SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
13045  unsigned int n = sqlite3Strlen30(zTitle) + 1;
13046  sqlite3_mutex_enter(mem.mutex);
13047  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
13048  memcpy(mem.zTitle, zTitle, n);
13049  mem.zTitle[n] = 0;
13050  mem.nTitle = ROUND8(n);
13051  sqlite3_mutex_leave(mem.mutex);
13052}
13053
13054SQLITE_PRIVATE void sqlite3MemdebugSync(){
13055  struct MemBlockHdr *pHdr;
13056  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13057    void **pBt = (void**)pHdr;
13058    pBt -= pHdr->nBacktraceSlots;
13059    mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
13060  }
13061}
13062
13063/*
13064** Open the file indicated and write a log of all unfreed memory
13065** allocations into that log.
13066*/
13067SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
13068  FILE *out;
13069  struct MemBlockHdr *pHdr;
13070  void **pBt;
13071  int i;
13072  out = fopen(zFilename, "w");
13073  if( out==0 ){
13074    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13075                    zFilename);
13076    return;
13077  }
13078  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13079    char *z = (char*)pHdr;
13080    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
13081    fprintf(out, "**** %lld bytes at %p from %s ****\n",
13082            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
13083    if( pHdr->nBacktrace ){
13084      fflush(out);
13085      pBt = (void**)pHdr;
13086      pBt -= pHdr->nBacktraceSlots;
13087      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
13088      fprintf(out, "\n");
13089    }
13090  }
13091  fprintf(out, "COUNTS:\n");
13092  for(i=0; i<NCSIZE-1; i++){
13093    if( mem.nAlloc[i] ){
13094      fprintf(out, "   %5d: %10d %10d %10d\n",
13095            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
13096    }
13097  }
13098  if( mem.nAlloc[NCSIZE-1] ){
13099    fprintf(out, "   %5d: %10d %10d %10d\n",
13100             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
13101             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
13102  }
13103  fclose(out);
13104}
13105
13106/*
13107** Return the number of times sqlite3MemMalloc() has been called.
13108*/
13109SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
13110  int i;
13111  int nTotal = 0;
13112  for(i=0; i<NCSIZE; i++){
13113    nTotal += mem.nAlloc[i];
13114  }
13115  return nTotal;
13116}
13117
13118
13119#endif /* SQLITE_MEMDEBUG */
13120
13121/************** End of mem2.c ************************************************/
13122/************** Begin file mem3.c ********************************************/
13123/*
13124** 2007 October 14
13125**
13126** The author disclaims copyright to this source code.  In place of
13127** a legal notice, here is a blessing:
13128**
13129**    May you do good and not evil.
13130**    May you find forgiveness for yourself and forgive others.
13131**    May you share freely, never taking more than you give.
13132**
13133*************************************************************************
13134** This file contains the C functions that implement a memory
13135** allocation subsystem for use by SQLite.
13136**
13137** This version of the memory allocation subsystem omits all
13138** use of malloc(). The SQLite user supplies a block of memory
13139** before calling sqlite3_initialize() from which allocations
13140** are made and returned by the xMalloc() and xRealloc()
13141** implementations. Once sqlite3_initialize() has been called,
13142** the amount of memory available to SQLite is fixed and cannot
13143** be changed.
13144**
13145** This version of the memory allocation subsystem is included
13146** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
13147*/
13148
13149/*
13150** This version of the memory allocator is only built into the library
13151** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
13152** mean that the library will use a memory-pool by default, just that
13153** it is available. The mempool allocator is activated by calling
13154** sqlite3_config().
13155*/
13156#ifdef SQLITE_ENABLE_MEMSYS3
13157
13158/*
13159** Maximum size (in Mem3Blocks) of a "small" chunk.
13160*/
13161#define MX_SMALL 10
13162
13163
13164/*
13165** Number of freelist hash slots
13166*/
13167#define N_HASH  61
13168
13169/*
13170** A memory allocation (also called a "chunk") consists of two or
13171** more blocks where each block is 8 bytes.  The first 8 bytes are
13172** a header that is not returned to the user.
13173**
13174** A chunk is two or more blocks that is either checked out or
13175** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
13176** size of the allocation in blocks if the allocation is free.
13177** The u.hdr.size4x&1 bit is true if the chunk is checked out and
13178** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
13179** is true if the previous chunk is checked out and false if the
13180** previous chunk is free.  The u.hdr.prevSize field is the size of
13181** the previous chunk in blocks if the previous chunk is on the
13182** freelist. If the previous chunk is checked out, then
13183** u.hdr.prevSize can be part of the data for that chunk and should
13184** not be read or written.
13185**
13186** We often identify a chunk by its index in mem3.aPool[].  When
13187** this is done, the chunk index refers to the second block of
13188** the chunk.  In this way, the first chunk has an index of 1.
13189** A chunk index of 0 means "no such chunk" and is the equivalent
13190** of a NULL pointer.
13191**
13192** The second block of free chunks is of the form u.list.  The
13193** two fields form a double-linked list of chunks of related sizes.
13194** Pointers to the head of the list are stored in mem3.aiSmall[]
13195** for smaller chunks and mem3.aiHash[] for larger chunks.
13196**
13197** The second block of a chunk is user data if the chunk is checked
13198** out.  If a chunk is checked out, the user data may extend into
13199** the u.hdr.prevSize value of the following chunk.
13200*/
13201typedef struct Mem3Block Mem3Block;
13202struct Mem3Block {
13203  union {
13204    struct {
13205      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
13206      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
13207    } hdr;
13208    struct {
13209      u32 next;       /* Index in mem3.aPool[] of next free chunk */
13210      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
13211    } list;
13212  } u;
13213};
13214
13215/*
13216** All of the static variables used by this module are collected
13217** into a single structure named "mem3".  This is to keep the
13218** static variables organized and to reduce namespace pollution
13219** when this module is combined with other in the amalgamation.
13220*/
13221static SQLITE_WSD struct Mem3Global {
13222  /*
13223  ** Memory available for allocation. nPool is the size of the array
13224  ** (in Mem3Blocks) pointed to by aPool less 2.
13225  */
13226  u32 nPool;
13227  Mem3Block *aPool;
13228
13229  /*
13230  ** True if we are evaluating an out-of-memory callback.
13231  */
13232  int alarmBusy;
13233
13234  /*
13235  ** Mutex to control access to the memory allocation subsystem.
13236  */
13237  sqlite3_mutex *mutex;
13238
13239  /*
13240  ** The minimum amount of free space that we have seen.
13241  */
13242  u32 mnMaster;
13243
13244  /*
13245  ** iMaster is the index of the master chunk.  Most new allocations
13246  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
13247  ** of the current master.  iMaster is 0 if there is not master chunk.
13248  ** The master chunk is not in either the aiHash[] or aiSmall[].
13249  */
13250  u32 iMaster;
13251  u32 szMaster;
13252
13253  /*
13254  ** Array of lists of free blocks according to the block size
13255  ** for smaller chunks, or a hash on the block size for larger
13256  ** chunks.
13257  */
13258  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
13259  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
13260} mem3 = { 97535575 };
13261
13262#define mem3 GLOBAL(struct Mem3Global, mem3)
13263
13264/*
13265** Unlink the chunk at mem3.aPool[i] from list it is currently
13266** on.  *pRoot is the list that i is a member of.
13267*/
13268static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
13269  u32 next = mem3.aPool[i].u.list.next;
13270  u32 prev = mem3.aPool[i].u.list.prev;
13271  assert( sqlite3_mutex_held(mem3.mutex) );
13272  if( prev==0 ){
13273    *pRoot = next;
13274  }else{
13275    mem3.aPool[prev].u.list.next = next;
13276  }
13277  if( next ){
13278    mem3.aPool[next].u.list.prev = prev;
13279  }
13280  mem3.aPool[i].u.list.next = 0;
13281  mem3.aPool[i].u.list.prev = 0;
13282}
13283
13284/*
13285** Unlink the chunk at index i from
13286** whatever list is currently a member of.
13287*/
13288static void memsys3Unlink(u32 i){
13289  u32 size, hash;
13290  assert( sqlite3_mutex_held(mem3.mutex) );
13291  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
13292  assert( i>=1 );
13293  size = mem3.aPool[i-1].u.hdr.size4x/4;
13294  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
13295  assert( size>=2 );
13296  if( size <= MX_SMALL ){
13297    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
13298  }else{
13299    hash = size % N_HASH;
13300    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
13301  }
13302}
13303
13304/*
13305** Link the chunk at mem3.aPool[i] so that is on the list rooted
13306** at *pRoot.
13307*/
13308static void memsys3LinkIntoList(u32 i, u32 *pRoot){
13309  assert( sqlite3_mutex_held(mem3.mutex) );
13310  mem3.aPool[i].u.list.next = *pRoot;
13311  mem3.aPool[i].u.list.prev = 0;
13312  if( *pRoot ){
13313    mem3.aPool[*pRoot].u.list.prev = i;
13314  }
13315  *pRoot = i;
13316}
13317
13318/*
13319** Link the chunk at index i into either the appropriate
13320** small chunk list, or into the large chunk hash table.
13321*/
13322static void memsys3Link(u32 i){
13323  u32 size, hash;
13324  assert( sqlite3_mutex_held(mem3.mutex) );
13325  assert( i>=1 );
13326  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
13327  size = mem3.aPool[i-1].u.hdr.size4x/4;
13328  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
13329  assert( size>=2 );
13330  if( size <= MX_SMALL ){
13331    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
13332  }else{
13333    hash = size % N_HASH;
13334    memsys3LinkIntoList(i, &mem3.aiHash[hash]);
13335  }
13336}
13337
13338/*
13339** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
13340** will already be held (obtained by code in malloc.c) if
13341** sqlite3GlobalConfig.bMemStat is true.
13342*/
13343static void memsys3Enter(void){
13344  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
13345    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
13346  }
13347  sqlite3_mutex_enter(mem3.mutex);
13348}
13349static void memsys3Leave(void){
13350  sqlite3_mutex_leave(mem3.mutex);
13351}
13352
13353/*
13354** Called when we are unable to satisfy an allocation of nBytes.
13355*/
13356static void memsys3OutOfMemory(int nByte){
13357  if( !mem3.alarmBusy ){
13358    mem3.alarmBusy = 1;
13359    assert( sqlite3_mutex_held(mem3.mutex) );
13360    sqlite3_mutex_leave(mem3.mutex);
13361    sqlite3_release_memory(nByte);
13362    sqlite3_mutex_enter(mem3.mutex);
13363    mem3.alarmBusy = 0;
13364  }
13365}
13366
13367
13368/*
13369** Chunk i is a free chunk that has been unlinked.  Adjust its
13370** size parameters for check-out and return a pointer to the
13371** user portion of the chunk.
13372*/
13373static void *memsys3Checkout(u32 i, u32 nBlock){
13374  u32 x;
13375  assert( sqlite3_mutex_held(mem3.mutex) );
13376  assert( i>=1 );
13377  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
13378  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
13379  x = mem3.aPool[i-1].u.hdr.size4x;
13380  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
13381  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
13382  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
13383  return &mem3.aPool[i];
13384}
13385
13386/*
13387** Carve a piece off of the end of the mem3.iMaster free chunk.
13388** Return a pointer to the new allocation.  Or, if the master chunk
13389** is not large enough, return 0.
13390*/
13391static void *memsys3FromMaster(u32 nBlock){
13392  assert( sqlite3_mutex_held(mem3.mutex) );
13393  assert( mem3.szMaster>=nBlock );
13394  if( nBlock>=mem3.szMaster-1 ){
13395    /* Use the entire master */
13396    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
13397    mem3.iMaster = 0;
13398    mem3.szMaster = 0;
13399    mem3.mnMaster = 0;
13400    return p;
13401  }else{
13402    /* Split the master block.  Return the tail. */
13403    u32 newi, x;
13404    newi = mem3.iMaster + mem3.szMaster - nBlock;
13405    assert( newi > mem3.iMaster+1 );
13406    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
13407    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
13408    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
13409    mem3.szMaster -= nBlock;
13410    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
13411    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13412    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13413    if( mem3.szMaster < mem3.mnMaster ){
13414      mem3.mnMaster = mem3.szMaster;
13415    }
13416    return (void*)&mem3.aPool[newi];
13417  }
13418}
13419
13420/*
13421** *pRoot is the head of a list of free chunks of the same size
13422** or same size hash.  In other words, *pRoot is an entry in either
13423** mem3.aiSmall[] or mem3.aiHash[].
13424**
13425** This routine examines all entries on the given list and tries
13426** to coalesce each entries with adjacent free chunks.
13427**
13428** If it sees a chunk that is larger than mem3.iMaster, it replaces
13429** the current mem3.iMaster with the new larger chunk.  In order for
13430** this mem3.iMaster replacement to work, the master chunk must be
13431** linked into the hash tables.  That is not the normal state of
13432** affairs, of course.  The calling routine must link the master
13433** chunk before invoking this routine, then must unlink the (possibly
13434** changed) master chunk once this routine has finished.
13435*/
13436static void memsys3Merge(u32 *pRoot){
13437  u32 iNext, prev, size, i, x;
13438
13439  assert( sqlite3_mutex_held(mem3.mutex) );
13440  for(i=*pRoot; i>0; i=iNext){
13441    iNext = mem3.aPool[i].u.list.next;
13442    size = mem3.aPool[i-1].u.hdr.size4x;
13443    assert( (size&1)==0 );
13444    if( (size&2)==0 ){
13445      memsys3UnlinkFromList(i, pRoot);
13446      assert( i > mem3.aPool[i-1].u.hdr.prevSize );
13447      prev = i - mem3.aPool[i-1].u.hdr.prevSize;
13448      if( prev==iNext ){
13449        iNext = mem3.aPool[prev].u.list.next;
13450      }
13451      memsys3Unlink(prev);
13452      size = i + size/4 - prev;
13453      x = mem3.aPool[prev-1].u.hdr.size4x & 2;
13454      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
13455      mem3.aPool[prev+size-1].u.hdr.prevSize = size;
13456      memsys3Link(prev);
13457      i = prev;
13458    }else{
13459      size /= 4;
13460    }
13461    if( size>mem3.szMaster ){
13462      mem3.iMaster = i;
13463      mem3.szMaster = size;
13464    }
13465  }
13466}
13467
13468/*
13469** Return a block of memory of at least nBytes in size.
13470** Return NULL if unable.
13471**
13472** This function assumes that the necessary mutexes, if any, are
13473** already held by the caller. Hence "Unsafe".
13474*/
13475static void *memsys3MallocUnsafe(int nByte){
13476  u32 i;
13477  u32 nBlock;
13478  u32 toFree;
13479
13480  assert( sqlite3_mutex_held(mem3.mutex) );
13481  assert( sizeof(Mem3Block)==8 );
13482  if( nByte<=12 ){
13483    nBlock = 2;
13484  }else{
13485    nBlock = (nByte + 11)/8;
13486  }
13487  assert( nBlock>=2 );
13488
13489  /* STEP 1:
13490  ** Look for an entry of the correct size in either the small
13491  ** chunk table or in the large chunk hash table.  This is
13492  ** successful most of the time (about 9 times out of 10).
13493  */
13494  if( nBlock <= MX_SMALL ){
13495    i = mem3.aiSmall[nBlock-2];
13496    if( i>0 ){
13497      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
13498      return memsys3Checkout(i, nBlock);
13499    }
13500  }else{
13501    int hash = nBlock % N_HASH;
13502    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
13503      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
13504        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
13505        return memsys3Checkout(i, nBlock);
13506      }
13507    }
13508  }
13509
13510  /* STEP 2:
13511  ** Try to satisfy the allocation by carving a piece off of the end
13512  ** of the master chunk.  This step usually works if step 1 fails.
13513  */
13514  if( mem3.szMaster>=nBlock ){
13515    return memsys3FromMaster(nBlock);
13516  }
13517
13518
13519  /* STEP 3:
13520  ** Loop through the entire memory pool.  Coalesce adjacent free
13521  ** chunks.  Recompute the master chunk as the largest free chunk.
13522  ** Then try again to satisfy the allocation by carving a piece off
13523  ** of the end of the master chunk.  This step happens very
13524  ** rarely (we hope!)
13525  */
13526  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
13527    memsys3OutOfMemory(toFree);
13528    if( mem3.iMaster ){
13529      memsys3Link(mem3.iMaster);
13530      mem3.iMaster = 0;
13531      mem3.szMaster = 0;
13532    }
13533    for(i=0; i<N_HASH; i++){
13534      memsys3Merge(&mem3.aiHash[i]);
13535    }
13536    for(i=0; i<MX_SMALL-1; i++){
13537      memsys3Merge(&mem3.aiSmall[i]);
13538    }
13539    if( mem3.szMaster ){
13540      memsys3Unlink(mem3.iMaster);
13541      if( mem3.szMaster>=nBlock ){
13542        return memsys3FromMaster(nBlock);
13543      }
13544    }
13545  }
13546
13547  /* If none of the above worked, then we fail. */
13548  return 0;
13549}
13550
13551/*
13552** Free an outstanding memory allocation.
13553**
13554** This function assumes that the necessary mutexes, if any, are
13555** already held by the caller. Hence "Unsafe".
13556*/
13557void memsys3FreeUnsafe(void *pOld){
13558  Mem3Block *p = (Mem3Block*)pOld;
13559  int i;
13560  u32 size, x;
13561  assert( sqlite3_mutex_held(mem3.mutex) );
13562  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
13563  i = p - mem3.aPool;
13564  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
13565  size = mem3.aPool[i-1].u.hdr.size4x/4;
13566  assert( i+size<=mem3.nPool+1 );
13567  mem3.aPool[i-1].u.hdr.size4x &= ~1;
13568  mem3.aPool[i+size-1].u.hdr.prevSize = size;
13569  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
13570  memsys3Link(i);
13571
13572  /* Try to expand the master using the newly freed chunk */
13573  if( mem3.iMaster ){
13574    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
13575      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
13576      mem3.iMaster -= size;
13577      mem3.szMaster += size;
13578      memsys3Unlink(mem3.iMaster);
13579      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13580      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13581      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
13582    }
13583    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13584    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
13585      memsys3Unlink(mem3.iMaster+mem3.szMaster);
13586      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
13587      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13588      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
13589    }
13590  }
13591}
13592
13593/*
13594** Return the size of an outstanding allocation, in bytes.  The
13595** size returned omits the 8-byte header overhead.  This only
13596** works for chunks that are currently checked out.
13597*/
13598static int memsys3Size(void *p){
13599  Mem3Block *pBlock;
13600  if( p==0 ) return 0;
13601  pBlock = (Mem3Block*)p;
13602  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
13603  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
13604}
13605
13606/*
13607** Round up a request size to the next valid allocation size.
13608*/
13609static int memsys3Roundup(int n){
13610  if( n<=12 ){
13611    return 12;
13612  }else{
13613    return ((n+11)&~7) - 4;
13614  }
13615}
13616
13617/*
13618** Allocate nBytes of memory.
13619*/
13620static void *memsys3Malloc(int nBytes){
13621  sqlite3_int64 *p;
13622  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
13623  memsys3Enter();
13624  p = memsys3MallocUnsafe(nBytes);
13625  memsys3Leave();
13626  return (void*)p;
13627}
13628
13629/*
13630** Free memory.
13631*/
13632void memsys3Free(void *pPrior){
13633  assert( pPrior );
13634  memsys3Enter();
13635  memsys3FreeUnsafe(pPrior);
13636  memsys3Leave();
13637}
13638
13639/*
13640** Change the size of an existing memory allocation
13641*/
13642void *memsys3Realloc(void *pPrior, int nBytes){
13643  int nOld;
13644  void *p;
13645  if( pPrior==0 ){
13646    return sqlite3_malloc(nBytes);
13647  }
13648  if( nBytes<=0 ){
13649    sqlite3_free(pPrior);
13650    return 0;
13651  }
13652  nOld = memsys3Size(pPrior);
13653  if( nBytes<=nOld && nBytes>=nOld-128 ){
13654    return pPrior;
13655  }
13656  memsys3Enter();
13657  p = memsys3MallocUnsafe(nBytes);
13658  if( p ){
13659    if( nOld<nBytes ){
13660      memcpy(p, pPrior, nOld);
13661    }else{
13662      memcpy(p, pPrior, nBytes);
13663    }
13664    memsys3FreeUnsafe(pPrior);
13665  }
13666  memsys3Leave();
13667  return p;
13668}
13669
13670/*
13671** Initialize this module.
13672*/
13673static int memsys3Init(void *NotUsed){
13674  UNUSED_PARAMETER(NotUsed);
13675  if( !sqlite3GlobalConfig.pHeap ){
13676    return SQLITE_ERROR;
13677  }
13678
13679  /* Store a pointer to the memory block in global structure mem3. */
13680  assert( sizeof(Mem3Block)==8 );
13681  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
13682  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
13683
13684  /* Initialize the master block. */
13685  mem3.szMaster = mem3.nPool;
13686  mem3.mnMaster = mem3.szMaster;
13687  mem3.iMaster = 1;
13688  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
13689  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
13690  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
13691
13692  return SQLITE_OK;
13693}
13694
13695/*
13696** Deinitialize this module.
13697*/
13698static void memsys3Shutdown(void *NotUsed){
13699  UNUSED_PARAMETER(NotUsed);
13700  mem3.mutex = 0;
13701  return;
13702}
13703
13704
13705
13706/*
13707** Open the file indicated and write a log of all unfreed memory
13708** allocations into that log.
13709*/
13710SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
13711#ifdef SQLITE_DEBUG
13712  FILE *out;
13713  u32 i, j;
13714  u32 size;
13715  if( zFilename==0 || zFilename[0]==0 ){
13716    out = stdout;
13717  }else{
13718    out = fopen(zFilename, "w");
13719    if( out==0 ){
13720      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13721                      zFilename);
13722      return;
13723    }
13724  }
13725  memsys3Enter();
13726  fprintf(out, "CHUNKS:\n");
13727  for(i=1; i<=mem3.nPool; i+=size/4){
13728    size = mem3.aPool[i-1].u.hdr.size4x;
13729    if( size/4<=1 ){
13730      fprintf(out, "%p size error\n", &mem3.aPool[i]);
13731      assert( 0 );
13732      break;
13733    }
13734    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
13735      fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
13736      assert( 0 );
13737      break;
13738    }
13739    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
13740      fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
13741      assert( 0 );
13742      break;
13743    }
13744    if( size&1 ){
13745      fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
13746    }else{
13747      fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
13748                  i==mem3.iMaster ? " **master**" : "");
13749    }
13750  }
13751  for(i=0; i<MX_SMALL-1; i++){
13752    if( mem3.aiSmall[i]==0 ) continue;
13753    fprintf(out, "small(%2d):", i);
13754    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
13755      fprintf(out, " %p(%d)", &mem3.aPool[j],
13756              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
13757    }
13758    fprintf(out, "\n");
13759  }
13760  for(i=0; i<N_HASH; i++){
13761    if( mem3.aiHash[i]==0 ) continue;
13762    fprintf(out, "hash(%2d):", i);
13763    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
13764      fprintf(out, " %p(%d)", &mem3.aPool[j],
13765              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
13766    }
13767    fprintf(out, "\n");
13768  }
13769  fprintf(out, "master=%d\n", mem3.iMaster);
13770  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
13771  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
13772  sqlite3_mutex_leave(mem3.mutex);
13773  if( out==stdout ){
13774    fflush(stdout);
13775  }else{
13776    fclose(out);
13777  }
13778#else
13779  UNUSED_PARAMETER(zFilename);
13780#endif
13781}
13782
13783/*
13784** This routine is the only routine in this file with external
13785** linkage.
13786**
13787** Populate the low-level memory allocation function pointers in
13788** sqlite3GlobalConfig.m with pointers to the routines in this file. The
13789** arguments specify the block of memory to manage.
13790**
13791** This routine is only called by sqlite3_config(), and therefore
13792** is not required to be threadsafe (it is not).
13793*/
13794SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
13795  static const sqlite3_mem_methods mempoolMethods = {
13796     memsys3Malloc,
13797     memsys3Free,
13798     memsys3Realloc,
13799     memsys3Size,
13800     memsys3Roundup,
13801     memsys3Init,
13802     memsys3Shutdown,
13803     0
13804  };
13805  return &mempoolMethods;
13806}
13807
13808#endif /* SQLITE_ENABLE_MEMSYS3 */
13809
13810/************** End of mem3.c ************************************************/
13811/************** Begin file mem5.c ********************************************/
13812/*
13813** 2007 October 14
13814**
13815** The author disclaims copyright to this source code.  In place of
13816** a legal notice, here is a blessing:
13817**
13818**    May you do good and not evil.
13819**    May you find forgiveness for yourself and forgive others.
13820**    May you share freely, never taking more than you give.
13821**
13822*************************************************************************
13823** This file contains the C functions that implement a memory
13824** allocation subsystem for use by SQLite.
13825**
13826** This version of the memory allocation subsystem omits all
13827** use of malloc(). The application gives SQLite a block of memory
13828** before calling sqlite3_initialize() from which allocations
13829** are made and returned by the xMalloc() and xRealloc()
13830** implementations. Once sqlite3_initialize() has been called,
13831** the amount of memory available to SQLite is fixed and cannot
13832** be changed.
13833**
13834** This version of the memory allocation subsystem is included
13835** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
13836**
13837** This memory allocator uses the following algorithm:
13838**
13839**   1.  All memory allocations sizes are rounded up to a power of 2.
13840**
13841**   2.  If two adjacent free blocks are the halves of a larger block,
13842**       then the two blocks are coalesed into the single larger block.
13843**
13844**   3.  New memory is allocated from the first available free block.
13845**
13846** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
13847** Concerning Dynamic Storage Allocation". Journal of the Association for
13848** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
13849**
13850** Let n be the size of the largest allocation divided by the minimum
13851** allocation size (after rounding all sizes up to a power of 2.)  Let M
13852** be the maximum amount of memory ever outstanding at one time.  Let
13853** N be the total amount of memory available for allocation.  Robson
13854** proved that this memory allocator will never breakdown due to
13855** fragmentation as long as the following constraint holds:
13856**
13857**      N >=  M*(1 + log2(n)/2) - n + 1
13858**
13859** The sqlite3_status() logic tracks the maximum values of n and M so
13860** that an application can, at any time, verify this constraint.
13861*/
13862
13863/*
13864** This version of the memory allocator is used only when
13865** SQLITE_ENABLE_MEMSYS5 is defined.
13866*/
13867#ifdef SQLITE_ENABLE_MEMSYS5
13868
13869/*
13870** A minimum allocation is an instance of the following structure.
13871** Larger allocations are an array of these structures where the
13872** size of the array is a power of 2.
13873**
13874** The size of this object must be a power of two.  That fact is
13875** verified in memsys5Init().
13876*/
13877typedef struct Mem5Link Mem5Link;
13878struct Mem5Link {
13879  int next;       /* Index of next free chunk */
13880  int prev;       /* Index of previous free chunk */
13881};
13882
13883/*
13884** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
13885** mem5.szAtom is always at least 8 and 32-bit integers are used,
13886** it is not actually possible to reach this limit.
13887*/
13888#define LOGMAX 30
13889
13890/*
13891** Masks used for mem5.aCtrl[] elements.
13892*/
13893#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
13894#define CTRL_FREE     0x20    /* True if not checked out */
13895
13896/*
13897** All of the static variables used by this module are collected
13898** into a single structure named "mem5".  This is to keep the
13899** static variables organized and to reduce namespace pollution
13900** when this module is combined with other in the amalgamation.
13901*/
13902static SQLITE_WSD struct Mem5Global {
13903  /*
13904  ** Memory available for allocation
13905  */
13906  int szAtom;      /* Smallest possible allocation in bytes */
13907  int nBlock;      /* Number of szAtom sized blocks in zPool */
13908  u8 *zPool;       /* Memory available to be allocated */
13909
13910  /*
13911  ** Mutex to control access to the memory allocation subsystem.
13912  */
13913  sqlite3_mutex *mutex;
13914
13915  /*
13916  ** Performance statistics
13917  */
13918  u64 nAlloc;         /* Total number of calls to malloc */
13919  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
13920  u64 totalExcess;    /* Total internal fragmentation */
13921  u32 currentOut;     /* Current checkout, including internal fragmentation */
13922  u32 currentCount;   /* Current number of distinct checkouts */
13923  u32 maxOut;         /* Maximum instantaneous currentOut */
13924  u32 maxCount;       /* Maximum instantaneous currentCount */
13925  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
13926
13927  /*
13928  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
13929  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
13930  ** and so forth.
13931  */
13932  int aiFreelist[LOGMAX+1];
13933
13934  /*
13935  ** Space for tracking which blocks are checked out and the size
13936  ** of each block.  One byte per block.
13937  */
13938  u8 *aCtrl;
13939
13940} mem5 = { 0 };
13941
13942/*
13943** Access the static variable through a macro for SQLITE_OMIT_WSD
13944*/
13945#define mem5 GLOBAL(struct Mem5Global, mem5)
13946
13947/*
13948** Assuming mem5.zPool is divided up into an array of Mem5Link
13949** structures, return a pointer to the idx-th such lik.
13950*/
13951#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
13952
13953/*
13954** Unlink the chunk at mem5.aPool[i] from list it is currently
13955** on.  It should be found on mem5.aiFreelist[iLogsize].
13956*/
13957static void memsys5Unlink(int i, int iLogsize){
13958  int next, prev;
13959  assert( i>=0 && i<mem5.nBlock );
13960  assert( iLogsize>=0 && iLogsize<=LOGMAX );
13961  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
13962
13963  next = MEM5LINK(i)->next;
13964  prev = MEM5LINK(i)->prev;
13965  if( prev<0 ){
13966    mem5.aiFreelist[iLogsize] = next;
13967  }else{
13968    MEM5LINK(prev)->next = next;
13969  }
13970  if( next>=0 ){
13971    MEM5LINK(next)->prev = prev;
13972  }
13973}
13974
13975/*
13976** Link the chunk at mem5.aPool[i] so that is on the iLogsize
13977** free list.
13978*/
13979static void memsys5Link(int i, int iLogsize){
13980  int x;
13981  assert( sqlite3_mutex_held(mem5.mutex) );
13982  assert( i>=0 && i<mem5.nBlock );
13983  assert( iLogsize>=0 && iLogsize<=LOGMAX );
13984  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
13985
13986  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
13987  MEM5LINK(i)->prev = -1;
13988  if( x>=0 ){
13989    assert( x<mem5.nBlock );
13990    MEM5LINK(x)->prev = i;
13991  }
13992  mem5.aiFreelist[iLogsize] = i;
13993}
13994
13995/*
13996** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
13997** will already be held (obtained by code in malloc.c) if
13998** sqlite3GlobalConfig.bMemStat is true.
13999*/
14000static void memsys5Enter(void){
14001  sqlite3_mutex_enter(mem5.mutex);
14002}
14003static void memsys5Leave(void){
14004  sqlite3_mutex_leave(mem5.mutex);
14005}
14006
14007/*
14008** Return the size of an outstanding allocation, in bytes.  The
14009** size returned omits the 8-byte header overhead.  This only
14010** works for chunks that are currently checked out.
14011*/
14012static int memsys5Size(void *p){
14013  int iSize = 0;
14014  if( p ){
14015    int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
14016    assert( i>=0 && i<mem5.nBlock );
14017    iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
14018  }
14019  return iSize;
14020}
14021
14022/*
14023** Find the first entry on the freelist iLogsize.  Unlink that
14024** entry and return its index.
14025*/
14026static int memsys5UnlinkFirst(int iLogsize){
14027  int i;
14028  int iFirst;
14029
14030  assert( iLogsize>=0 && iLogsize<=LOGMAX );
14031  i = iFirst = mem5.aiFreelist[iLogsize];
14032  assert( iFirst>=0 );
14033  while( i>0 ){
14034    if( i<iFirst ) iFirst = i;
14035    i = MEM5LINK(i)->next;
14036  }
14037  memsys5Unlink(iFirst, iLogsize);
14038  return iFirst;
14039}
14040
14041/*
14042** Return a block of memory of at least nBytes in size.
14043** Return NULL if unable.  Return NULL if nBytes==0.
14044**
14045** The caller guarantees that nByte positive.
14046**
14047** The caller has obtained a mutex prior to invoking this
14048** routine so there is never any chance that two or more
14049** threads can be in this routine at the same time.
14050*/
14051static void *memsys5MallocUnsafe(int nByte){
14052  int i;           /* Index of a mem5.aPool[] slot */
14053  int iBin;        /* Index into mem5.aiFreelist[] */
14054  int iFullSz;     /* Size of allocation rounded up to power of 2 */
14055  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
14056
14057  /* nByte must be a positive */
14058  assert( nByte>0 );
14059
14060  /* Keep track of the maximum allocation request.  Even unfulfilled
14061  ** requests are counted */
14062  if( (u32)nByte>mem5.maxRequest ){
14063    mem5.maxRequest = nByte;
14064  }
14065
14066  /* Abort if the requested allocation size is larger than the largest
14067  ** power of two that we can represent using 32-bit signed integers.
14068  */
14069  if( nByte > 0x40000000 ){
14070    return 0;
14071  }
14072
14073  /* Round nByte up to the next valid power of two */
14074  for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
14075
14076  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
14077  ** block.  If not, then split a block of the next larger power of
14078  ** two in order to create a new free block of size iLogsize.
14079  */
14080  for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
14081  if( iBin>LOGMAX ){
14082    testcase( sqlite3GlobalConfig.xLog!=0 );
14083    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
14084    return 0;
14085  }
14086  i = memsys5UnlinkFirst(iBin);
14087  while( iBin>iLogsize ){
14088    int newSize;
14089
14090    iBin--;
14091    newSize = 1 << iBin;
14092    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
14093    memsys5Link(i+newSize, iBin);
14094  }
14095  mem5.aCtrl[i] = iLogsize;
14096
14097  /* Update allocator performance statistics. */
14098  mem5.nAlloc++;
14099  mem5.totalAlloc += iFullSz;
14100  mem5.totalExcess += iFullSz - nByte;
14101  mem5.currentCount++;
14102  mem5.currentOut += iFullSz;
14103  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
14104  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
14105
14106  /* Return a pointer to the allocated memory. */
14107  return (void*)&mem5.zPool[i*mem5.szAtom];
14108}
14109
14110/*
14111** Free an outstanding memory allocation.
14112*/
14113static void memsys5FreeUnsafe(void *pOld){
14114  u32 size, iLogsize;
14115  int iBlock;
14116
14117  /* Set iBlock to the index of the block pointed to by pOld in
14118  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
14119  */
14120  iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
14121
14122  /* Check that the pointer pOld points to a valid, non-free block. */
14123  assert( iBlock>=0 && iBlock<mem5.nBlock );
14124  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
14125  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
14126
14127  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
14128  size = 1<<iLogsize;
14129  assert( iBlock+size-1<(u32)mem5.nBlock );
14130
14131  mem5.aCtrl[iBlock] |= CTRL_FREE;
14132  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
14133  assert( mem5.currentCount>0 );
14134  assert( mem5.currentOut>=(size*mem5.szAtom) );
14135  mem5.currentCount--;
14136  mem5.currentOut -= size*mem5.szAtom;
14137  assert( mem5.currentOut>0 || mem5.currentCount==0 );
14138  assert( mem5.currentCount>0 || mem5.currentOut==0 );
14139
14140  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14141  while( ALWAYS(iLogsize<LOGMAX) ){
14142    int iBuddy;
14143    if( (iBlock>>iLogsize) & 1 ){
14144      iBuddy = iBlock - size;
14145    }else{
14146      iBuddy = iBlock + size;
14147    }
14148    assert( iBuddy>=0 );
14149    if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
14150    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
14151    memsys5Unlink(iBuddy, iLogsize);
14152    iLogsize++;
14153    if( iBuddy<iBlock ){
14154      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
14155      mem5.aCtrl[iBlock] = 0;
14156      iBlock = iBuddy;
14157    }else{
14158      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14159      mem5.aCtrl[iBuddy] = 0;
14160    }
14161    size *= 2;
14162  }
14163  memsys5Link(iBlock, iLogsize);
14164}
14165
14166/*
14167** Allocate nBytes of memory
14168*/
14169static void *memsys5Malloc(int nBytes){
14170  sqlite3_int64 *p = 0;
14171  if( nBytes>0 ){
14172    memsys5Enter();
14173    p = memsys5MallocUnsafe(nBytes);
14174    memsys5Leave();
14175  }
14176  return (void*)p;
14177}
14178
14179/*
14180** Free memory.
14181**
14182** The outer layer memory allocator prevents this routine from
14183** being called with pPrior==0.
14184*/
14185static void memsys5Free(void *pPrior){
14186  assert( pPrior!=0 );
14187  memsys5Enter();
14188  memsys5FreeUnsafe(pPrior);
14189  memsys5Leave();
14190}
14191
14192/*
14193** Change the size of an existing memory allocation.
14194**
14195** The outer layer memory allocator prevents this routine from
14196** being called with pPrior==0.
14197**
14198** nBytes is always a value obtained from a prior call to
14199** memsys5Round().  Hence nBytes is always a non-negative power
14200** of two.  If nBytes==0 that means that an oversize allocation
14201** (an allocation larger than 0x40000000) was requested and this
14202** routine should return 0 without freeing pPrior.
14203*/
14204static void *memsys5Realloc(void *pPrior, int nBytes){
14205  int nOld;
14206  void *p;
14207  assert( pPrior!=0 );
14208  assert( (nBytes&(nBytes-1))==0 );
14209  assert( nBytes>=0 );
14210  if( nBytes==0 ){
14211    return 0;
14212  }
14213  nOld = memsys5Size(pPrior);
14214  if( nBytes<=nOld ){
14215    return pPrior;
14216  }
14217  memsys5Enter();
14218  p = memsys5MallocUnsafe(nBytes);
14219  if( p ){
14220    memcpy(p, pPrior, nOld);
14221    memsys5FreeUnsafe(pPrior);
14222  }
14223  memsys5Leave();
14224  return p;
14225}
14226
14227/*
14228** Round up a request size to the next valid allocation size.  If
14229** the allocation is too large to be handled by this allocation system,
14230** return 0.
14231**
14232** All allocations must be a power of two and must be expressed by a
14233** 32-bit signed integer.  Hence the largest allocation is 0x40000000
14234** or 1073741824 bytes.
14235*/
14236static int memsys5Roundup(int n){
14237  int iFullSz;
14238  if( n > 0x40000000 ) return 0;
14239  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
14240  return iFullSz;
14241}
14242
14243/*
14244** Return the ceiling of the logarithm base 2 of iValue.
14245**
14246** Examples:   memsys5Log(1) -> 0
14247**             memsys5Log(2) -> 1
14248**             memsys5Log(4) -> 2
14249**             memsys5Log(5) -> 3
14250**             memsys5Log(8) -> 3
14251**             memsys5Log(9) -> 4
14252*/
14253static int memsys5Log(int iValue){
14254  int iLog;
14255  for(iLog=0; (1<<iLog)<iValue; iLog++);
14256  return iLog;
14257}
14258
14259/*
14260** Initialize the memory allocator.
14261**
14262** This routine is not threadsafe.  The caller must be holding a mutex
14263** to prevent multiple threads from entering at the same time.
14264*/
14265static int memsys5Init(void *NotUsed){
14266  int ii;            /* Loop counter */
14267  int nByte;         /* Number of bytes of memory available to this allocator */
14268  u8 *zByte;         /* Memory usable by this allocator */
14269  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
14270  int iOffset;       /* An offset into mem5.aCtrl[] */
14271
14272  UNUSED_PARAMETER(NotUsed);
14273
14274  /* For the purposes of this routine, disable the mutex */
14275  mem5.mutex = 0;
14276
14277  /* The size of a Mem5Link object must be a power of two.  Verify that
14278  ** this is case.
14279  */
14280  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
14281
14282  nByte = sqlite3GlobalConfig.nHeap;
14283  zByte = (u8*)sqlite3GlobalConfig.pHeap;
14284  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
14285
14286  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
14287  mem5.szAtom = (1<<nMinLog);
14288  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
14289    mem5.szAtom = mem5.szAtom << 1;
14290  }
14291
14292  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
14293  mem5.zPool = zByte;
14294  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
14295
14296  for(ii=0; ii<=LOGMAX; ii++){
14297    mem5.aiFreelist[ii] = -1;
14298  }
14299
14300  iOffset = 0;
14301  for(ii=LOGMAX; ii>=0; ii--){
14302    int nAlloc = (1<<ii);
14303    if( (iOffset+nAlloc)<=mem5.nBlock ){
14304      mem5.aCtrl[iOffset] = ii | CTRL_FREE;
14305      memsys5Link(iOffset, ii);
14306      iOffset += nAlloc;
14307    }
14308    assert((iOffset+nAlloc)>mem5.nBlock);
14309  }
14310
14311  /* If a mutex is required for normal operation, allocate one */
14312  if( sqlite3GlobalConfig.bMemstat==0 ){
14313    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14314  }
14315
14316  return SQLITE_OK;
14317}
14318
14319/*
14320** Deinitialize this module.
14321*/
14322static void memsys5Shutdown(void *NotUsed){
14323  UNUSED_PARAMETER(NotUsed);
14324  mem5.mutex = 0;
14325  return;
14326}
14327
14328#ifdef SQLITE_TEST
14329/*
14330** Open the file indicated and write a log of all unfreed memory
14331** allocations into that log.
14332*/
14333SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
14334  FILE *out;
14335  int i, j, n;
14336  int nMinLog;
14337
14338  if( zFilename==0 || zFilename[0]==0 ){
14339    out = stdout;
14340  }else{
14341    out = fopen(zFilename, "w");
14342    if( out==0 ){
14343      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
14344                      zFilename);
14345      return;
14346    }
14347  }
14348  memsys5Enter();
14349  nMinLog = memsys5Log(mem5.szAtom);
14350  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
14351    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
14352    fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
14353  }
14354  fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
14355  fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
14356  fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
14357  fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
14358  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
14359  fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
14360  fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
14361  fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
14362  memsys5Leave();
14363  if( out==stdout ){
14364    fflush(stdout);
14365  }else{
14366    fclose(out);
14367  }
14368}
14369#endif
14370
14371/*
14372** This routine is the only routine in this file with external
14373** linkage. It returns a pointer to a static sqlite3_mem_methods
14374** struct populated with the memsys5 methods.
14375*/
14376SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
14377  static const sqlite3_mem_methods memsys5Methods = {
14378     memsys5Malloc,
14379     memsys5Free,
14380     memsys5Realloc,
14381     memsys5Size,
14382     memsys5Roundup,
14383     memsys5Init,
14384     memsys5Shutdown,
14385     0
14386  };
14387  return &memsys5Methods;
14388}
14389
14390#endif /* SQLITE_ENABLE_MEMSYS5 */
14391
14392/************** End of mem5.c ************************************************/
14393/************** Begin file mutex.c *******************************************/
14394/*
14395** 2007 August 14
14396**
14397** The author disclaims copyright to this source code.  In place of
14398** a legal notice, here is a blessing:
14399**
14400**    May you do good and not evil.
14401**    May you find forgiveness for yourself and forgive others.
14402**    May you share freely, never taking more than you give.
14403**
14404*************************************************************************
14405** This file contains the C functions that implement mutexes.
14406**
14407** This file contains code that is common across all mutex implementations.
14408*/
14409
14410#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
14411/*
14412** For debugging purposes, record when the mutex subsystem is initialized
14413** and uninitialized so that we can assert() if there is an attempt to
14414** allocate a mutex while the system is uninitialized.
14415*/
14416static SQLITE_WSD int mutexIsInit = 0;
14417#endif /* SQLITE_DEBUG */
14418
14419
14420#ifndef SQLITE_MUTEX_OMIT
14421/*
14422** Initialize the mutex system.
14423*/
14424SQLITE_PRIVATE int sqlite3MutexInit(void){
14425  int rc = SQLITE_OK;
14426  if( sqlite3GlobalConfig.bCoreMutex ){
14427    if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
14428      /* If the xMutexAlloc method has not been set, then the user did not
14429      ** install a mutex implementation via sqlite3_config() prior to
14430      ** sqlite3_initialize() being called. This block copies pointers to
14431      ** the default implementation into the sqlite3GlobalConfig structure.
14432      */
14433      sqlite3_mutex_methods *pFrom = sqlite3DefaultMutex();
14434      sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
14435
14436      memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
14437      memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
14438             sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
14439      pTo->xMutexAlloc = pFrom->xMutexAlloc;
14440    }
14441    rc = sqlite3GlobalConfig.mutex.xMutexInit();
14442  }
14443
14444#ifdef SQLITE_DEBUG
14445  GLOBAL(int, mutexIsInit) = 1;
14446#endif
14447
14448  return rc;
14449}
14450
14451/*
14452** Shutdown the mutex system. This call frees resources allocated by
14453** sqlite3MutexInit().
14454*/
14455SQLITE_PRIVATE int sqlite3MutexEnd(void){
14456  int rc = SQLITE_OK;
14457  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
14458    rc = sqlite3GlobalConfig.mutex.xMutexEnd();
14459  }
14460
14461#ifdef SQLITE_DEBUG
14462  GLOBAL(int, mutexIsInit) = 0;
14463#endif
14464
14465  return rc;
14466}
14467
14468/*
14469** Retrieve a pointer to a static mutex or allocate a new dynamic one.
14470*/
14471SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
14472#ifndef SQLITE_OMIT_AUTOINIT
14473  if( sqlite3_initialize() ) return 0;
14474#endif
14475  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
14476}
14477
14478SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
14479  if( !sqlite3GlobalConfig.bCoreMutex ){
14480    return 0;
14481  }
14482  assert( GLOBAL(int, mutexIsInit) );
14483  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
14484}
14485
14486/*
14487** Free a dynamic mutex.
14488*/
14489SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
14490  if( p ){
14491    sqlite3GlobalConfig.mutex.xMutexFree(p);
14492  }
14493}
14494
14495/*
14496** Obtain the mutex p. If some other thread already has the mutex, block
14497** until it can be obtained.
14498*/
14499SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
14500  if( p ){
14501    sqlite3GlobalConfig.mutex.xMutexEnter(p);
14502  }
14503}
14504
14505/*
14506** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
14507** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
14508*/
14509SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
14510  int rc = SQLITE_OK;
14511  if( p ){
14512    return sqlite3GlobalConfig.mutex.xMutexTry(p);
14513  }
14514  return rc;
14515}
14516
14517/*
14518** The sqlite3_mutex_leave() routine exits a mutex that was previously
14519** entered by the same thread.  The behavior is undefined if the mutex
14520** is not currently entered. If a NULL pointer is passed as an argument
14521** this function is a no-op.
14522*/
14523SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
14524  if( p ){
14525    sqlite3GlobalConfig.mutex.xMutexLeave(p);
14526  }
14527}
14528
14529#ifndef NDEBUG
14530/*
14531** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14532** intended for use inside assert() statements.
14533*/
14534SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
14535  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
14536}
14537SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
14538  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
14539}
14540#endif
14541
14542#endif /* SQLITE_MUTEX_OMIT */
14543
14544/************** End of mutex.c ***********************************************/
14545/************** Begin file mutex_noop.c **************************************/
14546/*
14547** 2008 October 07
14548**
14549** The author disclaims copyright to this source code.  In place of
14550** a legal notice, here is a blessing:
14551**
14552**    May you do good and not evil.
14553**    May you find forgiveness for yourself and forgive others.
14554**    May you share freely, never taking more than you give.
14555**
14556*************************************************************************
14557** This file contains the C functions that implement mutexes.
14558**
14559** This implementation in this file does not provide any mutual
14560** exclusion and is thus suitable for use only in applications
14561** that use SQLite in a single thread.  The routines defined
14562** here are place-holders.  Applications can substitute working
14563** mutex routines at start-time using the
14564**
14565**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
14566**
14567** interface.
14568**
14569** If compiled with SQLITE_DEBUG, then additional logic is inserted
14570** that does error checking on mutexes to make sure they are being
14571** called correctly.
14572*/
14573
14574
14575#if defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG)
14576/*
14577** Stub routines for all mutex methods.
14578**
14579** This routines provide no mutual exclusion or error checking.
14580*/
14581static int noopMutexHeld(sqlite3_mutex *p){ return 1; }
14582static int noopMutexNotheld(sqlite3_mutex *p){ return 1; }
14583static int noopMutexInit(void){ return SQLITE_OK; }
14584static int noopMutexEnd(void){ return SQLITE_OK; }
14585static sqlite3_mutex *noopMutexAlloc(int id){ return (sqlite3_mutex*)8; }
14586static void noopMutexFree(sqlite3_mutex *p){ return; }
14587static void noopMutexEnter(sqlite3_mutex *p){ return; }
14588static int noopMutexTry(sqlite3_mutex *p){ return SQLITE_OK; }
14589static void noopMutexLeave(sqlite3_mutex *p){ return; }
14590
14591SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
14592  static sqlite3_mutex_methods sMutex = {
14593    noopMutexInit,
14594    noopMutexEnd,
14595    noopMutexAlloc,
14596    noopMutexFree,
14597    noopMutexEnter,
14598    noopMutexTry,
14599    noopMutexLeave,
14600
14601    noopMutexHeld,
14602    noopMutexNotheld
14603  };
14604
14605  return &sMutex;
14606}
14607#endif /* defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG) */
14608
14609#if defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG)
14610/*
14611** In this implementation, error checking is provided for testing
14612** and debugging purposes.  The mutexes still do not provide any
14613** mutual exclusion.
14614*/
14615
14616/*
14617** The mutex object
14618*/
14619struct sqlite3_mutex {
14620  int id;     /* The mutex type */
14621  int cnt;    /* Number of entries without a matching leave */
14622};
14623
14624/*
14625** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14626** intended for use inside assert() statements.
14627*/
14628static int debugMutexHeld(sqlite3_mutex *p){
14629  return p==0 || p->cnt>0;
14630}
14631static int debugMutexNotheld(sqlite3_mutex *p){
14632  return p==0 || p->cnt==0;
14633}
14634
14635/*
14636** Initialize and deinitialize the mutex subsystem.
14637*/
14638static int debugMutexInit(void){ return SQLITE_OK; }
14639static int debugMutexEnd(void){ return SQLITE_OK; }
14640
14641/*
14642** The sqlite3_mutex_alloc() routine allocates a new
14643** mutex and returns a pointer to it.  If it returns NULL
14644** that means that a mutex could not be allocated.
14645*/
14646static sqlite3_mutex *debugMutexAlloc(int id){
14647  static sqlite3_mutex aStatic[6];
14648  sqlite3_mutex *pNew = 0;
14649  switch( id ){
14650    case SQLITE_MUTEX_FAST:
14651    case SQLITE_MUTEX_RECURSIVE: {
14652      pNew = sqlite3Malloc(sizeof(*pNew));
14653      if( pNew ){
14654        pNew->id = id;
14655        pNew->cnt = 0;
14656      }
14657      break;
14658    }
14659    default: {
14660      assert( id-2 >= 0 );
14661      assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
14662      pNew = &aStatic[id-2];
14663      pNew->id = id;
14664      break;
14665    }
14666  }
14667  return pNew;
14668}
14669
14670/*
14671** This routine deallocates a previously allocated mutex.
14672*/
14673static void debugMutexFree(sqlite3_mutex *p){
14674  assert( p->cnt==0 );
14675  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
14676  sqlite3_free(p);
14677}
14678
14679/*
14680** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
14681** to enter a mutex.  If another thread is already within the mutex,
14682** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
14683** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
14684** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
14685** be entered multiple times by the same thread.  In such cases the,
14686** mutex must be exited an equal number of times before another thread
14687** can enter.  If the same thread tries to enter any other kind of mutex
14688** more than once, the behavior is undefined.
14689*/
14690static void debugMutexEnter(sqlite3_mutex *p){
14691  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
14692  p->cnt++;
14693}
14694static int debugMutexTry(sqlite3_mutex *p){
14695  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
14696  p->cnt++;
14697  return SQLITE_OK;
14698}
14699
14700/*
14701** The sqlite3_mutex_leave() routine exits a mutex that was
14702** previously entered by the same thread.  The behavior
14703** is undefined if the mutex is not currently entered or
14704** is not currently allocated.  SQLite will never do either.
14705*/
14706static void debugMutexLeave(sqlite3_mutex *p){
14707  assert( debugMutexHeld(p) );
14708  p->cnt--;
14709  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
14710}
14711
14712SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
14713  static sqlite3_mutex_methods sMutex = {
14714    debugMutexInit,
14715    debugMutexEnd,
14716    debugMutexAlloc,
14717    debugMutexFree,
14718    debugMutexEnter,
14719    debugMutexTry,
14720    debugMutexLeave,
14721
14722    debugMutexHeld,
14723    debugMutexNotheld
14724  };
14725
14726  return &sMutex;
14727}
14728#endif /* defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG) */
14729
14730/************** End of mutex_noop.c ******************************************/
14731/************** Begin file mutex_os2.c ***************************************/
14732/*
14733** 2007 August 28
14734**
14735** The author disclaims copyright to this source code.  In place of
14736** a legal notice, here is a blessing:
14737**
14738**    May you do good and not evil.
14739**    May you find forgiveness for yourself and forgive others.
14740**    May you share freely, never taking more than you give.
14741**
14742*************************************************************************
14743** This file contains the C functions that implement mutexes for OS/2
14744*/
14745
14746/*
14747** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
14748** See the mutex.h file for details.
14749*/
14750#ifdef SQLITE_MUTEX_OS2
14751
14752/********************** OS/2 Mutex Implementation **********************
14753**
14754** This implementation of mutexes is built using the OS/2 API.
14755*/
14756
14757/*
14758** The mutex object
14759** Each recursive mutex is an instance of the following structure.
14760*/
14761struct sqlite3_mutex {
14762  HMTX mutex;       /* Mutex controlling the lock */
14763  int  id;          /* Mutex type */
14764  int  nRef;        /* Number of references */
14765  TID  owner;       /* Thread holding this mutex */
14766};
14767
14768#define OS2_MUTEX_INITIALIZER   0,0,0,0
14769
14770/*
14771** Initialize and deinitialize the mutex subsystem.
14772*/
14773static int os2MutexInit(void){ return SQLITE_OK; }
14774static int os2MutexEnd(void){ return SQLITE_OK; }
14775
14776/*
14777** The sqlite3_mutex_alloc() routine allocates a new
14778** mutex and returns a pointer to it.  If it returns NULL
14779** that means that a mutex could not be allocated.
14780** SQLite will unwind its stack and return an error.  The argument
14781** to sqlite3_mutex_alloc() is one of these integer constants:
14782**
14783** <ul>
14784** <li>  SQLITE_MUTEX_FAST               0
14785** <li>  SQLITE_MUTEX_RECURSIVE          1
14786** <li>  SQLITE_MUTEX_STATIC_MASTER      2
14787** <li>  SQLITE_MUTEX_STATIC_MEM         3
14788** <li>  SQLITE_MUTEX_STATIC_PRNG        4
14789** </ul>
14790**
14791** The first two constants cause sqlite3_mutex_alloc() to create
14792** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
14793** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
14794** The mutex implementation does not need to make a distinction
14795** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
14796** not want to.  But SQLite will only request a recursive mutex in
14797** cases where it really needs one.  If a faster non-recursive mutex
14798** implementation is available on the host platform, the mutex subsystem
14799** might return such a mutex in response to SQLITE_MUTEX_FAST.
14800**
14801** The other allowed parameters to sqlite3_mutex_alloc() each return
14802** a pointer to a static preexisting mutex.  Three static mutexes are
14803** used by the current version of SQLite.  Future versions of SQLite
14804** may add additional static mutexes.  Static mutexes are for internal
14805** use by SQLite only.  Applications that use SQLite mutexes should
14806** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
14807** SQLITE_MUTEX_RECURSIVE.
14808**
14809** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
14810** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
14811** returns a different mutex on every call.  But for the static
14812** mutex types, the same mutex is returned on every call that has
14813** the same type number.
14814*/
14815static sqlite3_mutex *os2MutexAlloc(int iType){
14816  sqlite3_mutex *p = NULL;
14817  switch( iType ){
14818    case SQLITE_MUTEX_FAST:
14819    case SQLITE_MUTEX_RECURSIVE: {
14820      p = sqlite3MallocZero( sizeof(*p) );
14821      if( p ){
14822        p->id = iType;
14823        if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
14824          sqlite3_free( p );
14825          p = NULL;
14826        }
14827      }
14828      break;
14829    }
14830    default: {
14831      static volatile int isInit = 0;
14832      static sqlite3_mutex staticMutexes[] = {
14833        { OS2_MUTEX_INITIALIZER, },
14834        { OS2_MUTEX_INITIALIZER, },
14835        { OS2_MUTEX_INITIALIZER, },
14836        { OS2_MUTEX_INITIALIZER, },
14837        { OS2_MUTEX_INITIALIZER, },
14838        { OS2_MUTEX_INITIALIZER, },
14839      };
14840      if ( !isInit ){
14841        APIRET rc;
14842        PTIB ptib;
14843        PPIB ppib;
14844        HMTX mutex;
14845        char name[32];
14846        DosGetInfoBlocks( &ptib, &ppib );
14847        sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
14848                          ppib->pib_ulpid );
14849        while( !isInit ){
14850          mutex = 0;
14851          rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
14852          if( rc == NO_ERROR ){
14853            unsigned int i;
14854            if( !isInit ){
14855              for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
14856                DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
14857              }
14858              isInit = 1;
14859            }
14860            DosCloseMutexSem( mutex );
14861          }else if( rc == ERROR_DUPLICATE_NAME ){
14862            DosSleep( 1 );
14863          }else{
14864            return p;
14865          }
14866        }
14867      }
14868      assert( iType-2 >= 0 );
14869      assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
14870      p = &staticMutexes[iType-2];
14871      p->id = iType;
14872      break;
14873    }
14874  }
14875  return p;
14876}
14877
14878
14879/*
14880** This routine deallocates a previously allocated mutex.
14881** SQLite is careful to deallocate every mutex that it allocates.
14882*/
14883static void os2MutexFree(sqlite3_mutex *p){
14884  if( p==0 ) return;
14885  assert( p->nRef==0 );
14886  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
14887  DosCloseMutexSem( p->mutex );
14888  sqlite3_free( p );
14889}
14890
14891#ifdef SQLITE_DEBUG
14892/*
14893** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14894** intended for use inside assert() statements.
14895*/
14896static int os2MutexHeld(sqlite3_mutex *p){
14897  TID tid;
14898  PID pid;
14899  ULONG ulCount;
14900  PTIB ptib;
14901  if( p!=0 ) {
14902    DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
14903  } else {
14904    DosGetInfoBlocks(&ptib, NULL);
14905    tid = ptib->tib_ptib2->tib2_ultid;
14906  }
14907  return p==0 || (p->nRef!=0 && p->owner==tid);
14908}
14909static int os2MutexNotheld(sqlite3_mutex *p){
14910  TID tid;
14911  PID pid;
14912  ULONG ulCount;
14913  PTIB ptib;
14914  if( p!= 0 ) {
14915    DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
14916  } else {
14917    DosGetInfoBlocks(&ptib, NULL);
14918    tid = ptib->tib_ptib2->tib2_ultid;
14919  }
14920  return p==0 || p->nRef==0 || p->owner!=tid;
14921}
14922#endif
14923
14924/*
14925** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
14926** to enter a mutex.  If another thread is already within the mutex,
14927** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
14928** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
14929** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
14930** be entered multiple times by the same thread.  In such cases the,
14931** mutex must be exited an equal number of times before another thread
14932** can enter.  If the same thread tries to enter any other kind of mutex
14933** more than once, the behavior is undefined.
14934*/
14935static void os2MutexEnter(sqlite3_mutex *p){
14936  TID tid;
14937  PID holder1;
14938  ULONG holder2;
14939  if( p==0 ) return;
14940  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
14941  DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
14942  DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
14943  p->owner = tid;
14944  p->nRef++;
14945}
14946static int os2MutexTry(sqlite3_mutex *p){
14947  int rc;
14948  TID tid;
14949  PID holder1;
14950  ULONG holder2;
14951  if( p==0 ) return SQLITE_OK;
14952  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
14953  if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
14954    DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
14955    p->owner = tid;
14956    p->nRef++;
14957    rc = SQLITE_OK;
14958  } else {
14959    rc = SQLITE_BUSY;
14960  }
14961
14962  return rc;
14963}
14964
14965/*
14966** The sqlite3_mutex_leave() routine exits a mutex that was
14967** previously entered by the same thread.  The behavior
14968** is undefined if the mutex is not currently entered or
14969** is not currently allocated.  SQLite will never do either.
14970*/
14971static void os2MutexLeave(sqlite3_mutex *p){
14972  TID tid;
14973  PID holder1;
14974  ULONG holder2;
14975  if( p==0 ) return;
14976  assert( p->nRef>0 );
14977  DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
14978  assert( p->owner==tid );
14979  p->nRef--;
14980  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
14981  DosReleaseMutexSem(p->mutex);
14982}
14983
14984SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
14985  static sqlite3_mutex_methods sMutex = {
14986    os2MutexInit,
14987    os2MutexEnd,
14988    os2MutexAlloc,
14989    os2MutexFree,
14990    os2MutexEnter,
14991    os2MutexTry,
14992    os2MutexLeave,
14993#ifdef SQLITE_DEBUG
14994    os2MutexHeld,
14995    os2MutexNotheld
14996#endif
14997  };
14998
14999  return &sMutex;
15000}
15001#endif /* SQLITE_MUTEX_OS2 */
15002
15003/************** End of mutex_os2.c *******************************************/
15004/************** Begin file mutex_unix.c **************************************/
15005/*
15006** 2007 August 28
15007**
15008** The author disclaims copyright to this source code.  In place of
15009** a legal notice, here is a blessing:
15010**
15011**    May you do good and not evil.
15012**    May you find forgiveness for yourself and forgive others.
15013**    May you share freely, never taking more than you give.
15014**
15015*************************************************************************
15016** This file contains the C functions that implement mutexes for pthreads
15017*/
15018
15019/*
15020** The code in this file is only used if we are compiling threadsafe
15021** under unix with pthreads.
15022**
15023** Note that this implementation requires a version of pthreads that
15024** supports recursive mutexes.
15025*/
15026#ifdef SQLITE_MUTEX_PTHREADS
15027
15028#include <pthread.h>
15029
15030
15031/*
15032** Each recursive mutex is an instance of the following structure.
15033*/
15034struct sqlite3_mutex {
15035  pthread_mutex_t mutex;     /* Mutex controlling the lock */
15036  int id;                    /* Mutex type */
15037  int nRef;                  /* Number of entrances */
15038  pthread_t owner;           /* Thread that is within this mutex */
15039#ifdef SQLITE_DEBUG
15040  int trace;                 /* True to trace changes */
15041#endif
15042};
15043#ifdef SQLITE_DEBUG
15044#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
15045#else
15046#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0 }
15047#endif
15048
15049/*
15050** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15051** intended for use only inside assert() statements.  On some platforms,
15052** there might be race conditions that can cause these routines to
15053** deliver incorrect results.  In particular, if pthread_equal() is
15054** not an atomic operation, then these routines might delivery
15055** incorrect results.  On most platforms, pthread_equal() is a
15056** comparison of two integers and is therefore atomic.  But we are
15057** told that HPUX is not such a platform.  If so, then these routines
15058** will not always work correctly on HPUX.
15059**
15060** On those platforms where pthread_equal() is not atomic, SQLite
15061** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
15062** make sure no assert() statements are evaluated and hence these
15063** routines are never called.
15064*/
15065#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
15066static int pthreadMutexHeld(sqlite3_mutex *p){
15067  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
15068}
15069static int pthreadMutexNotheld(sqlite3_mutex *p){
15070  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
15071}
15072#endif
15073
15074/*
15075** Initialize and deinitialize the mutex subsystem.
15076*/
15077static int pthreadMutexInit(void){ return SQLITE_OK; }
15078static int pthreadMutexEnd(void){ return SQLITE_OK; }
15079
15080/*
15081** The sqlite3_mutex_alloc() routine allocates a new
15082** mutex and returns a pointer to it.  If it returns NULL
15083** that means that a mutex could not be allocated.  SQLite
15084** will unwind its stack and return an error.  The argument
15085** to sqlite3_mutex_alloc() is one of these integer constants:
15086**
15087** <ul>
15088** <li>  SQLITE_MUTEX_FAST
15089** <li>  SQLITE_MUTEX_RECURSIVE
15090** <li>  SQLITE_MUTEX_STATIC_MASTER
15091** <li>  SQLITE_MUTEX_STATIC_MEM
15092** <li>  SQLITE_MUTEX_STATIC_MEM2
15093** <li>  SQLITE_MUTEX_STATIC_PRNG
15094** <li>  SQLITE_MUTEX_STATIC_LRU
15095** <li>  SQLITE_MUTEX_STATIC_LRU2
15096** </ul>
15097**
15098** The first two constants cause sqlite3_mutex_alloc() to create
15099** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15100** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15101** The mutex implementation does not need to make a distinction
15102** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15103** not want to.  But SQLite will only request a recursive mutex in
15104** cases where it really needs one.  If a faster non-recursive mutex
15105** implementation is available on the host platform, the mutex subsystem
15106** might return such a mutex in response to SQLITE_MUTEX_FAST.
15107**
15108** The other allowed parameters to sqlite3_mutex_alloc() each return
15109** a pointer to a static preexisting mutex.  Six static mutexes are
15110** used by the current version of SQLite.  Future versions of SQLite
15111** may add additional static mutexes.  Static mutexes are for internal
15112** use by SQLite only.  Applications that use SQLite mutexes should
15113** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15114** SQLITE_MUTEX_RECURSIVE.
15115**
15116** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15117** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15118** returns a different mutex on every call.  But for the static
15119** mutex types, the same mutex is returned on every call that has
15120** the same type number.
15121*/
15122static sqlite3_mutex *pthreadMutexAlloc(int iType){
15123  static sqlite3_mutex staticMutexes[] = {
15124    SQLITE3_MUTEX_INITIALIZER,
15125    SQLITE3_MUTEX_INITIALIZER,
15126    SQLITE3_MUTEX_INITIALIZER,
15127    SQLITE3_MUTEX_INITIALIZER,
15128    SQLITE3_MUTEX_INITIALIZER,
15129    SQLITE3_MUTEX_INITIALIZER
15130  };
15131  sqlite3_mutex *p;
15132  switch( iType ){
15133    case SQLITE_MUTEX_RECURSIVE: {
15134      p = sqlite3MallocZero( sizeof(*p) );
15135      if( p ){
15136#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15137        /* If recursive mutexes are not available, we will have to
15138        ** build our own.  See below. */
15139        pthread_mutex_init(&p->mutex, 0);
15140#else
15141        /* Use a recursive mutex if it is available */
15142        pthread_mutexattr_t recursiveAttr;
15143        pthread_mutexattr_init(&recursiveAttr);
15144        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
15145        pthread_mutex_init(&p->mutex, &recursiveAttr);
15146        pthread_mutexattr_destroy(&recursiveAttr);
15147#endif
15148        p->id = iType;
15149      }
15150      break;
15151    }
15152    case SQLITE_MUTEX_FAST: {
15153      p = sqlite3MallocZero( sizeof(*p) );
15154      if( p ){
15155        p->id = iType;
15156        pthread_mutex_init(&p->mutex, 0);
15157      }
15158      break;
15159    }
15160    default: {
15161      assert( iType-2 >= 0 );
15162      assert( iType-2 < ArraySize(staticMutexes) );
15163      p = &staticMutexes[iType-2];
15164      p->id = iType;
15165      break;
15166    }
15167  }
15168  return p;
15169}
15170
15171
15172/*
15173** This routine deallocates a previously
15174** allocated mutex.  SQLite is careful to deallocate every
15175** mutex that it allocates.
15176*/
15177static void pthreadMutexFree(sqlite3_mutex *p){
15178  assert( p->nRef==0 );
15179  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15180  pthread_mutex_destroy(&p->mutex);
15181  sqlite3_free(p);
15182}
15183
15184/*
15185** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15186** to enter a mutex.  If another thread is already within the mutex,
15187** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15188** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15189** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15190** be entered multiple times by the same thread.  In such cases the,
15191** mutex must be exited an equal number of times before another thread
15192** can enter.  If the same thread tries to enter any other kind of mutex
15193** more than once, the behavior is undefined.
15194*/
15195static void pthreadMutexEnter(sqlite3_mutex *p){
15196  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15197
15198#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15199  /* If recursive mutexes are not available, then we have to grow
15200  ** our own.  This implementation assumes that pthread_equal()
15201  ** is atomic - that it cannot be deceived into thinking self
15202  ** and p->owner are equal if p->owner changes between two values
15203  ** that are not equal to self while the comparison is taking place.
15204  ** This implementation also assumes a coherent cache - that
15205  ** separate processes cannot read different values from the same
15206  ** address at the same time.  If either of these two conditions
15207  ** are not met, then the mutexes will fail and problems will result.
15208  */
15209  {
15210    pthread_t self = pthread_self();
15211    if( p->nRef>0 && pthread_equal(p->owner, self) ){
15212      p->nRef++;
15213    }else{
15214      pthread_mutex_lock(&p->mutex);
15215      assert( p->nRef==0 );
15216      p->owner = self;
15217      p->nRef = 1;
15218    }
15219  }
15220#else
15221  /* Use the built-in recursive mutexes if they are available.
15222  */
15223  pthread_mutex_lock(&p->mutex);
15224  p->owner = pthread_self();
15225  p->nRef++;
15226#endif
15227
15228#ifdef SQLITE_DEBUG
15229  if( p->trace ){
15230    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15231  }
15232#endif
15233}
15234static int pthreadMutexTry(sqlite3_mutex *p){
15235  int rc;
15236  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15237
15238#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15239  /* If recursive mutexes are not available, then we have to grow
15240  ** our own.  This implementation assumes that pthread_equal()
15241  ** is atomic - that it cannot be deceived into thinking self
15242  ** and p->owner are equal if p->owner changes between two values
15243  ** that are not equal to self while the comparison is taking place.
15244  ** This implementation also assumes a coherent cache - that
15245  ** separate processes cannot read different values from the same
15246  ** address at the same time.  If either of these two conditions
15247  ** are not met, then the mutexes will fail and problems will result.
15248  */
15249  {
15250    pthread_t self = pthread_self();
15251    if( p->nRef>0 && pthread_equal(p->owner, self) ){
15252      p->nRef++;
15253      rc = SQLITE_OK;
15254    }else if( pthread_mutex_trylock(&p->mutex)==0 ){
15255      assert( p->nRef==0 );
15256      p->owner = self;
15257      p->nRef = 1;
15258      rc = SQLITE_OK;
15259    }else{
15260      rc = SQLITE_BUSY;
15261    }
15262  }
15263#else
15264  /* Use the built-in recursive mutexes if they are available.
15265  */
15266  if( pthread_mutex_trylock(&p->mutex)==0 ){
15267    p->owner = pthread_self();
15268    p->nRef++;
15269    rc = SQLITE_OK;
15270  }else{
15271    rc = SQLITE_BUSY;
15272  }
15273#endif
15274
15275#ifdef SQLITE_DEBUG
15276  if( rc==SQLITE_OK && p->trace ){
15277    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15278  }
15279#endif
15280  return rc;
15281}
15282
15283/*
15284** The sqlite3_mutex_leave() routine exits a mutex that was
15285** previously entered by the same thread.  The behavior
15286** is undefined if the mutex is not currently entered or
15287** is not currently allocated.  SQLite will never do either.
15288*/
15289static void pthreadMutexLeave(sqlite3_mutex *p){
15290  assert( pthreadMutexHeld(p) );
15291  p->nRef--;
15292  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15293
15294#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15295  if( p->nRef==0 ){
15296    pthread_mutex_unlock(&p->mutex);
15297  }
15298#else
15299  pthread_mutex_unlock(&p->mutex);
15300#endif
15301
15302#ifdef SQLITE_DEBUG
15303  if( p->trace ){
15304    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15305  }
15306#endif
15307}
15308
15309SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15310  static sqlite3_mutex_methods sMutex = {
15311    pthreadMutexInit,
15312    pthreadMutexEnd,
15313    pthreadMutexAlloc,
15314    pthreadMutexFree,
15315    pthreadMutexEnter,
15316    pthreadMutexTry,
15317    pthreadMutexLeave,
15318#ifdef SQLITE_DEBUG
15319    pthreadMutexHeld,
15320    pthreadMutexNotheld
15321#else
15322    0,
15323    0
15324#endif
15325  };
15326
15327  return &sMutex;
15328}
15329
15330#endif /* SQLITE_MUTEX_PTHREAD */
15331
15332/************** End of mutex_unix.c ******************************************/
15333/************** Begin file mutex_w32.c ***************************************/
15334/*
15335** 2007 August 14
15336**
15337** The author disclaims copyright to this source code.  In place of
15338** a legal notice, here is a blessing:
15339**
15340**    May you do good and not evil.
15341**    May you find forgiveness for yourself and forgive others.
15342**    May you share freely, never taking more than you give.
15343**
15344*************************************************************************
15345** This file contains the C functions that implement mutexes for win32
15346*/
15347
15348/*
15349** The code in this file is only used if we are compiling multithreaded
15350** on a win32 system.
15351*/
15352#ifdef SQLITE_MUTEX_W32
15353
15354/*
15355** Each recursive mutex is an instance of the following structure.
15356*/
15357struct sqlite3_mutex {
15358  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
15359  int id;                    /* Mutex type */
15360  int nRef;                  /* Number of enterances */
15361  DWORD owner;               /* Thread holding this mutex */
15362};
15363
15364/*
15365** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
15366** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
15367**
15368** Here is an interesting observation:  Win95, Win98, and WinME lack
15369** the LockFileEx() API.  But we can still statically link against that
15370** API as long as we don't call it win running Win95/98/ME.  A call to
15371** this routine is used to determine if the host is Win95/98/ME or
15372** WinNT/2K/XP so that we will know whether or not we can safely call
15373** the LockFileEx() API.
15374**
15375** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
15376** which is only available if your application was compiled with
15377** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
15378** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
15379** this out as well.
15380*/
15381#if 0
15382#if SQLITE_OS_WINCE
15383# define mutexIsNT()  (1)
15384#else
15385  static int mutexIsNT(void){
15386    static int osType = 0;
15387    if( osType==0 ){
15388      OSVERSIONINFO sInfo;
15389      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
15390      GetVersionEx(&sInfo);
15391      osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
15392    }
15393    return osType==2;
15394  }
15395#endif /* SQLITE_OS_WINCE */
15396#endif
15397
15398#ifdef SQLITE_DEBUG
15399/*
15400** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15401** intended for use only inside assert() statements.
15402*/
15403static int winMutexHeld(sqlite3_mutex *p){
15404  return p->nRef!=0 && p->owner==GetCurrentThreadId();
15405}
15406static int winMutexNotheld(sqlite3_mutex *p){
15407  return p->nRef==0 || p->owner!=GetCurrentThreadId();
15408}
15409#endif
15410
15411
15412/*
15413** Initialize and deinitialize the mutex subsystem.
15414*/
15415static sqlite3_mutex winMutex_staticMutexes[6];
15416static int winMutex_isInit = 0;
15417/* As winMutexInit() and winMutexEnd() are called as part
15418** of the sqlite3_initialize and sqlite3_shutdown()
15419** processing, the "interlocked" magic is probably not
15420** strictly necessary.
15421*/
15422static long winMutex_lock = 0;
15423
15424static int winMutexInit(void){
15425  /* The first to increment to 1 does actual initialization */
15426  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
15427    int i;
15428    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
15429      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
15430    }
15431    winMutex_isInit = 1;
15432  }else{
15433    /* Someone else is in the process of initing the static mutexes */
15434    while( !winMutex_isInit ){
15435      Sleep(1);
15436    }
15437  }
15438  return SQLITE_OK;
15439}
15440
15441static int winMutexEnd(void){
15442  /* The first to decrement to 0 does actual shutdown
15443  ** (which should be the last to shutdown.) */
15444  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
15445    if( winMutex_isInit==1 ){
15446      int i;
15447      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
15448        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
15449      }
15450      winMutex_isInit = 0;
15451    }
15452  }
15453  return SQLITE_OK;
15454}
15455
15456/*
15457** The sqlite3_mutex_alloc() routine allocates a new
15458** mutex and returns a pointer to it.  If it returns NULL
15459** that means that a mutex could not be allocated.  SQLite
15460** will unwind its stack and return an error.  The argument
15461** to sqlite3_mutex_alloc() is one of these integer constants:
15462**
15463** <ul>
15464** <li>  SQLITE_MUTEX_FAST
15465** <li>  SQLITE_MUTEX_RECURSIVE
15466** <li>  SQLITE_MUTEX_STATIC_MASTER
15467** <li>  SQLITE_MUTEX_STATIC_MEM
15468** <li>  SQLITE_MUTEX_STATIC_MEM2
15469** <li>  SQLITE_MUTEX_STATIC_PRNG
15470** <li>  SQLITE_MUTEX_STATIC_LRU
15471** <li>  SQLITE_MUTEX_STATIC_LRU2
15472** </ul>
15473**
15474** The first two constants cause sqlite3_mutex_alloc() to create
15475** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15476** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15477** The mutex implementation does not need to make a distinction
15478** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15479** not want to.  But SQLite will only request a recursive mutex in
15480** cases where it really needs one.  If a faster non-recursive mutex
15481** implementation is available on the host platform, the mutex subsystem
15482** might return such a mutex in response to SQLITE_MUTEX_FAST.
15483**
15484** The other allowed parameters to sqlite3_mutex_alloc() each return
15485** a pointer to a static preexisting mutex.  Six static mutexes are
15486** used by the current version of SQLite.  Future versions of SQLite
15487** may add additional static mutexes.  Static mutexes are for internal
15488** use by SQLite only.  Applications that use SQLite mutexes should
15489** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15490** SQLITE_MUTEX_RECURSIVE.
15491**
15492** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15493** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15494** returns a different mutex on every call.  But for the static
15495** mutex types, the same mutex is returned on every call that has
15496** the same type number.
15497*/
15498static sqlite3_mutex *winMutexAlloc(int iType){
15499  sqlite3_mutex *p;
15500
15501  switch( iType ){
15502    case SQLITE_MUTEX_FAST:
15503    case SQLITE_MUTEX_RECURSIVE: {
15504      p = sqlite3MallocZero( sizeof(*p) );
15505      if( p ){
15506        p->id = iType;
15507        InitializeCriticalSection(&p->mutex);
15508      }
15509      break;
15510    }
15511    default: {
15512      assert( winMutex_isInit==1 );
15513      assert( iType-2 >= 0 );
15514      assert( iType-2 < ArraySize(winMutex_staticMutexes) );
15515      p = &winMutex_staticMutexes[iType-2];
15516      p->id = iType;
15517      break;
15518    }
15519  }
15520  return p;
15521}
15522
15523
15524/*
15525** This routine deallocates a previously
15526** allocated mutex.  SQLite is careful to deallocate every
15527** mutex that it allocates.
15528*/
15529static void winMutexFree(sqlite3_mutex *p){
15530  assert( p );
15531  assert( p->nRef==0 );
15532  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15533  DeleteCriticalSection(&p->mutex);
15534  sqlite3_free(p);
15535}
15536
15537/*
15538** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15539** to enter a mutex.  If another thread is already within the mutex,
15540** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15541** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15542** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15543** be entered multiple times by the same thread.  In such cases the,
15544** mutex must be exited an equal number of times before another thread
15545** can enter.  If the same thread tries to enter any other kind of mutex
15546** more than once, the behavior is undefined.
15547*/
15548static void winMutexEnter(sqlite3_mutex *p){
15549  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
15550  EnterCriticalSection(&p->mutex);
15551  p->owner = GetCurrentThreadId();
15552  p->nRef++;
15553}
15554static int winMutexTry(sqlite3_mutex *p){
15555  int rc = SQLITE_BUSY;
15556  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
15557  /*
15558  ** The sqlite3_mutex_try() routine is very rarely used, and when it
15559  ** is used it is merely an optimization.  So it is OK for it to always
15560  ** fail.
15561  **
15562  ** The TryEnterCriticalSection() interface is only available on WinNT.
15563  ** And some windows compilers complain if you try to use it without
15564  ** first doing some #defines that prevent SQLite from building on Win98.
15565  ** For that reason, we will omit this optimization for now.  See
15566  ** ticket #2685.
15567  */
15568#if 0
15569  if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
15570    p->owner = GetCurrentThreadId();
15571    p->nRef++;
15572    rc = SQLITE_OK;
15573  }
15574#else
15575  UNUSED_PARAMETER(p);
15576#endif
15577  return rc;
15578}
15579
15580/*
15581** The sqlite3_mutex_leave() routine exits a mutex that was
15582** previously entered by the same thread.  The behavior
15583** is undefined if the mutex is not currently entered or
15584** is not currently allocated.  SQLite will never do either.
15585*/
15586static void winMutexLeave(sqlite3_mutex *p){
15587  assert( p->nRef>0 );
15588  assert( p->owner==GetCurrentThreadId() );
15589  p->nRef--;
15590  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15591  LeaveCriticalSection(&p->mutex);
15592}
15593
15594SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15595  static sqlite3_mutex_methods sMutex = {
15596    winMutexInit,
15597    winMutexEnd,
15598    winMutexAlloc,
15599    winMutexFree,
15600    winMutexEnter,
15601    winMutexTry,
15602    winMutexLeave,
15603#ifdef SQLITE_DEBUG
15604    winMutexHeld,
15605    winMutexNotheld
15606#else
15607    0,
15608    0
15609#endif
15610  };
15611
15612  return &sMutex;
15613}
15614#endif /* SQLITE_MUTEX_W32 */
15615
15616/************** End of mutex_w32.c *******************************************/
15617/************** Begin file malloc.c ******************************************/
15618/*
15619** 2001 September 15
15620**
15621** The author disclaims copyright to this source code.  In place of
15622** a legal notice, here is a blessing:
15623**
15624**    May you do good and not evil.
15625**    May you find forgiveness for yourself and forgive others.
15626**    May you share freely, never taking more than you give.
15627**
15628*************************************************************************
15629**
15630** Memory allocation functions used throughout sqlite.
15631*/
15632
15633/*
15634** This routine runs when the memory allocator sees that the
15635** total memory allocation is about to exceed the soft heap
15636** limit.
15637*/
15638static void softHeapLimitEnforcer(
15639  void *NotUsed,
15640  sqlite3_int64 NotUsed2,
15641  int allocSize
15642){
15643  UNUSED_PARAMETER2(NotUsed, NotUsed2);
15644  sqlite3_release_memory(allocSize);
15645}
15646
15647/*
15648** Set the soft heap-size limit for the library. Passing a zero or
15649** negative value indicates no limit.
15650*/
15651SQLITE_API void sqlite3_soft_heap_limit(int n){
15652  sqlite3_uint64 iLimit;
15653  int overage;
15654  if( n<0 ){
15655    iLimit = 0;
15656  }else{
15657    iLimit = n;
15658  }
15659#ifndef SQLITE_OMIT_AUTOINIT
15660  sqlite3_initialize();
15661#endif
15662  if( iLimit>0 ){
15663    sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
15664  }else{
15665    sqlite3MemoryAlarm(0, 0, 0);
15666  }
15667  overage = (int)(sqlite3_memory_used() - (i64)n);
15668  if( overage>0 ){
15669    sqlite3_release_memory(overage);
15670  }
15671}
15672
15673/*
15674** Attempt to release up to n bytes of non-essential memory currently
15675** held by SQLite. An example of non-essential memory is memory used to
15676** cache database pages that are not currently in use.
15677*/
15678SQLITE_API int sqlite3_release_memory(int n){
15679#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
15680  int nRet = 0;
15681  nRet += sqlite3PcacheReleaseMemory(n-nRet);
15682  return nRet;
15683#else
15684  UNUSED_PARAMETER(n);
15685  return SQLITE_OK;
15686#endif
15687}
15688
15689/*
15690** State information local to the memory allocation subsystem.
15691*/
15692static SQLITE_WSD struct Mem0Global {
15693  /* Number of free pages for scratch and page-cache memory */
15694  u32 nScratchFree;
15695  u32 nPageFree;
15696
15697  sqlite3_mutex *mutex;         /* Mutex to serialize access */
15698
15699  /*
15700  ** The alarm callback and its arguments.  The mem0.mutex lock will
15701  ** be held while the callback is running.  Recursive calls into
15702  ** the memory subsystem are allowed, but no new callbacks will be
15703  ** issued.
15704  */
15705  sqlite3_int64 alarmThreshold;
15706  void (*alarmCallback)(void*, sqlite3_int64,int);
15707  void *alarmArg;
15708
15709  /*
15710  ** Pointers to the end of sqlite3GlobalConfig.pScratch and
15711  ** sqlite3GlobalConfig.pPage to a block of memory that records
15712  ** which pages are available.
15713  */
15714  u32 *aScratchFree;
15715  u32 *aPageFree;
15716} mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
15717
15718#define mem0 GLOBAL(struct Mem0Global, mem0)
15719
15720/*
15721** Initialize the memory allocation subsystem.
15722*/
15723SQLITE_PRIVATE int sqlite3MallocInit(void){
15724  if( sqlite3GlobalConfig.m.xMalloc==0 ){
15725    sqlite3MemSetDefault();
15726  }
15727  memset(&mem0, 0, sizeof(mem0));
15728  if( sqlite3GlobalConfig.bCoreMutex ){
15729    mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15730  }
15731  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
15732      && sqlite3GlobalConfig.nScratch>=0 ){
15733    int i;
15734    sqlite3GlobalConfig.szScratch = ROUNDDOWN8(sqlite3GlobalConfig.szScratch-4);
15735    mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
15736                  [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
15737    for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
15738    mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
15739  }else{
15740    sqlite3GlobalConfig.pScratch = 0;
15741    sqlite3GlobalConfig.szScratch = 0;
15742  }
15743  if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
15744      && sqlite3GlobalConfig.nPage>=1 ){
15745    int i;
15746    int overhead;
15747    int sz = ROUNDDOWN8(sqlite3GlobalConfig.szPage);
15748    int n = sqlite3GlobalConfig.nPage;
15749    overhead = (4*n + sz - 1)/sz;
15750    sqlite3GlobalConfig.nPage -= overhead;
15751    mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
15752                  [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
15753    for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
15754    mem0.nPageFree = sqlite3GlobalConfig.nPage;
15755  }else{
15756    sqlite3GlobalConfig.pPage = 0;
15757    sqlite3GlobalConfig.szPage = 0;
15758  }
15759  return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
15760}
15761
15762/*
15763** Deinitialize the memory allocation subsystem.
15764*/
15765SQLITE_PRIVATE void sqlite3MallocEnd(void){
15766  if( sqlite3GlobalConfig.m.xShutdown ){
15767    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
15768  }
15769  memset(&mem0, 0, sizeof(mem0));
15770}
15771
15772/*
15773** Return the amount of memory currently checked out.
15774*/
15775SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
15776  int n, mx;
15777  sqlite3_int64 res;
15778  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
15779  res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
15780  return res;
15781}
15782
15783/*
15784** Return the maximum amount of memory that has ever been
15785** checked out since either the beginning of this process
15786** or since the most recent reset.
15787*/
15788SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
15789  int n, mx;
15790  sqlite3_int64 res;
15791  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
15792  res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
15793  return res;
15794}
15795
15796/*
15797** Change the alarm callback
15798*/
15799SQLITE_PRIVATE int sqlite3MemoryAlarm(
15800  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
15801  void *pArg,
15802  sqlite3_int64 iThreshold
15803){
15804  sqlite3_mutex_enter(mem0.mutex);
15805  mem0.alarmCallback = xCallback;
15806  mem0.alarmArg = pArg;
15807  mem0.alarmThreshold = iThreshold;
15808  sqlite3_mutex_leave(mem0.mutex);
15809  return SQLITE_OK;
15810}
15811
15812#ifndef SQLITE_OMIT_DEPRECATED
15813/*
15814** Deprecated external interface.  Internal/core SQLite code
15815** should call sqlite3MemoryAlarm.
15816*/
15817SQLITE_API int sqlite3_memory_alarm(
15818  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
15819  void *pArg,
15820  sqlite3_int64 iThreshold
15821){
15822  return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
15823}
15824#endif
15825
15826/*
15827** Trigger the alarm
15828*/
15829static void sqlite3MallocAlarm(int nByte){
15830  void (*xCallback)(void*,sqlite3_int64,int);
15831  sqlite3_int64 nowUsed;
15832  void *pArg;
15833  if( mem0.alarmCallback==0 ) return;
15834  xCallback = mem0.alarmCallback;
15835  nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
15836  pArg = mem0.alarmArg;
15837  mem0.alarmCallback = 0;
15838  sqlite3_mutex_leave(mem0.mutex);
15839  xCallback(pArg, nowUsed, nByte);
15840  sqlite3_mutex_enter(mem0.mutex);
15841  mem0.alarmCallback = xCallback;
15842  mem0.alarmArg = pArg;
15843}
15844
15845/*
15846** Do a memory allocation with statistics and alarms.  Assume the
15847** lock is already held.
15848*/
15849static int mallocWithAlarm(int n, void **pp){
15850  int nFull;
15851  void *p;
15852  assert( sqlite3_mutex_held(mem0.mutex) );
15853  nFull = sqlite3GlobalConfig.m.xRoundup(n);
15854  sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
15855  if( mem0.alarmCallback!=0 ){
15856    int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
15857    if( nUsed+nFull >= mem0.alarmThreshold ){
15858      sqlite3MallocAlarm(nFull);
15859    }
15860  }
15861  p = sqlite3GlobalConfig.m.xMalloc(nFull);
15862  if( p==0 && mem0.alarmCallback ){
15863    sqlite3MallocAlarm(nFull);
15864    p = sqlite3GlobalConfig.m.xMalloc(nFull);
15865  }
15866  if( p ){
15867    nFull = sqlite3MallocSize(p);
15868    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
15869  }
15870  *pp = p;
15871  return nFull;
15872}
15873
15874/*
15875** Allocate memory.  This routine is like sqlite3_malloc() except that it
15876** assumes the memory subsystem has already been initialized.
15877*/
15878SQLITE_PRIVATE void *sqlite3Malloc(int n){
15879  void *p;
15880  if( n<=0 || n>=0x7fffff00 ){
15881    /* A memory allocation of a number of bytes which is near the maximum
15882    ** signed integer value might cause an integer overflow inside of the
15883    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
15884    ** 255 bytes of overhead.  SQLite itself will never use anything near
15885    ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
15886    p = 0;
15887  }else if( sqlite3GlobalConfig.bMemstat ){
15888    sqlite3_mutex_enter(mem0.mutex);
15889    mallocWithAlarm(n, &p);
15890    sqlite3_mutex_leave(mem0.mutex);
15891  }else{
15892    p = sqlite3GlobalConfig.m.xMalloc(n);
15893  }
15894  return p;
15895}
15896
15897/*
15898** This version of the memory allocation is for use by the application.
15899** First make sure the memory subsystem is initialized, then do the
15900** allocation.
15901*/
15902SQLITE_API void *sqlite3_malloc(int n){
15903#ifndef SQLITE_OMIT_AUTOINIT
15904  if( sqlite3_initialize() ) return 0;
15905#endif
15906  return sqlite3Malloc(n);
15907}
15908
15909/*
15910** Each thread may only have a single outstanding allocation from
15911** xScratchMalloc().  We verify this constraint in the single-threaded
15912** case by setting scratchAllocOut to 1 when an allocation
15913** is outstanding clearing it when the allocation is freed.
15914*/
15915#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15916static int scratchAllocOut = 0;
15917#endif
15918
15919
15920/*
15921** Allocate memory that is to be used and released right away.
15922** This routine is similar to alloca() in that it is not intended
15923** for situations where the memory might be held long-term.  This
15924** routine is intended to get memory to old large transient data
15925** structures that would not normally fit on the stack of an
15926** embedded processor.
15927*/
15928SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
15929  void *p;
15930  assert( n>0 );
15931
15932#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15933  /* Verify that no more than one scratch allocation per thread
15934  ** is outstanding at one time.  (This is only checked in the
15935  ** single-threaded case since checking in the multi-threaded case
15936  ** would be much more complicated.) */
15937  assert( scratchAllocOut==0 );
15938#endif
15939
15940  if( sqlite3GlobalConfig.szScratch<n ){
15941    goto scratch_overflow;
15942  }else{
15943    sqlite3_mutex_enter(mem0.mutex);
15944    if( mem0.nScratchFree==0 ){
15945      sqlite3_mutex_leave(mem0.mutex);
15946      goto scratch_overflow;
15947    }else{
15948      int i;
15949      i = mem0.aScratchFree[--mem0.nScratchFree];
15950      i *= sqlite3GlobalConfig.szScratch;
15951      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
15952      sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
15953      sqlite3_mutex_leave(mem0.mutex);
15954      p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
15955      assert(  (((u8*)p - (u8*)0) & 7)==0 );
15956    }
15957  }
15958#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15959  scratchAllocOut = p!=0;
15960#endif
15961
15962  return p;
15963
15964scratch_overflow:
15965  if( sqlite3GlobalConfig.bMemstat ){
15966    sqlite3_mutex_enter(mem0.mutex);
15967    sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
15968    n = mallocWithAlarm(n, &p);
15969    if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
15970    sqlite3_mutex_leave(mem0.mutex);
15971  }else{
15972    p = sqlite3GlobalConfig.m.xMalloc(n);
15973  }
15974#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15975  scratchAllocOut = p!=0;
15976#endif
15977  return p;
15978}
15979SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
15980  if( p ){
15981
15982#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15983    /* Verify that no more than one scratch allocation per thread
15984    ** is outstanding at one time.  (This is only checked in the
15985    ** single-threaded case since checking in the multi-threaded case
15986    ** would be much more complicated.) */
15987    assert( scratchAllocOut==1 );
15988    scratchAllocOut = 0;
15989#endif
15990
15991    if( sqlite3GlobalConfig.pScratch==0
15992           || p<sqlite3GlobalConfig.pScratch
15993           || p>=(void*)mem0.aScratchFree ){
15994      if( sqlite3GlobalConfig.bMemstat ){
15995        int iSize = sqlite3MallocSize(p);
15996        sqlite3_mutex_enter(mem0.mutex);
15997        sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
15998        sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
15999        sqlite3GlobalConfig.m.xFree(p);
16000        sqlite3_mutex_leave(mem0.mutex);
16001      }else{
16002        sqlite3GlobalConfig.m.xFree(p);
16003      }
16004    }else{
16005      int i;
16006      i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
16007      i /= sqlite3GlobalConfig.szScratch;
16008      assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
16009      sqlite3_mutex_enter(mem0.mutex);
16010      assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
16011      mem0.aScratchFree[mem0.nScratchFree++] = i;
16012      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
16013      sqlite3_mutex_leave(mem0.mutex);
16014    }
16015  }
16016}
16017
16018/*
16019** TRUE if p is a lookaside memory allocation from db
16020*/
16021#ifndef SQLITE_OMIT_LOOKASIDE
16022static int isLookaside(sqlite3 *db, void *p){
16023  return db && p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
16024}
16025#else
16026#define isLookaside(A,B) 0
16027#endif
16028
16029/*
16030** Return the size of a memory allocation previously obtained from
16031** sqlite3Malloc() or sqlite3_malloc().
16032*/
16033SQLITE_PRIVATE int sqlite3MallocSize(void *p){
16034  return sqlite3GlobalConfig.m.xSize(p);
16035}
16036SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
16037  assert( db==0 || sqlite3_mutex_held(db->mutex) );
16038  if( isLookaside(db, p) ){
16039    return db->lookaside.sz;
16040  }else{
16041    return sqlite3GlobalConfig.m.xSize(p);
16042  }
16043}
16044
16045/*
16046** Free memory previously obtained from sqlite3Malloc().
16047*/
16048SQLITE_API void sqlite3_free(void *p){
16049  if( p==0 ) return;
16050  if( sqlite3GlobalConfig.bMemstat ){
16051    sqlite3_mutex_enter(mem0.mutex);
16052    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
16053    sqlite3GlobalConfig.m.xFree(p);
16054    sqlite3_mutex_leave(mem0.mutex);
16055  }else{
16056    sqlite3GlobalConfig.m.xFree(p);
16057  }
16058}
16059
16060/*
16061** Free memory that might be associated with a particular database
16062** connection.
16063*/
16064SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
16065  assert( db==0 || sqlite3_mutex_held(db->mutex) );
16066  if( isLookaside(db, p) ){
16067    LookasideSlot *pBuf = (LookasideSlot*)p;
16068    pBuf->pNext = db->lookaside.pFree;
16069    db->lookaside.pFree = pBuf;
16070    db->lookaside.nOut--;
16071  }else{
16072    sqlite3_free(p);
16073  }
16074}
16075
16076/*
16077** Change the size of an existing memory allocation
16078*/
16079SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
16080  int nOld, nNew;
16081  void *pNew;
16082  if( pOld==0 ){
16083    return sqlite3Malloc(nBytes);
16084  }
16085  if( nBytes<=0 ){
16086    sqlite3_free(pOld);
16087    return 0;
16088  }
16089  if( nBytes>=0x7fffff00 ){
16090    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
16091    return 0;
16092  }
16093  nOld = sqlite3MallocSize(pOld);
16094  nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
16095  if( nOld==nNew ){
16096    pNew = pOld;
16097  }else if( sqlite3GlobalConfig.bMemstat ){
16098    sqlite3_mutex_enter(mem0.mutex);
16099    sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
16100    if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >=
16101          mem0.alarmThreshold ){
16102      sqlite3MallocAlarm(nNew-nOld);
16103    }
16104    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16105    if( pNew==0 && mem0.alarmCallback ){
16106      sqlite3MallocAlarm(nBytes);
16107      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16108    }
16109    if( pNew ){
16110      nNew = sqlite3MallocSize(pNew);
16111      sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
16112    }
16113    sqlite3_mutex_leave(mem0.mutex);
16114  }else{
16115    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16116  }
16117  return pNew;
16118}
16119
16120/*
16121** The public interface to sqlite3Realloc.  Make sure that the memory
16122** subsystem is initialized prior to invoking sqliteRealloc.
16123*/
16124SQLITE_API void *sqlite3_realloc(void *pOld, int n){
16125#ifndef SQLITE_OMIT_AUTOINIT
16126  if( sqlite3_initialize() ) return 0;
16127#endif
16128  return sqlite3Realloc(pOld, n);
16129}
16130
16131
16132/*
16133** Allocate and zero memory.
16134*/
16135SQLITE_PRIVATE void *sqlite3MallocZero(int n){
16136  void *p = sqlite3Malloc(n);
16137  if( p ){
16138    memset(p, 0, n);
16139  }
16140  return p;
16141}
16142
16143/*
16144** Allocate and zero memory.  If the allocation fails, make
16145** the mallocFailed flag in the connection pointer.
16146*/
16147SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
16148  void *p = sqlite3DbMallocRaw(db, n);
16149  if( p ){
16150    memset(p, 0, n);
16151  }
16152  return p;
16153}
16154
16155/*
16156** Allocate and zero memory.  If the allocation fails, make
16157** the mallocFailed flag in the connection pointer.
16158**
16159** If db!=0 and db->mallocFailed is true (indicating a prior malloc
16160** failure on the same database connection) then always return 0.
16161** Hence for a particular database connection, once malloc starts
16162** failing, it fails consistently until mallocFailed is reset.
16163** This is an important assumption.  There are many places in the
16164** code that do things like this:
16165**
16166**         int *a = (int*)sqlite3DbMallocRaw(db, 100);
16167**         int *b = (int*)sqlite3DbMallocRaw(db, 200);
16168**         if( b ) a[10] = 9;
16169**
16170** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
16171** that all prior mallocs (ex: "a") worked too.
16172*/
16173SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
16174  void *p;
16175  assert( db==0 || sqlite3_mutex_held(db->mutex) );
16176#ifndef SQLITE_OMIT_LOOKASIDE
16177  if( db ){
16178    LookasideSlot *pBuf;
16179    if( db->mallocFailed ){
16180      return 0;
16181    }
16182    if( db->lookaside.bEnabled && n<=db->lookaside.sz
16183         && (pBuf = db->lookaside.pFree)!=0 ){
16184      db->lookaside.pFree = pBuf->pNext;
16185      db->lookaside.nOut++;
16186      if( db->lookaside.nOut>db->lookaside.mxOut ){
16187        db->lookaside.mxOut = db->lookaside.nOut;
16188      }
16189      return (void*)pBuf;
16190    }
16191  }
16192#else
16193  if( db && db->mallocFailed ){
16194    return 0;
16195  }
16196#endif
16197  p = sqlite3Malloc(n);
16198  if( !p && db ){
16199    db->mallocFailed = 1;
16200  }
16201  return p;
16202}
16203
16204/*
16205** Resize the block of memory pointed to by p to n bytes. If the
16206** resize fails, set the mallocFailed flag in the connection object.
16207*/
16208SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
16209  void *pNew = 0;
16210  assert( db!=0 );
16211  assert( sqlite3_mutex_held(db->mutex) );
16212  if( db->mallocFailed==0 ){
16213    if( p==0 ){
16214      return sqlite3DbMallocRaw(db, n);
16215    }
16216    if( isLookaside(db, p) ){
16217      if( n<=db->lookaside.sz ){
16218        return p;
16219      }
16220      pNew = sqlite3DbMallocRaw(db, n);
16221      if( pNew ){
16222        memcpy(pNew, p, db->lookaside.sz);
16223        sqlite3DbFree(db, p);
16224      }
16225    }else{
16226      pNew = sqlite3_realloc(p, n);
16227      if( !pNew ){
16228        db->mallocFailed = 1;
16229      }
16230    }
16231  }
16232  return pNew;
16233}
16234
16235/*
16236** Attempt to reallocate p.  If the reallocation fails, then free p
16237** and set the mallocFailed flag in the database connection.
16238*/
16239SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
16240  void *pNew;
16241  pNew = sqlite3DbRealloc(db, p, n);
16242  if( !pNew ){
16243    sqlite3DbFree(db, p);
16244  }
16245  return pNew;
16246}
16247
16248/*
16249** Make a copy of a string in memory obtained from sqliteMalloc(). These
16250** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
16251** is because when memory debugging is turned on, these two functions are
16252** called via macros that record the current file and line number in the
16253** ThreadData structure.
16254*/
16255SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
16256  char *zNew;
16257  size_t n;
16258  if( z==0 ){
16259    return 0;
16260  }
16261  n = sqlite3Strlen30(z) + 1;
16262  assert( (n&0x7fffffff)==n );
16263  zNew = sqlite3DbMallocRaw(db, (int)n);
16264  if( zNew ){
16265    memcpy(zNew, z, n);
16266  }
16267  return zNew;
16268}
16269SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
16270  char *zNew;
16271  if( z==0 ){
16272    return 0;
16273  }
16274  assert( (n&0x7fffffff)==n );
16275  zNew = sqlite3DbMallocRaw(db, n+1);
16276  if( zNew ){
16277    memcpy(zNew, z, n);
16278    zNew[n] = 0;
16279  }
16280  return zNew;
16281}
16282
16283/*
16284** Create a string from the zFromat argument and the va_list that follows.
16285** Store the string in memory obtained from sqliteMalloc() and make *pz
16286** point to that string.
16287*/
16288SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
16289  va_list ap;
16290  char *z;
16291
16292  va_start(ap, zFormat);
16293  z = sqlite3VMPrintf(db, zFormat, ap);
16294  va_end(ap);
16295  sqlite3DbFree(db, *pz);
16296  *pz = z;
16297}
16298
16299
16300/*
16301** This function must be called before exiting any API function (i.e.
16302** returning control to the user) that has called sqlite3_malloc or
16303** sqlite3_realloc.
16304**
16305** The returned value is normally a copy of the second argument to this
16306** function. However, if a malloc() failure has occurred since the previous
16307** invocation SQLITE_NOMEM is returned instead.
16308**
16309** If the first argument, db, is not NULL and a malloc() error has occurred,
16310** then the connection error-code (the value returned by sqlite3_errcode())
16311** is set to SQLITE_NOMEM.
16312*/
16313SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
16314  /* If the db handle is not NULL, then we must hold the connection handle
16315  ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
16316  ** is unsafe, as is the call to sqlite3Error().
16317  */
16318  assert( !db || sqlite3_mutex_held(db->mutex) );
16319  if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
16320    sqlite3Error(db, SQLITE_NOMEM, 0);
16321    db->mallocFailed = 0;
16322    rc = SQLITE_NOMEM;
16323  }
16324  return rc & (db ? db->errMask : 0xff);
16325}
16326
16327/************** End of malloc.c **********************************************/
16328/************** Begin file printf.c ******************************************/
16329/*
16330** The "printf" code that follows dates from the 1980's.  It is in
16331** the public domain.  The original comments are included here for
16332** completeness.  They are very out-of-date but might be useful as
16333** an historical reference.  Most of the "enhancements" have been backed
16334** out so that the functionality is now the same as standard printf().
16335**
16336**************************************************************************
16337**
16338** The following modules is an enhanced replacement for the "printf" subroutines
16339** found in the standard C library.  The following enhancements are
16340** supported:
16341**
16342**      +  Additional functions.  The standard set of "printf" functions
16343**         includes printf, fprintf, sprintf, vprintf, vfprintf, and
16344**         vsprintf.  This module adds the following:
16345**
16346**           *  snprintf -- Works like sprintf, but has an extra argument
16347**                          which is the size of the buffer written to.
16348**
16349**           *  mprintf --  Similar to sprintf.  Writes output to memory
16350**                          obtained from malloc.
16351**
16352**           *  xprintf --  Calls a function to dispose of output.
16353**
16354**           *  nprintf --  No output, but returns the number of characters
16355**                          that would have been output by printf.
16356**
16357**           *  A v- version (ex: vsnprintf) of every function is also
16358**              supplied.
16359**
16360**      +  A few extensions to the formatting notation are supported:
16361**
16362**           *  The "=" flag (similar to "-") causes the output to be
16363**              be centered in the appropriately sized field.
16364**
16365**           *  The %b field outputs an integer in binary notation.
16366**
16367**           *  The %c field now accepts a precision.  The character output
16368**              is repeated by the number of times the precision specifies.
16369**
16370**           *  The %' field works like %c, but takes as its character the
16371**              next character of the format string, instead of the next
16372**              argument.  For example,  printf("%.78'-")  prints 78 minus
16373**              signs, the same as  printf("%.78c",'-').
16374**
16375**      +  When compiled using GCC on a SPARC, this version of printf is
16376**         faster than the library printf for SUN OS 4.1.
16377**
16378**      +  All functions are fully reentrant.
16379**
16380*/
16381
16382/*
16383** Conversion types fall into various categories as defined by the
16384** following enumeration.
16385*/
16386#define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
16387#define etFLOAT       2 /* Floating point.  %f */
16388#define etEXP         3 /* Exponentional notation. %e and %E */
16389#define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
16390#define etSIZE        5 /* Return number of characters processed so far. %n */
16391#define etSTRING      6 /* Strings. %s */
16392#define etDYNSTRING   7 /* Dynamically allocated strings. %z */
16393#define etPERCENT     8 /* Percent symbol. %% */
16394#define etCHARX       9 /* Characters. %c */
16395/* The rest are extensions, not normally found in printf() */
16396#define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
16397#define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
16398                          NULL pointers replaced by SQL NULL.  %Q */
16399#define etTOKEN      12 /* a pointer to a Token structure */
16400#define etSRCLIST    13 /* a pointer to a SrcList */
16401#define etPOINTER    14 /* The %p conversion */
16402#define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
16403#define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
16404
16405#define etINVALID     0 /* Any unrecognized conversion type */
16406
16407
16408/*
16409** An "etByte" is an 8-bit unsigned value.
16410*/
16411typedef unsigned char etByte;
16412
16413/*
16414** Each builtin conversion character (ex: the 'd' in "%d") is described
16415** by an instance of the following structure
16416*/
16417typedef struct et_info {   /* Information about each format field */
16418  char fmttype;            /* The format field code letter */
16419  etByte base;             /* The base for radix conversion */
16420  etByte flags;            /* One or more of FLAG_ constants below */
16421  etByte type;             /* Conversion paradigm */
16422  etByte charset;          /* Offset into aDigits[] of the digits string */
16423  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
16424} et_info;
16425
16426/*
16427** Allowed values for et_info.flags
16428*/
16429#define FLAG_SIGNED  1     /* True if the value to convert is signed */
16430#define FLAG_INTERN  2     /* True if for internal use only */
16431#define FLAG_STRING  4     /* Allow infinity precision */
16432
16433
16434/*
16435** The following table is searched linearly, so it is good to put the
16436** most frequently used conversion types first.
16437*/
16438static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
16439static const char aPrefix[] = "-x0\000X0";
16440static const et_info fmtinfo[] = {
16441  {  'd', 10, 1, etRADIX,      0,  0 },
16442  {  's',  0, 4, etSTRING,     0,  0 },
16443  {  'g',  0, 1, etGENERIC,    30, 0 },
16444  {  'z',  0, 4, etDYNSTRING,  0,  0 },
16445  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
16446  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
16447  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
16448  {  'c',  0, 0, etCHARX,      0,  0 },
16449  {  'o',  8, 0, etRADIX,      0,  2 },
16450  {  'u', 10, 0, etRADIX,      0,  0 },
16451  {  'x', 16, 0, etRADIX,      16, 1 },
16452  {  'X', 16, 0, etRADIX,      0,  4 },
16453#ifndef SQLITE_OMIT_FLOATING_POINT
16454  {  'f',  0, 1, etFLOAT,      0,  0 },
16455  {  'e',  0, 1, etEXP,        30, 0 },
16456  {  'E',  0, 1, etEXP,        14, 0 },
16457  {  'G',  0, 1, etGENERIC,    14, 0 },
16458#endif
16459  {  'i', 10, 1, etRADIX,      0,  0 },
16460  {  'n',  0, 0, etSIZE,       0,  0 },
16461  {  '%',  0, 0, etPERCENT,    0,  0 },
16462  {  'p', 16, 0, etPOINTER,    0,  1 },
16463
16464/* All the rest have the FLAG_INTERN bit set and are thus for internal
16465** use only */
16466  {  'T',  0, 2, etTOKEN,      0,  0 },
16467  {  'S',  0, 2, etSRCLIST,    0,  0 },
16468  {  'r', 10, 3, etORDINAL,    0,  0 },
16469};
16470
16471/*
16472** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
16473** conversions will work.
16474*/
16475#ifndef SQLITE_OMIT_FLOATING_POINT
16476/*
16477** "*val" is a double such that 0.1 <= *val < 10.0
16478** Return the ascii code for the leading digit of *val, then
16479** multiply "*val" by 10.0 to renormalize.
16480**
16481** Example:
16482**     input:     *val = 3.14159
16483**     output:    *val = 1.4159    function return = '3'
16484**
16485** The counter *cnt is incremented each time.  After counter exceeds
16486** 16 (the number of significant digits in a 64-bit float) '0' is
16487** always returned.
16488*/
16489static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
16490  int digit;
16491  LONGDOUBLE_TYPE d;
16492  if( (*cnt)++ >= 16 ) return '0';
16493  digit = (int)*val;
16494  d = digit;
16495  digit += '0';
16496  *val = (*val - d)*10.0;
16497  return (char)digit;
16498}
16499#endif /* SQLITE_OMIT_FLOATING_POINT */
16500
16501/*
16502** Append N space characters to the given string buffer.
16503*/
16504static void appendSpace(StrAccum *pAccum, int N){
16505  static const char zSpaces[] = "                             ";
16506  while( N>=(int)sizeof(zSpaces)-1 ){
16507    sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
16508    N -= sizeof(zSpaces)-1;
16509  }
16510  if( N>0 ){
16511    sqlite3StrAccumAppend(pAccum, zSpaces, N);
16512  }
16513}
16514
16515/*
16516** On machines with a small stack size, you can redefine the
16517** SQLITE_PRINT_BUF_SIZE to be less than 350.
16518*/
16519#ifndef SQLITE_PRINT_BUF_SIZE
16520# if defined(SQLITE_SMALL_STACK)
16521#   define SQLITE_PRINT_BUF_SIZE 50
16522# else
16523#   define SQLITE_PRINT_BUF_SIZE 350
16524# endif
16525#endif
16526#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
16527
16528/*
16529** The root program.  All variations call this core.
16530**
16531** INPUTS:
16532**   func   This is a pointer to a function taking three arguments
16533**            1. A pointer to anything.  Same as the "arg" parameter.
16534**            2. A pointer to the list of characters to be output
16535**               (Note, this list is NOT null terminated.)
16536**            3. An integer number of characters to be output.
16537**               (Note: This number might be zero.)
16538**
16539**   arg    This is the pointer to anything which will be passed as the
16540**          first argument to "func".  Use it for whatever you like.
16541**
16542**   fmt    This is the format string, as in the usual print.
16543**
16544**   ap     This is a pointer to a list of arguments.  Same as in
16545**          vfprint.
16546**
16547** OUTPUTS:
16548**          The return value is the total number of characters sent to
16549**          the function "func".  Returns -1 on a error.
16550**
16551** Note that the order in which automatic variables are declared below
16552** seems to make a big difference in determining how fast this beast
16553** will run.
16554*/
16555SQLITE_PRIVATE void sqlite3VXPrintf(
16556  StrAccum *pAccum,                  /* Accumulate results here */
16557  int useExtended,                   /* Allow extended %-conversions */
16558  const char *fmt,                   /* Format string */
16559  va_list ap                         /* arguments */
16560){
16561  int c;                     /* Next character in the format string */
16562  char *bufpt;               /* Pointer to the conversion buffer */
16563  int precision;             /* Precision of the current field */
16564  int length;                /* Length of the field */
16565  int idx;                   /* A general purpose loop counter */
16566  int width;                 /* Width of the current field */
16567  etByte flag_leftjustify;   /* True if "-" flag is present */
16568  etByte flag_plussign;      /* True if "+" flag is present */
16569  etByte flag_blanksign;     /* True if " " flag is present */
16570  etByte flag_alternateform; /* True if "#" flag is present */
16571  etByte flag_altform2;      /* True if "!" flag is present */
16572  etByte flag_zeropad;       /* True if field width constant starts with zero */
16573  etByte flag_long;          /* True if "l" flag is present */
16574  etByte flag_longlong;      /* True if the "ll" flag is present */
16575  etByte done;               /* Loop termination flag */
16576  sqlite_uint64 longvalue;   /* Value for integer types */
16577  LONGDOUBLE_TYPE realvalue; /* Value for real types */
16578  const et_info *infop;      /* Pointer to the appropriate info structure */
16579  char buf[etBUFSIZE];       /* Conversion buffer */
16580  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
16581  etByte xtype = 0;          /* Conversion paradigm */
16582  char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
16583#ifndef SQLITE_OMIT_FLOATING_POINT
16584  int  exp, e2;              /* exponent of real numbers */
16585  double rounder;            /* Used for rounding floating point values */
16586  etByte flag_dp;            /* True if decimal point should be shown */
16587  etByte flag_rtz;           /* True if trailing zeros should be removed */
16588  etByte flag_exp;           /* True to force display of the exponent */
16589  int nsd;                   /* Number of significant digits returned */
16590#endif
16591
16592  length = 0;
16593  bufpt = 0;
16594  for(; (c=(*fmt))!=0; ++fmt){
16595    if( c!='%' ){
16596      int amt;
16597      bufpt = (char *)fmt;
16598      amt = 1;
16599      while( (c=(*++fmt))!='%' && c!=0 ) amt++;
16600      sqlite3StrAccumAppend(pAccum, bufpt, amt);
16601      if( c==0 ) break;
16602    }
16603    if( (c=(*++fmt))==0 ){
16604      sqlite3StrAccumAppend(pAccum, "%", 1);
16605      break;
16606    }
16607    /* Find out what flags are present */
16608    flag_leftjustify = flag_plussign = flag_blanksign =
16609     flag_alternateform = flag_altform2 = flag_zeropad = 0;
16610    done = 0;
16611    do{
16612      switch( c ){
16613        case '-':   flag_leftjustify = 1;     break;
16614        case '+':   flag_plussign = 1;        break;
16615        case ' ':   flag_blanksign = 1;       break;
16616        case '#':   flag_alternateform = 1;   break;
16617        case '!':   flag_altform2 = 1;        break;
16618        case '0':   flag_zeropad = 1;         break;
16619        default:    done = 1;                 break;
16620      }
16621    }while( !done && (c=(*++fmt))!=0 );
16622    /* Get the field width */
16623    width = 0;
16624    if( c=='*' ){
16625      width = va_arg(ap,int);
16626      if( width<0 ){
16627        flag_leftjustify = 1;
16628        width = -width;
16629      }
16630      c = *++fmt;
16631    }else{
16632      while( c>='0' && c<='9' ){
16633        width = width*10 + c - '0';
16634        c = *++fmt;
16635      }
16636    }
16637    if( width > etBUFSIZE-10 ){
16638      width = etBUFSIZE-10;
16639    }
16640    /* Get the precision */
16641    if( c=='.' ){
16642      precision = 0;
16643      c = *++fmt;
16644      if( c=='*' ){
16645        precision = va_arg(ap,int);
16646        if( precision<0 ) precision = -precision;
16647        c = *++fmt;
16648      }else{
16649        while( c>='0' && c<='9' ){
16650          precision = precision*10 + c - '0';
16651          c = *++fmt;
16652        }
16653      }
16654    }else{
16655      precision = -1;
16656    }
16657    /* Get the conversion type modifier */
16658    if( c=='l' ){
16659      flag_long = 1;
16660      c = *++fmt;
16661      if( c=='l' ){
16662        flag_longlong = 1;
16663        c = *++fmt;
16664      }else{
16665        flag_longlong = 0;
16666      }
16667    }else{
16668      flag_long = flag_longlong = 0;
16669    }
16670    /* Fetch the info entry for the field */
16671    infop = &fmtinfo[0];
16672    xtype = etINVALID;
16673    for(idx=0; idx<ArraySize(fmtinfo); idx++){
16674      if( c==fmtinfo[idx].fmttype ){
16675        infop = &fmtinfo[idx];
16676        if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
16677          xtype = infop->type;
16678        }else{
16679          return;
16680        }
16681        break;
16682      }
16683    }
16684    zExtra = 0;
16685
16686
16687    /* Limit the precision to prevent overflowing buf[] during conversion */
16688    if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
16689      precision = etBUFSIZE-40;
16690    }
16691
16692    /*
16693    ** At this point, variables are initialized as follows:
16694    **
16695    **   flag_alternateform          TRUE if a '#' is present.
16696    **   flag_altform2               TRUE if a '!' is present.
16697    **   flag_plussign               TRUE if a '+' is present.
16698    **   flag_leftjustify            TRUE if a '-' is present or if the
16699    **                               field width was negative.
16700    **   flag_zeropad                TRUE if the width began with 0.
16701    **   flag_long                   TRUE if the letter 'l' (ell) prefixed
16702    **                               the conversion character.
16703    **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
16704    **                               the conversion character.
16705    **   flag_blanksign              TRUE if a ' ' is present.
16706    **   width                       The specified field width.  This is
16707    **                               always non-negative.  Zero is the default.
16708    **   precision                   The specified precision.  The default
16709    **                               is -1.
16710    **   xtype                       The class of the conversion.
16711    **   infop                       Pointer to the appropriate info struct.
16712    */
16713    switch( xtype ){
16714      case etPOINTER:
16715        flag_longlong = sizeof(char*)==sizeof(i64);
16716        flag_long = sizeof(char*)==sizeof(long int);
16717        /* Fall through into the next case */
16718      case etORDINAL:
16719      case etRADIX:
16720        if( infop->flags & FLAG_SIGNED ){
16721          i64 v;
16722          if( flag_longlong ){
16723            v = va_arg(ap,i64);
16724          }else if( flag_long ){
16725            v = va_arg(ap,long int);
16726          }else{
16727            v = va_arg(ap,int);
16728          }
16729          if( v<0 ){
16730            longvalue = -v;
16731            prefix = '-';
16732          }else{
16733            longvalue = v;
16734            if( flag_plussign )        prefix = '+';
16735            else if( flag_blanksign )  prefix = ' ';
16736            else                       prefix = 0;
16737          }
16738        }else{
16739          if( flag_longlong ){
16740            longvalue = va_arg(ap,u64);
16741          }else if( flag_long ){
16742            longvalue = va_arg(ap,unsigned long int);
16743          }else{
16744            longvalue = va_arg(ap,unsigned int);
16745          }
16746          prefix = 0;
16747        }
16748        if( longvalue==0 ) flag_alternateform = 0;
16749        if( flag_zeropad && precision<width-(prefix!=0) ){
16750          precision = width-(prefix!=0);
16751        }
16752        bufpt = &buf[etBUFSIZE-1];
16753        if( xtype==etORDINAL ){
16754          static const char zOrd[] = "thstndrd";
16755          int x = (int)(longvalue % 10);
16756          if( x>=4 || (longvalue/10)%10==1 ){
16757            x = 0;
16758          }
16759          buf[etBUFSIZE-3] = zOrd[x*2];
16760          buf[etBUFSIZE-2] = zOrd[x*2+1];
16761          bufpt -= 2;
16762        }
16763        {
16764          register const char *cset;      /* Use registers for speed */
16765          register int base;
16766          cset = &aDigits[infop->charset];
16767          base = infop->base;
16768          do{                                           /* Convert to ascii */
16769            *(--bufpt) = cset[longvalue%base];
16770            longvalue = longvalue/base;
16771          }while( longvalue>0 );
16772        }
16773        length = (int)(&buf[etBUFSIZE-1]-bufpt);
16774        for(idx=precision-length; idx>0; idx--){
16775          *(--bufpt) = '0';                             /* Zero pad */
16776        }
16777        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
16778        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
16779          const char *pre;
16780          char x;
16781          pre = &aPrefix[infop->prefix];
16782          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
16783        }
16784        length = (int)(&buf[etBUFSIZE-1]-bufpt);
16785        break;
16786      case etFLOAT:
16787      case etEXP:
16788      case etGENERIC:
16789        realvalue = va_arg(ap,double);
16790#ifndef SQLITE_OMIT_FLOATING_POINT
16791        if( precision<0 ) precision = 6;         /* Set default precision */
16792        if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
16793        if( realvalue<0.0 ){
16794          realvalue = -realvalue;
16795          prefix = '-';
16796        }else{
16797          if( flag_plussign )          prefix = '+';
16798          else if( flag_blanksign )    prefix = ' ';
16799          else                         prefix = 0;
16800        }
16801        if( xtype==etGENERIC && precision>0 ) precision--;
16802#if 0
16803        /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
16804        for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
16805#else
16806        /* It makes more sense to use 0.5 */
16807        for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
16808#endif
16809        if( xtype==etFLOAT ) realvalue += rounder;
16810        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
16811        exp = 0;
16812        if( sqlite3IsNaN((double)realvalue) ){
16813          bufpt = "NaN";
16814          length = 3;
16815          break;
16816        }
16817        if( realvalue>0.0 ){
16818          while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
16819          while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
16820          while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
16821          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
16822          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
16823          if( exp>350 ){
16824            if( prefix=='-' ){
16825              bufpt = "-Inf";
16826            }else if( prefix=='+' ){
16827              bufpt = "+Inf";
16828            }else{
16829              bufpt = "Inf";
16830            }
16831            length = sqlite3Strlen30(bufpt);
16832            break;
16833          }
16834        }
16835        bufpt = buf;
16836        /*
16837        ** If the field type is etGENERIC, then convert to either etEXP
16838        ** or etFLOAT, as appropriate.
16839        */
16840        flag_exp = xtype==etEXP;
16841        if( xtype!=etFLOAT ){
16842          realvalue += rounder;
16843          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
16844        }
16845        if( xtype==etGENERIC ){
16846          flag_rtz = !flag_alternateform;
16847          if( exp<-4 || exp>precision ){
16848            xtype = etEXP;
16849          }else{
16850            precision = precision - exp;
16851            xtype = etFLOAT;
16852          }
16853        }else{
16854          flag_rtz = 0;
16855        }
16856        if( xtype==etEXP ){
16857          e2 = 0;
16858        }else{
16859          e2 = exp;
16860        }
16861        nsd = 0;
16862        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
16863        /* The sign in front of the number */
16864        if( prefix ){
16865          *(bufpt++) = prefix;
16866        }
16867        /* Digits prior to the decimal point */
16868        if( e2<0 ){
16869          *(bufpt++) = '0';
16870        }else{
16871          for(; e2>=0; e2--){
16872            *(bufpt++) = et_getdigit(&realvalue,&nsd);
16873          }
16874        }
16875        /* The decimal point */
16876        if( flag_dp ){
16877          *(bufpt++) = '.';
16878        }
16879        /* "0" digits after the decimal point but before the first
16880        ** significant digit of the number */
16881        for(e2++; e2<0; precision--, e2++){
16882          assert( precision>0 );
16883          *(bufpt++) = '0';
16884        }
16885        /* Significant digits after the decimal point */
16886        while( (precision--)>0 ){
16887          *(bufpt++) = et_getdigit(&realvalue,&nsd);
16888        }
16889        /* Remove trailing zeros and the "." if no digits follow the "." */
16890        if( flag_rtz && flag_dp ){
16891          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
16892          assert( bufpt>buf );
16893          if( bufpt[-1]=='.' ){
16894            if( flag_altform2 ){
16895              *(bufpt++) = '0';
16896            }else{
16897              *(--bufpt) = 0;
16898            }
16899          }
16900        }
16901        /* Add the "eNNN" suffix */
16902        if( flag_exp || xtype==etEXP ){
16903          *(bufpt++) = aDigits[infop->charset];
16904          if( exp<0 ){
16905            *(bufpt++) = '-'; exp = -exp;
16906          }else{
16907            *(bufpt++) = '+';
16908          }
16909          if( exp>=100 ){
16910            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
16911            exp %= 100;
16912          }
16913          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
16914          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
16915        }
16916        *bufpt = 0;
16917
16918        /* The converted number is in buf[] and zero terminated. Output it.
16919        ** Note that the number is in the usual order, not reversed as with
16920        ** integer conversions. */
16921        length = (int)(bufpt-buf);
16922        bufpt = buf;
16923
16924        /* Special case:  Add leading zeros if the flag_zeropad flag is
16925        ** set and we are not left justified */
16926        if( flag_zeropad && !flag_leftjustify && length < width){
16927          int i;
16928          int nPad = width - length;
16929          for(i=width; i>=nPad; i--){
16930            bufpt[i] = bufpt[i-nPad];
16931          }
16932          i = prefix!=0;
16933          while( nPad-- ) bufpt[i++] = '0';
16934          length = width;
16935        }
16936#endif
16937        break;
16938      case etSIZE:
16939        *(va_arg(ap,int*)) = pAccum->nChar;
16940        length = width = 0;
16941        break;
16942      case etPERCENT:
16943        buf[0] = '%';
16944        bufpt = buf;
16945        length = 1;
16946        break;
16947      case etCHARX:
16948        c = va_arg(ap,int);
16949        buf[0] = (char)c;
16950        if( precision>=0 ){
16951          for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
16952          length = precision;
16953        }else{
16954          length =1;
16955        }
16956        bufpt = buf;
16957        break;
16958      case etSTRING:
16959      case etDYNSTRING:
16960        bufpt = va_arg(ap,char*);
16961        if( bufpt==0 ){
16962          bufpt = "";
16963        }else if( xtype==etDYNSTRING ){
16964          zExtra = bufpt;
16965        }
16966        if( precision>=0 ){
16967          for(length=0; length<precision && bufpt[length]; length++){}
16968        }else{
16969          length = sqlite3Strlen30(bufpt);
16970        }
16971        break;
16972      case etSQLESCAPE:
16973      case etSQLESCAPE2:
16974      case etSQLESCAPE3: {
16975        int i, j, k, n, isnull;
16976        int needQuote;
16977        char ch;
16978        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
16979        char *escarg = va_arg(ap,char*);
16980        isnull = escarg==0;
16981        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
16982        k = precision;
16983        for(i=n=0; (ch=escarg[i])!=0 && k!=0; i++, k--){
16984          if( ch==q )  n++;
16985        }
16986        needQuote = !isnull && xtype==etSQLESCAPE2;
16987        n += i + 1 + needQuote*2;
16988        if( n>etBUFSIZE ){
16989          bufpt = zExtra = sqlite3Malloc( n );
16990          if( bufpt==0 ){
16991            pAccum->mallocFailed = 1;
16992            return;
16993          }
16994        }else{
16995          bufpt = buf;
16996        }
16997        j = 0;
16998        if( needQuote ) bufpt[j++] = q;
16999        k = i;
17000        for(i=0; i<k; i++){
17001          bufpt[j++] = ch = escarg[i];
17002          if( ch==q ) bufpt[j++] = ch;
17003        }
17004        if( needQuote ) bufpt[j++] = q;
17005        bufpt[j] = 0;
17006        length = j;
17007        /* The precision in %q and %Q means how many input characters to
17008        ** consume, not the length of the output...
17009        ** if( precision>=0 && precision<length ) length = precision; */
17010        break;
17011      }
17012      case etTOKEN: {
17013        Token *pToken = va_arg(ap, Token*);
17014        if( pToken ){
17015          sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
17016        }
17017        length = width = 0;
17018        break;
17019      }
17020      case etSRCLIST: {
17021        SrcList *pSrc = va_arg(ap, SrcList*);
17022        int k = va_arg(ap, int);
17023        struct SrcList_item *pItem = &pSrc->a[k];
17024        assert( k>=0 && k<pSrc->nSrc );
17025        if( pItem->zDatabase ){
17026          sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
17027          sqlite3StrAccumAppend(pAccum, ".", 1);
17028        }
17029        sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
17030        length = width = 0;
17031        break;
17032      }
17033      default: {
17034        assert( xtype==etINVALID );
17035        return;
17036      }
17037    }/* End switch over the format type */
17038    /*
17039    ** The text of the conversion is pointed to by "bufpt" and is
17040    ** "length" characters long.  The field width is "width".  Do
17041    ** the output.
17042    */
17043    if( !flag_leftjustify ){
17044      register int nspace;
17045      nspace = width-length;
17046      if( nspace>0 ){
17047        appendSpace(pAccum, nspace);
17048      }
17049    }
17050    if( length>0 ){
17051      sqlite3StrAccumAppend(pAccum, bufpt, length);
17052    }
17053    if( flag_leftjustify ){
17054      register int nspace;
17055      nspace = width-length;
17056      if( nspace>0 ){
17057        appendSpace(pAccum, nspace);
17058      }
17059    }
17060    if( zExtra ){
17061      sqlite3_free(zExtra);
17062    }
17063  }/* End for loop over the format string */
17064} /* End of function */
17065
17066/*
17067** Append N bytes of text from z to the StrAccum object.
17068*/
17069SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
17070  assert( z!=0 || N==0 );
17071  if( p->tooBig | p->mallocFailed ){
17072    testcase(p->tooBig);
17073    testcase(p->mallocFailed);
17074    return;
17075  }
17076  if( N<0 ){
17077    N = sqlite3Strlen30(z);
17078  }
17079  if( N==0 || NEVER(z==0) ){
17080    return;
17081  }
17082  if( p->nChar+N >= p->nAlloc ){
17083    char *zNew;
17084    if( !p->useMalloc ){
17085      p->tooBig = 1;
17086      N = p->nAlloc - p->nChar - 1;
17087      if( N<=0 ){
17088        return;
17089      }
17090    }else{
17091      i64 szNew = p->nChar;
17092      szNew += N + 1;
17093      if( szNew > p->mxAlloc ){
17094        sqlite3StrAccumReset(p);
17095        p->tooBig = 1;
17096        return;
17097      }else{
17098        p->nAlloc = (int)szNew;
17099      }
17100      zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
17101      if( zNew ){
17102        memcpy(zNew, p->zText, p->nChar);
17103        sqlite3StrAccumReset(p);
17104        p->zText = zNew;
17105      }else{
17106        p->mallocFailed = 1;
17107        sqlite3StrAccumReset(p);
17108        return;
17109      }
17110    }
17111  }
17112  memcpy(&p->zText[p->nChar], z, N);
17113  p->nChar += N;
17114}
17115
17116/*
17117** Finish off a string by making sure it is zero-terminated.
17118** Return a pointer to the resulting string.  Return a NULL
17119** pointer if any kind of error was encountered.
17120*/
17121SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
17122  if( p->zText ){
17123    p->zText[p->nChar] = 0;
17124    if( p->useMalloc && p->zText==p->zBase ){
17125      p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
17126      if( p->zText ){
17127        memcpy(p->zText, p->zBase, p->nChar+1);
17128      }else{
17129        p->mallocFailed = 1;
17130      }
17131    }
17132  }
17133  return p->zText;
17134}
17135
17136/*
17137** Reset an StrAccum string.  Reclaim all malloced memory.
17138*/
17139SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
17140  if( p->zText!=p->zBase ){
17141    sqlite3DbFree(p->db, p->zText);
17142  }
17143  p->zText = 0;
17144}
17145
17146/*
17147** Initialize a string accumulator
17148*/
17149SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
17150  p->zText = p->zBase = zBase;
17151  p->db = 0;
17152  p->nChar = 0;
17153  p->nAlloc = n;
17154  p->mxAlloc = mx;
17155  p->useMalloc = 1;
17156  p->tooBig = 0;
17157  p->mallocFailed = 0;
17158}
17159
17160/*
17161** Print into memory obtained from sqliteMalloc().  Use the internal
17162** %-conversion extensions.
17163*/
17164SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
17165  char *z;
17166  char zBase[SQLITE_PRINT_BUF_SIZE];
17167  StrAccum acc;
17168  assert( db!=0 );
17169  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
17170                      db->aLimit[SQLITE_LIMIT_LENGTH]);
17171  acc.db = db;
17172  sqlite3VXPrintf(&acc, 1, zFormat, ap);
17173  z = sqlite3StrAccumFinish(&acc);
17174  if( acc.mallocFailed ){
17175    db->mallocFailed = 1;
17176  }
17177  return z;
17178}
17179
17180/*
17181** Print into memory obtained from sqliteMalloc().  Use the internal
17182** %-conversion extensions.
17183*/
17184SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
17185  va_list ap;
17186  char *z;
17187  va_start(ap, zFormat);
17188  z = sqlite3VMPrintf(db, zFormat, ap);
17189  va_end(ap);
17190  return z;
17191}
17192
17193/*
17194** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
17195** the string and before returnning.  This routine is intended to be used
17196** to modify an existing string.  For example:
17197**
17198**       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
17199**
17200*/
17201SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
17202  va_list ap;
17203  char *z;
17204  va_start(ap, zFormat);
17205  z = sqlite3VMPrintf(db, zFormat, ap);
17206  va_end(ap);
17207  sqlite3DbFree(db, zStr);
17208  return z;
17209}
17210
17211/*
17212** Print into memory obtained from sqlite3_malloc().  Omit the internal
17213** %-conversion extensions.
17214*/
17215SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
17216  char *z;
17217  char zBase[SQLITE_PRINT_BUF_SIZE];
17218  StrAccum acc;
17219#ifndef SQLITE_OMIT_AUTOINIT
17220  if( sqlite3_initialize() ) return 0;
17221#endif
17222  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
17223  sqlite3VXPrintf(&acc, 0, zFormat, ap);
17224  z = sqlite3StrAccumFinish(&acc);
17225  return z;
17226}
17227
17228/*
17229** Print into memory obtained from sqlite3_malloc()().  Omit the internal
17230** %-conversion extensions.
17231*/
17232SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
17233  va_list ap;
17234  char *z;
17235#ifndef SQLITE_OMIT_AUTOINIT
17236  if( sqlite3_initialize() ) return 0;
17237#endif
17238  va_start(ap, zFormat);
17239  z = sqlite3_vmprintf(zFormat, ap);
17240  va_end(ap);
17241  return z;
17242}
17243
17244/*
17245** sqlite3_snprintf() works like snprintf() except that it ignores the
17246** current locale settings.  This is important for SQLite because we
17247** are not able to use a "," as the decimal point in place of "." as
17248** specified by some locales.
17249*/
17250SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
17251  char *z;
17252  va_list ap;
17253  StrAccum acc;
17254
17255  if( n<=0 ){
17256    return zBuf;
17257  }
17258  sqlite3StrAccumInit(&acc, zBuf, n, 0);
17259  acc.useMalloc = 0;
17260  va_start(ap,zFormat);
17261  sqlite3VXPrintf(&acc, 0, zFormat, ap);
17262  va_end(ap);
17263  z = sqlite3StrAccumFinish(&acc);
17264  return z;
17265}
17266
17267/*
17268** This is the routine that actually formats the sqlite3_log() message.
17269** We house it in a separate routine from sqlite3_log() to avoid using
17270** stack space on small-stack systems when logging is disabled.
17271**
17272** sqlite3_log() must render into a static buffer.  It cannot dynamically
17273** allocate memory because it might be called while the memory allocator
17274** mutex is held.
17275*/
17276static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
17277  StrAccum acc;                           /* String accumulator */
17278#ifdef SQLITE_SMALL_STACK
17279  char zMsg[150];                         /* Complete log message */
17280#else
17281  char zMsg[400];                         /* Complete log message */
17282#endif
17283
17284  sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
17285  acc.useMalloc = 0;
17286  sqlite3VXPrintf(&acc, 0, zFormat, ap);
17287  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
17288                           sqlite3StrAccumFinish(&acc));
17289}
17290
17291/*
17292** Format and write a message to the log if logging is enabled.
17293*/
17294SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
17295  va_list ap;                             /* Vararg list */
17296  if( sqlite3GlobalConfig.xLog ){
17297    va_start(ap, zFormat);
17298    renderLogMsg(iErrCode, zFormat, ap);
17299    va_end(ap);
17300  }
17301}
17302
17303#if defined(SQLITE_DEBUG)
17304/*
17305** A version of printf() that understands %lld.  Used for debugging.
17306** The printf() built into some versions of windows does not understand %lld
17307** and segfaults if you give it a long long int.
17308*/
17309SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
17310  va_list ap;
17311  StrAccum acc;
17312  char zBuf[500];
17313  sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
17314  acc.useMalloc = 0;
17315  va_start(ap,zFormat);
17316  sqlite3VXPrintf(&acc, 0, zFormat, ap);
17317  va_end(ap);
17318  sqlite3StrAccumFinish(&acc);
17319  fprintf(stdout,"%s", zBuf);
17320  fflush(stdout);
17321}
17322#endif
17323
17324#ifndef SQLITE_OMIT_TRACE
17325/*
17326** variable-argument wrapper around sqlite3VXPrintf().
17327*/
17328SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
17329  va_list ap;
17330  va_start(ap,zFormat);
17331  sqlite3VXPrintf(p, 1, zFormat, ap);
17332  va_end(ap);
17333}
17334#endif
17335
17336/************** End of printf.c **********************************************/
17337/************** Begin file random.c ******************************************/
17338/*
17339** 2001 September 15
17340**
17341** The author disclaims copyright to this source code.  In place of
17342** a legal notice, here is a blessing:
17343**
17344**    May you do good and not evil.
17345**    May you find forgiveness for yourself and forgive others.
17346**    May you share freely, never taking more than you give.
17347**
17348*************************************************************************
17349** This file contains code to implement a pseudo-random number
17350** generator (PRNG) for SQLite.
17351**
17352** Random numbers are used by some of the database backends in order
17353** to generate random integer keys for tables or random filenames.
17354*/
17355
17356
17357/* All threads share a single random number generator.
17358** This structure is the current state of the generator.
17359*/
17360static SQLITE_WSD struct sqlite3PrngType {
17361  unsigned char isInit;          /* True if initialized */
17362  unsigned char i, j;            /* State variables */
17363  unsigned char s[256];          /* State variables */
17364} sqlite3Prng;
17365
17366/*
17367** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
17368** must be held while executing this routine.
17369**
17370** Why not just use a library random generator like lrand48() for this?
17371** Because the OP_NewRowid opcode in the VDBE depends on having a very
17372** good source of random numbers.  The lrand48() library function may
17373** well be good enough.  But maybe not.  Or maybe lrand48() has some
17374** subtle problems on some systems that could cause problems.  It is hard
17375** to know.  To minimize the risk of problems due to bad lrand48()
17376** implementations, SQLite uses this random number generator based
17377** on RC4, which we know works very well.
17378**
17379** (Later):  Actually, OP_NewRowid does not depend on a good source of
17380** randomness any more.  But we will leave this code in all the same.
17381*/
17382static u8 randomByte(void){
17383  unsigned char t;
17384
17385
17386  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
17387  ** state vector.  If writable static data is unsupported on the target,
17388  ** we have to locate the state vector at run-time.  In the more common
17389  ** case where writable static data is supported, wsdPrng can refer directly
17390  ** to the "sqlite3Prng" state vector declared above.
17391  */
17392#ifdef SQLITE_OMIT_WSD
17393  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
17394# define wsdPrng p[0]
17395#else
17396# define wsdPrng sqlite3Prng
17397#endif
17398
17399
17400  /* Initialize the state of the random number generator once,
17401  ** the first time this routine is called.  The seed value does
17402  ** not need to contain a lot of randomness since we are not
17403  ** trying to do secure encryption or anything like that...
17404  **
17405  ** Nothing in this file or anywhere else in SQLite does any kind of
17406  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
17407  ** number generator) not as an encryption device.
17408  */
17409  if( !wsdPrng.isInit ){
17410    int i;
17411    char k[256];
17412    wsdPrng.j = 0;
17413    wsdPrng.i = 0;
17414    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
17415    for(i=0; i<256; i++){
17416      wsdPrng.s[i] = (u8)i;
17417    }
17418    for(i=0; i<256; i++){
17419      wsdPrng.j += wsdPrng.s[i] + k[i];
17420      t = wsdPrng.s[wsdPrng.j];
17421      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
17422      wsdPrng.s[i] = t;
17423    }
17424    wsdPrng.isInit = 1;
17425  }
17426
17427  /* Generate and return single random byte
17428  */
17429  wsdPrng.i++;
17430  t = wsdPrng.s[wsdPrng.i];
17431  wsdPrng.j += t;
17432  wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
17433  wsdPrng.s[wsdPrng.j] = t;
17434  t += wsdPrng.s[wsdPrng.i];
17435  return wsdPrng.s[t];
17436}
17437
17438/*
17439** Return N random bytes.
17440*/
17441SQLITE_API void sqlite3_randomness(int N, void *pBuf){
17442  unsigned char *zBuf = pBuf;
17443#if SQLITE_THREADSAFE
17444  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
17445#endif
17446  sqlite3_mutex_enter(mutex);
17447  while( N-- ){
17448    *(zBuf++) = randomByte();
17449  }
17450  sqlite3_mutex_leave(mutex);
17451}
17452
17453#ifndef SQLITE_OMIT_BUILTIN_TEST
17454/*
17455** For testing purposes, we sometimes want to preserve the state of
17456** PRNG and restore the PRNG to its saved state at a later time, or
17457** to reset the PRNG to its initial state.  These routines accomplish
17458** those tasks.
17459**
17460** The sqlite3_test_control() interface calls these routines to
17461** control the PRNG.
17462*/
17463static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
17464SQLITE_PRIVATE void sqlite3PrngSaveState(void){
17465  memcpy(
17466    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
17467    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
17468    sizeof(sqlite3Prng)
17469  );
17470}
17471SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
17472  memcpy(
17473    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
17474    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
17475    sizeof(sqlite3Prng)
17476  );
17477}
17478SQLITE_PRIVATE void sqlite3PrngResetState(void){
17479  GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
17480}
17481#endif /* SQLITE_OMIT_BUILTIN_TEST */
17482
17483/************** End of random.c **********************************************/
17484/************** Begin file utf.c *********************************************/
17485/*
17486** 2004 April 13
17487**
17488** The author disclaims copyright to this source code.  In place of
17489** a legal notice, here is a blessing:
17490**
17491**    May you do good and not evil.
17492**    May you find forgiveness for yourself and forgive others.
17493**    May you share freely, never taking more than you give.
17494**
17495*************************************************************************
17496** This file contains routines used to translate between UTF-8,
17497** UTF-16, UTF-16BE, and UTF-16LE.
17498**
17499** Notes on UTF-8:
17500**
17501**   Byte-0    Byte-1    Byte-2    Byte-3    Value
17502**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
17503**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
17504**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
17505**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
17506**
17507**
17508** Notes on UTF-16:  (with wwww+1==uuuuu)
17509**
17510**      Word-0               Word-1          Value
17511**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
17512**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
17513**
17514**
17515** BOM or Byte Order Mark:
17516**     0xff 0xfe   little-endian utf-16 follows
17517**     0xfe 0xff   big-endian utf-16 follows
17518**
17519*/
17520/************** Include vdbeInt.h in the middle of utf.c *********************/
17521/************** Begin file vdbeInt.h *****************************************/
17522/*
17523** 2003 September 6
17524**
17525** The author disclaims copyright to this source code.  In place of
17526** a legal notice, here is a blessing:
17527**
17528**    May you do good and not evil.
17529**    May you find forgiveness for yourself and forgive others.
17530**    May you share freely, never taking more than you give.
17531**
17532*************************************************************************
17533** This is the header file for information that is private to the
17534** VDBE.  This information used to all be at the top of the single
17535** source code file "vdbe.c".  When that file became too big (over
17536** 6000 lines long) it was split up into several smaller files and
17537** this header information was factored out.
17538*/
17539#ifndef _VDBEINT_H_
17540#define _VDBEINT_H_
17541
17542/*
17543** SQL is translated into a sequence of instructions to be
17544** executed by a virtual machine.  Each instruction is an instance
17545** of the following structure.
17546*/
17547typedef struct VdbeOp Op;
17548
17549/*
17550** Boolean values
17551*/
17552typedef unsigned char Bool;
17553
17554/*
17555** A cursor is a pointer into a single BTree within a database file.
17556** The cursor can seek to a BTree entry with a particular key, or
17557** loop over all entries of the Btree.  You can also insert new BTree
17558** entries or retrieve the key or data from the entry that the cursor
17559** is currently pointing to.
17560**
17561** Every cursor that the virtual machine has open is represented by an
17562** instance of the following structure.
17563**
17564** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is
17565** really a single row that represents the NEW or OLD pseudo-table of
17566** a row trigger.  The data for the row is stored in VdbeCursor.pData and
17567** the rowid is in VdbeCursor.iKey.
17568*/
17569struct VdbeCursor {
17570  BtCursor *pCursor;    /* The cursor structure of the backend */
17571  int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
17572  i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
17573  Bool zeroed;          /* True if zeroed out and ready for reuse */
17574  Bool rowidIsValid;    /* True if lastRowid is valid */
17575  Bool atFirst;         /* True if pointing to first entry */
17576  Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
17577  Bool nullRow;         /* True if pointing to a row with no data */
17578  Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
17579  Bool isTable;         /* True if a table requiring integer keys */
17580  Bool isIndex;         /* True if an index containing keys only - no data */
17581  i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
17582  Btree *pBt;           /* Separate file holding temporary table */
17583  int pseudoTableReg;   /* Register holding pseudotable content. */
17584  KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
17585  int nField;           /* Number of fields in the header */
17586  i64 seqCount;         /* Sequence counter */
17587  sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
17588  const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
17589
17590  /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
17591  ** OP_IsUnique opcode on this cursor. */
17592  int seekResult;
17593
17594  /* Cached information about the header for the data record that the
17595  ** cursor is currently pointing to.  Only valid if cacheStatus matches
17596  ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
17597  ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
17598  ** the cache is out of date.
17599  **
17600  ** aRow might point to (ephemeral) data for the current row, or it might
17601  ** be NULL.
17602  */
17603  u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
17604  int payloadSize;      /* Total number of bytes in the record */
17605  u32 *aType;           /* Type values for all entries in the record */
17606  u32 *aOffset;         /* Cached offsets to the start of each columns data */
17607  u8 *aRow;             /* Data for the current row, if all on one page */
17608};
17609typedef struct VdbeCursor VdbeCursor;
17610
17611/*
17612** When a sub-program is executed (OP_Program), a structure of this type
17613** is allocated to store the current value of the program counter, as
17614** well as the current memory cell array and various other frame specific
17615** values stored in the Vdbe struct. When the sub-program is finished,
17616** these values are copied back to the Vdbe from the VdbeFrame structure,
17617** restoring the state of the VM to as it was before the sub-program
17618** began executing.
17619**
17620** Frames are stored in a linked list headed at Vdbe.pParent. Vdbe.pParent
17621** is the parent of the current frame, or zero if the current frame
17622** is the main Vdbe program.
17623*/
17624typedef struct VdbeFrame VdbeFrame;
17625struct VdbeFrame {
17626  Vdbe *v;                /* VM this frame belongs to */
17627  int pc;                 /* Program Counter */
17628  Op *aOp;                /* Program instructions */
17629  int nOp;                /* Size of aOp array */
17630  Mem *aMem;              /* Array of memory cells */
17631  int nMem;               /* Number of entries in aMem */
17632  VdbeCursor **apCsr;     /* Element of Vdbe cursors */
17633  u16 nCursor;            /* Number of entries in apCsr */
17634  void *token;            /* Copy of SubProgram.token */
17635  int nChildMem;          /* Number of memory cells for child frame */
17636  int nChildCsr;          /* Number of cursors for child frame */
17637  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
17638  int nChange;            /* Statement changes (Vdbe.nChanges)     */
17639  VdbeFrame *pParent;     /* Parent of this frame */
17640};
17641
17642#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
17643
17644/*
17645** A value for VdbeCursor.cacheValid that means the cache is always invalid.
17646*/
17647#define CACHE_STALE 0
17648
17649/*
17650** Internally, the vdbe manipulates nearly all SQL values as Mem
17651** structures. Each Mem struct may cache multiple representations (string,
17652** integer etc.) of the same value.  A value (and therefore Mem structure)
17653** has the following properties:
17654**
17655** Each value has a manifest type. The manifest type of the value stored
17656** in a Mem struct is returned by the MemType(Mem*) macro. The type is
17657** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
17658** SQLITE_BLOB.
17659*/
17660struct Mem {
17661  union {
17662    i64 i;              /* Integer value. */
17663    int nZero;          /* Used when bit MEM_Zero is set in flags */
17664    FuncDef *pDef;      /* Used only when flags==MEM_Agg */
17665    RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
17666    VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
17667  } u;
17668  double r;           /* Real value */
17669  sqlite3 *db;        /* The associated database connection */
17670  char *z;            /* String or BLOB value */
17671  int n;              /* Number of characters in string value, excluding '\0' */
17672  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
17673  u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
17674  u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
17675  void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
17676  char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
17677};
17678
17679/* One or more of the following flags are set to indicate the validOK
17680** representations of the value stored in the Mem struct.
17681**
17682** If the MEM_Null flag is set, then the value is an SQL NULL value.
17683** No other flags may be set in this case.
17684**
17685** If the MEM_Str flag is set then Mem.z points at a string representation.
17686** Usually this is encoded in the same unicode encoding as the main
17687** database (see below for exceptions). If the MEM_Term flag is also
17688** set, then the string is nul terminated. The MEM_Int and MEM_Real
17689** flags may coexist with the MEM_Str flag.
17690**
17691** Multiple of these values can appear in Mem.flags.  But only one
17692** at a time can appear in Mem.type.
17693*/
17694#define MEM_Null      0x0001   /* Value is NULL */
17695#define MEM_Str       0x0002   /* Value is a string */
17696#define MEM_Int       0x0004   /* Value is an integer */
17697#define MEM_Real      0x0008   /* Value is a real number */
17698#define MEM_Blob      0x0010   /* Value is a BLOB */
17699#define MEM_RowSet    0x0020   /* Value is a RowSet object */
17700#define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
17701#define MEM_TypeMask  0x00ff   /* Mask of type bits */
17702
17703/* Whenever Mem contains a valid string or blob representation, one of
17704** the following flags must be set to determine the memory management
17705** policy for Mem.z.  The MEM_Term flag tells us whether or not the
17706** string is \000 or \u0000 terminated
17707*/
17708#define MEM_Term      0x0200   /* String rep is nul terminated */
17709#define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
17710#define MEM_Static    0x0800   /* Mem.z points to a static string */
17711#define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
17712#define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
17713#define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
17714
17715#ifdef SQLITE_OMIT_INCRBLOB
17716  #undef MEM_Zero
17717  #define MEM_Zero 0x0000
17718#endif
17719
17720
17721/*
17722** Clear any existing type flags from a Mem and replace them with f
17723*/
17724#define MemSetTypeFlag(p, f) \
17725   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
17726
17727
17728/* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
17729** additional information about auxiliary information bound to arguments
17730** of the function.  This is used to implement the sqlite3_get_auxdata()
17731** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
17732** that can be associated with a constant argument to a function.  This
17733** allows functions such as "regexp" to compile their constant regular
17734** expression argument once and reused the compiled code for multiple
17735** invocations.
17736*/
17737struct VdbeFunc {
17738  FuncDef *pFunc;               /* The definition of the function */
17739  int nAux;                     /* Number of entries allocated for apAux[] */
17740  struct AuxData {
17741    void *pAux;                   /* Aux data for the i-th argument */
17742    void (*xDelete)(void *);      /* Destructor for the aux data */
17743  } apAux[1];                   /* One slot for each function argument */
17744};
17745
17746/*
17747** The "context" argument for a installable function.  A pointer to an
17748** instance of this structure is the first argument to the routines used
17749** implement the SQL functions.
17750**
17751** There is a typedef for this structure in sqlite.h.  So all routines,
17752** even the public interface to SQLite, can use a pointer to this structure.
17753** But this file is the only place where the internal details of this
17754** structure are known.
17755**
17756** This structure is defined inside of vdbeInt.h because it uses substructures
17757** (Mem) which are only defined there.
17758*/
17759struct sqlite3_context {
17760  FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
17761  VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
17762  Mem s;                /* The return value is stored here */
17763  Mem *pMem;            /* Memory cell used to store aggregate context */
17764  int isError;          /* Error code returned by the function. */
17765  CollSeq *pColl;       /* Collating sequence */
17766};
17767
17768/*
17769** A Set structure is used for quick testing to see if a value
17770** is part of a small set.  Sets are used to implement code like
17771** this:
17772**            x.y IN ('hi','hoo','hum')
17773*/
17774typedef struct Set Set;
17775struct Set {
17776  Hash hash;             /* A set is just a hash table */
17777  HashElem *prev;        /* Previously accessed hash elemen */
17778};
17779
17780/*
17781** An instance of the virtual machine.  This structure contains the complete
17782** state of the virtual machine.
17783**
17784** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
17785** is really a pointer to an instance of this structure.
17786**
17787** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
17788** any virtual table method invocations made by the vdbe program. It is
17789** set to 2 for xDestroy method calls and 1 for all other methods. This
17790** variable is used for two purposes: to allow xDestroy methods to execute
17791** "DROP TABLE" statements and to prevent some nasty side effects of
17792** malloc failure when SQLite is invoked recursively by a virtual table
17793** method function.
17794*/
17795struct Vdbe {
17796  sqlite3 *db;            /* The database connection that owns this statement */
17797  Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
17798  int nOp;                /* Number of instructions in the program */
17799  int nOpAlloc;           /* Number of slots allocated for aOp[] */
17800  Op *aOp;                /* Space to hold the virtual machine's program */
17801  int nLabel;             /* Number of labels used */
17802  int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
17803  int *aLabel;            /* Space to hold the labels */
17804  Mem **apArg;            /* Arguments to currently executing user function */
17805  Mem *aColName;          /* Column names to return */
17806  Mem *pResultSet;        /* Pointer to an array of results */
17807  u16 nResColumn;         /* Number of columns in one row of the result set */
17808  u16 nCursor;            /* Number of slots in apCsr[] */
17809  VdbeCursor **apCsr;     /* One element of this array for each open cursor */
17810  u8 errorAction;         /* Recovery action to do in case of an error */
17811  u8 okVar;               /* True if azVar[] has been initialized */
17812  ynVar nVar;             /* Number of entries in aVar[] */
17813  Mem *aVar;              /* Values for the OP_Variable opcode. */
17814  char **azVar;           /* Name of variables */
17815  u32 magic;              /* Magic number for sanity checking */
17816  int nMem;               /* Number of memory locations currently allocated */
17817  Mem *aMem;              /* The memory locations */
17818  u32 cacheCtr;           /* VdbeCursor row cache generation counter */
17819  int pc;                 /* The program counter */
17820  int rc;                 /* Value to return */
17821  char *zErrMsg;          /* Error message written here */
17822  u8 explain;             /* True if EXPLAIN present on SQL command */
17823  u8 changeCntOn;         /* True to update the change-counter */
17824  u8 expired;             /* True if the VM needs to be recompiled */
17825  u8 runOnlyOnce;         /* Automatically expire on reset */
17826  u8 minWriteFileFormat;  /* Minimum file format for writable database files */
17827  u8 inVtabMethod;        /* See comments above */
17828  u8 usesStmtJournal;     /* True if uses a statement journal */
17829  u8 readOnly;            /* True for read-only statements */
17830  u8 isPrepareV2;         /* True if prepared with prepare_v2() */
17831  int nChange;            /* Number of db changes made since last reset */
17832  int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
17833  i64 startTime;          /* Time when query started - used for profiling */
17834  BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
17835  int aCounter[2];        /* Counters used by sqlite3_stmt_status() */
17836  char *zSql;             /* Text of the SQL statement that generated this */
17837  void *pFree;            /* Free this when deleting the vdbe */
17838  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
17839  i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
17840  int iStatement;         /* Statement number (or 0 if has not opened stmt) */
17841#ifdef SQLITE_DEBUG
17842  FILE *trace;            /* Write an execution trace here, if not NULL */
17843#endif
17844  VdbeFrame *pFrame;      /* Parent frame */
17845  int nFrame;             /* Number of frames in pFrame list */
17846  u32 expmask;            /* Binding to these vars invalidates VM */
17847};
17848
17849/*
17850** The following are allowed values for Vdbe.magic
17851*/
17852#define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
17853#define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
17854#define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
17855#define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
17856
17857/*
17858** Function prototypes
17859*/
17860SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
17861void sqliteVdbePopStack(Vdbe*,int);
17862SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
17863#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
17864SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
17865#endif
17866SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
17867SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
17868SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
17869SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
17870SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
17871
17872int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
17873SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
17874SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
17875SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
17876SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
17877SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
17878SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
17879SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
17880SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
17881SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
17882SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
17883SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
17884SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
17885SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
17886SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
17887SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
17888SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
17889SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
17890SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
17891SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
17892SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
17893SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
17894SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
17895SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
17896SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
17897SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
17898SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
17899SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
17900SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
17901SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
17902SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
17903SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
17904SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
17905SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
17906SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
17907SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
17908SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
17909
17910#ifndef SQLITE_OMIT_FOREIGN_KEY
17911SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
17912#else
17913# define sqlite3VdbeCheckFk(p,i) 0
17914#endif
17915
17916#ifndef SQLITE_OMIT_SHARED_CACHE
17917SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p);
17918#else
17919# define sqlite3VdbeMutexArrayEnter(p)
17920#endif
17921
17922SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
17923#ifdef SQLITE_DEBUG
17924SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
17925SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
17926#endif
17927SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
17928
17929#ifndef SQLITE_OMIT_INCRBLOB
17930SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
17931#else
17932  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
17933#endif
17934
17935#endif /* !defined(_VDBEINT_H_) */
17936
17937/************** End of vdbeInt.h *********************************************/
17938/************** Continuing where we left off in utf.c ************************/
17939
17940#ifndef SQLITE_AMALGAMATION
17941/*
17942** The following constant value is used by the SQLITE_BIGENDIAN and
17943** SQLITE_LITTLEENDIAN macros.
17944*/
17945SQLITE_PRIVATE const int sqlite3one = 1;
17946#endif /* SQLITE_AMALGAMATION */
17947
17948/*
17949** This lookup table is used to help decode the first byte of
17950** a multi-byte UTF8 character.
17951*/
17952static const unsigned char sqlite3Utf8Trans1[] = {
17953  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
17954  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
17955  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
17956  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
17957  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
17958  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
17959  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
17960  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
17961};
17962
17963
17964#define WRITE_UTF8(zOut, c) {                          \
17965  if( c<0x00080 ){                                     \
17966    *zOut++ = (u8)(c&0xFF);                            \
17967  }                                                    \
17968  else if( c<0x00800 ){                                \
17969    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
17970    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
17971  }                                                    \
17972  else if( c<0x10000 ){                                \
17973    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
17974    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
17975    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
17976  }else{                                               \
17977    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
17978    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
17979    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
17980    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
17981  }                                                    \
17982}
17983
17984#define WRITE_UTF16LE(zOut, c) {                                    \
17985  if( c<=0xFFFF ){                                                  \
17986    *zOut++ = (u8)(c&0x00FF);                                       \
17987    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
17988  }else{                                                            \
17989    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
17990    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
17991    *zOut++ = (u8)(c&0x00FF);                                       \
17992    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
17993  }                                                                 \
17994}
17995
17996#define WRITE_UTF16BE(zOut, c) {                                    \
17997  if( c<=0xFFFF ){                                                  \
17998    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
17999    *zOut++ = (u8)(c&0x00FF);                                       \
18000  }else{                                                            \
18001    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
18002    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
18003    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
18004    *zOut++ = (u8)(c&0x00FF);                                       \
18005  }                                                                 \
18006}
18007
18008#define READ_UTF16LE(zIn, TERM, c){                                   \
18009  c = (*zIn++);                                                       \
18010  c += ((*zIn++)<<8);                                                 \
18011  if( c>=0xD800 && c<0xE000 && TERM ){                                \
18012    int c2 = (*zIn++);                                                \
18013    c2 += ((*zIn++)<<8);                                              \
18014    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18015  }                                                                   \
18016}
18017
18018#define READ_UTF16BE(zIn, TERM, c){                                   \
18019  c = ((*zIn++)<<8);                                                  \
18020  c += (*zIn++);                                                      \
18021  if( c>=0xD800 && c<0xE000 && TERM ){                                \
18022    int c2 = ((*zIn++)<<8);                                           \
18023    c2 += (*zIn++);                                                   \
18024    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18025  }                                                                   \
18026}
18027
18028/*
18029** Translate a single UTF-8 character.  Return the unicode value.
18030**
18031** During translation, assume that the byte that zTerm points
18032** is a 0x00.
18033**
18034** Write a pointer to the next unread byte back into *pzNext.
18035**
18036** Notes On Invalid UTF-8:
18037**
18038**  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
18039**     be encoded as a multi-byte character.  Any multi-byte character that
18040**     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
18041**
18042**  *  This routine never allows a UTF16 surrogate value to be encoded.
18043**     If a multi-byte character attempts to encode a value between
18044**     0xd800 and 0xe000 then it is rendered as 0xfffd.
18045**
18046**  *  Bytes in the range of 0x80 through 0xbf which occur as the first
18047**     byte of a character are interpreted as single-byte characters
18048**     and rendered as themselves even though they are technically
18049**     invalid characters.
18050**
18051**  *  This routine accepts an infinite number of different UTF8 encodings
18052**     for unicode values 0x80 and greater.  It do not change over-length
18053**     encodings to 0xfffd as some systems recommend.
18054*/
18055#define READ_UTF8(zIn, zTerm, c)                           \
18056  c = *(zIn++);                                            \
18057  if( c>=0xc0 ){                                           \
18058    c = sqlite3Utf8Trans1[c-0xc0];                         \
18059    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
18060      c = (c<<6) + (0x3f & *(zIn++));                      \
18061    }                                                      \
18062    if( c<0x80                                             \
18063        || (c&0xFFFFF800)==0xD800                          \
18064        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
18065  }
18066SQLITE_PRIVATE int sqlite3Utf8Read(
18067  const unsigned char *zIn,       /* First byte of UTF-8 character */
18068  const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
18069){
18070  int c;
18071
18072  /* Same as READ_UTF8() above but without the zTerm parameter.
18073  ** For this routine, we assume the UTF8 string is always zero-terminated.
18074  */
18075  c = *(zIn++);
18076  if( c>=0xc0 ){
18077    c = sqlite3Utf8Trans1[c-0xc0];
18078    while( (*zIn & 0xc0)==0x80 ){
18079      c = (c<<6) + (0x3f & *(zIn++));
18080    }
18081    if( c<0x80
18082        || (c&0xFFFFF800)==0xD800
18083        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
18084  }
18085  *pzNext = zIn;
18086  return c;
18087}
18088
18089
18090
18091
18092/*
18093** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
18094** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
18095*/
18096/* #define TRANSLATE_TRACE 1 */
18097
18098#ifndef SQLITE_OMIT_UTF16
18099/*
18100** This routine transforms the internal text encoding used by pMem to
18101** desiredEnc. It is an error if the string is already of the desired
18102** encoding, or if *pMem does not contain a string value.
18103*/
18104SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
18105  int len;                    /* Maximum length of output string in bytes */
18106  unsigned char *zOut;                  /* Output buffer */
18107  unsigned char *zIn;                   /* Input iterator */
18108  unsigned char *zTerm;                 /* End of input */
18109  unsigned char *z;                     /* Output iterator */
18110  unsigned int c;
18111
18112  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
18113  assert( pMem->flags&MEM_Str );
18114  assert( pMem->enc!=desiredEnc );
18115  assert( pMem->enc!=0 );
18116  assert( pMem->n>=0 );
18117
18118#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
18119  {
18120    char zBuf[100];
18121    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
18122    fprintf(stderr, "INPUT:  %s\n", zBuf);
18123  }
18124#endif
18125
18126  /* If the translation is between UTF-16 little and big endian, then
18127  ** all that is required is to swap the byte order. This case is handled
18128  ** differently from the others.
18129  */
18130  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
18131    u8 temp;
18132    int rc;
18133    rc = sqlite3VdbeMemMakeWriteable(pMem);
18134    if( rc!=SQLITE_OK ){
18135      assert( rc==SQLITE_NOMEM );
18136      return SQLITE_NOMEM;
18137    }
18138    zIn = (u8*)pMem->z;
18139    zTerm = &zIn[pMem->n&~1];
18140    while( zIn<zTerm ){
18141      temp = *zIn;
18142      *zIn = *(zIn+1);
18143      zIn++;
18144      *zIn++ = temp;
18145    }
18146    pMem->enc = desiredEnc;
18147    goto translate_out;
18148  }
18149
18150  /* Set len to the maximum number of bytes required in the output buffer. */
18151  if( desiredEnc==SQLITE_UTF8 ){
18152    /* When converting from UTF-16, the maximum growth results from
18153    ** translating a 2-byte character to a 4-byte UTF-8 character.
18154    ** A single byte is required for the output string
18155    ** nul-terminator.
18156    */
18157    pMem->n &= ~1;
18158    len = pMem->n * 2 + 1;
18159  }else{
18160    /* When converting from UTF-8 to UTF-16 the maximum growth is caused
18161    ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
18162    ** character. Two bytes are required in the output buffer for the
18163    ** nul-terminator.
18164    */
18165    len = pMem->n * 2 + 2;
18166  }
18167
18168  /* Set zIn to point at the start of the input buffer and zTerm to point 1
18169  ** byte past the end.
18170  **
18171  ** Variable zOut is set to point at the output buffer, space obtained
18172  ** from sqlite3_malloc().
18173  */
18174  zIn = (u8*)pMem->z;
18175  zTerm = &zIn[pMem->n];
18176  zOut = sqlite3DbMallocRaw(pMem->db, len);
18177  if( !zOut ){
18178    return SQLITE_NOMEM;
18179  }
18180  z = zOut;
18181
18182  if( pMem->enc==SQLITE_UTF8 ){
18183    if( desiredEnc==SQLITE_UTF16LE ){
18184      /* UTF-8 -> UTF-16 Little-endian */
18185      while( zIn<zTerm ){
18186        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
18187        READ_UTF8(zIn, zTerm, c);
18188        WRITE_UTF16LE(z, c);
18189      }
18190    }else{
18191      assert( desiredEnc==SQLITE_UTF16BE );
18192      /* UTF-8 -> UTF-16 Big-endian */
18193      while( zIn<zTerm ){
18194        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
18195        READ_UTF8(zIn, zTerm, c);
18196        WRITE_UTF16BE(z, c);
18197      }
18198    }
18199    pMem->n = (int)(z - zOut);
18200    *z++ = 0;
18201  }else{
18202    assert( desiredEnc==SQLITE_UTF8 );
18203    if( pMem->enc==SQLITE_UTF16LE ){
18204      /* UTF-16 Little-endian -> UTF-8 */
18205      while( zIn<zTerm ){
18206        READ_UTF16LE(zIn, zIn<zTerm, c);
18207        WRITE_UTF8(z, c);
18208      }
18209    }else{
18210      /* UTF-16 Big-endian -> UTF-8 */
18211      while( zIn<zTerm ){
18212        READ_UTF16BE(zIn, zIn<zTerm, c);
18213        WRITE_UTF8(z, c);
18214      }
18215    }
18216    pMem->n = (int)(z - zOut);
18217  }
18218  *z = 0;
18219  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
18220
18221  sqlite3VdbeMemRelease(pMem);
18222  pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
18223  pMem->enc = desiredEnc;
18224  pMem->flags |= (MEM_Term|MEM_Dyn);
18225  pMem->z = (char*)zOut;
18226  pMem->zMalloc = pMem->z;
18227
18228translate_out:
18229#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
18230  {
18231    char zBuf[100];
18232    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
18233    fprintf(stderr, "OUTPUT: %s\n", zBuf);
18234  }
18235#endif
18236  return SQLITE_OK;
18237}
18238
18239/*
18240** This routine checks for a byte-order mark at the beginning of the
18241** UTF-16 string stored in *pMem. If one is present, it is removed and
18242** the encoding of the Mem adjusted. This routine does not do any
18243** byte-swapping, it just sets Mem.enc appropriately.
18244**
18245** The allocation (static, dynamic etc.) and encoding of the Mem may be
18246** changed by this function.
18247*/
18248SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
18249  int rc = SQLITE_OK;
18250  u8 bom = 0;
18251
18252  assert( pMem->n>=0 );
18253  if( pMem->n>1 ){
18254    u8 b1 = *(u8 *)pMem->z;
18255    u8 b2 = *(((u8 *)pMem->z) + 1);
18256    if( b1==0xFE && b2==0xFF ){
18257      bom = SQLITE_UTF16BE;
18258    }
18259    if( b1==0xFF && b2==0xFE ){
18260      bom = SQLITE_UTF16LE;
18261    }
18262  }
18263
18264  if( bom ){
18265    rc = sqlite3VdbeMemMakeWriteable(pMem);
18266    if( rc==SQLITE_OK ){
18267      pMem->n -= 2;
18268      memmove(pMem->z, &pMem->z[2], pMem->n);
18269      pMem->z[pMem->n] = '\0';
18270      pMem->z[pMem->n+1] = '\0';
18271      pMem->flags |= MEM_Term;
18272      pMem->enc = bom;
18273    }
18274  }
18275  return rc;
18276}
18277#endif /* SQLITE_OMIT_UTF16 */
18278
18279/*
18280** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
18281** return the number of unicode characters in pZ up to (but not including)
18282** the first 0x00 byte. If nByte is not less than zero, return the
18283** number of unicode characters in the first nByte of pZ (or up to
18284** the first 0x00, whichever comes first).
18285*/
18286SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
18287  int r = 0;
18288  const u8 *z = (const u8*)zIn;
18289  const u8 *zTerm;
18290  if( nByte>=0 ){
18291    zTerm = &z[nByte];
18292  }else{
18293    zTerm = (const u8*)(-1);
18294  }
18295  assert( z<=zTerm );
18296  while( *z!=0 && z<zTerm ){
18297    SQLITE_SKIP_UTF8(z);
18298    r++;
18299  }
18300  return r;
18301}
18302
18303/* This test function is not currently used by the automated test-suite.
18304** Hence it is only available in debug builds.
18305*/
18306#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
18307/*
18308** Translate UTF-8 to UTF-8.
18309**
18310** This has the effect of making sure that the string is well-formed
18311** UTF-8.  Miscoded characters are removed.
18312**
18313** The translation is done in-place (since it is impossible for the
18314** correct UTF-8 encoding to be longer than a malformed encoding).
18315*/
18316SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
18317  unsigned char *zOut = zIn;
18318  unsigned char *zStart = zIn;
18319  u32 c;
18320
18321  while( zIn[0] ){
18322    c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
18323    if( c!=0xfffd ){
18324      WRITE_UTF8(zOut, c);
18325    }
18326  }
18327  *zOut = 0;
18328  return (int)(zOut - zStart);
18329}
18330#endif
18331
18332#ifndef SQLITE_OMIT_UTF16
18333/*
18334** Convert a UTF-16 string in the native encoding into a UTF-8 string.
18335** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
18336** be freed by the calling function.
18337**
18338** NULL is returned if there is an allocation error.
18339*/
18340SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte){
18341  Mem m;
18342  memset(&m, 0, sizeof(m));
18343  m.db = db;
18344  sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
18345  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
18346  if( db->mallocFailed ){
18347    sqlite3VdbeMemRelease(&m);
18348    m.z = 0;
18349  }
18350  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
18351  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
18352  return (m.flags & MEM_Dyn)!=0 ? m.z : sqlite3DbStrDup(db, m.z);
18353}
18354
18355/*
18356** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
18357** enc. A pointer to the new string is returned, and the value of *pnOut
18358** is set to the length of the returned string in bytes. The call should
18359** arrange to call sqlite3DbFree() on the returned pointer when it is
18360** no longer required.
18361**
18362** If a malloc failure occurs, NULL is returned and the db.mallocFailed
18363** flag set.
18364*/
18365#ifdef SQLITE_ENABLE_STAT2
18366SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
18367  Mem m;
18368  memset(&m, 0, sizeof(m));
18369  m.db = db;
18370  sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
18371  if( sqlite3VdbeMemTranslate(&m, enc) ){
18372    assert( db->mallocFailed );
18373    return 0;
18374  }
18375  assert( m.z==m.zMalloc );
18376  *pnOut = m.n;
18377  return m.z;
18378}
18379#endif
18380
18381/*
18382** zIn is a UTF-16 encoded unicode string at least nChar characters long.
18383** Return the number of bytes in the first nChar unicode characters
18384** in pZ.  nChar must be non-negative.
18385*/
18386SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
18387  int c;
18388  unsigned char const *z = zIn;
18389  int n = 0;
18390
18391  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
18392    while( n<nChar ){
18393      READ_UTF16BE(z, 1, c);
18394      n++;
18395    }
18396  }else{
18397    while( n<nChar ){
18398      READ_UTF16LE(z, 1, c);
18399      n++;
18400    }
18401  }
18402  return (int)(z-(unsigned char const *)zIn);
18403}
18404
18405#if defined(SQLITE_TEST)
18406/*
18407** This routine is called from the TCL test function "translate_selftest".
18408** It checks that the primitives for serializing and deserializing
18409** characters in each encoding are inverses of each other.
18410*/
18411SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
18412  unsigned int i, t;
18413  unsigned char zBuf[20];
18414  unsigned char *z;
18415  int n;
18416  unsigned int c;
18417
18418  for(i=0; i<0x00110000; i++){
18419    z = zBuf;
18420    WRITE_UTF8(z, i);
18421    n = (int)(z-zBuf);
18422    assert( n>0 && n<=4 );
18423    z[0] = 0;
18424    z = zBuf;
18425    c = sqlite3Utf8Read(z, (const u8**)&z);
18426    t = i;
18427    if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
18428    if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
18429    assert( c==t );
18430    assert( (z-zBuf)==n );
18431  }
18432  for(i=0; i<0x00110000; i++){
18433    if( i>=0xD800 && i<0xE000 ) continue;
18434    z = zBuf;
18435    WRITE_UTF16LE(z, i);
18436    n = (int)(z-zBuf);
18437    assert( n>0 && n<=4 );
18438    z[0] = 0;
18439    z = zBuf;
18440    READ_UTF16LE(z, 1, c);
18441    assert( c==i );
18442    assert( (z-zBuf)==n );
18443  }
18444  for(i=0; i<0x00110000; i++){
18445    if( i>=0xD800 && i<0xE000 ) continue;
18446    z = zBuf;
18447    WRITE_UTF16BE(z, i);
18448    n = (int)(z-zBuf);
18449    assert( n>0 && n<=4 );
18450    z[0] = 0;
18451    z = zBuf;
18452    READ_UTF16BE(z, 1, c);
18453    assert( c==i );
18454    assert( (z-zBuf)==n );
18455  }
18456}
18457#endif /* SQLITE_TEST */
18458#endif /* SQLITE_OMIT_UTF16 */
18459
18460/************** End of utf.c *************************************************/
18461/************** Begin file util.c ********************************************/
18462/*
18463** 2001 September 15
18464**
18465** The author disclaims copyright to this source code.  In place of
18466** a legal notice, here is a blessing:
18467**
18468**    May you do good and not evil.
18469**    May you find forgiveness for yourself and forgive others.
18470**    May you share freely, never taking more than you give.
18471**
18472*************************************************************************
18473** Utility functions used throughout sqlite.
18474**
18475** This file contains functions for allocating memory, comparing
18476** strings, and stuff like that.
18477**
18478*/
18479#ifdef SQLITE_HAVE_ISNAN
18480# include <math.h>
18481#endif
18482
18483/*
18484** Routine needed to support the testcase() macro.
18485*/
18486#ifdef SQLITE_COVERAGE_TEST
18487SQLITE_PRIVATE void sqlite3Coverage(int x){
18488  static int dummy = 0;
18489  dummy += x;
18490}
18491#endif
18492
18493/*
18494** Return true if the floating point value is Not a Number (NaN).
18495**
18496** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
18497** Otherwise, we have our own implementation that works on most systems.
18498*/
18499SQLITE_PRIVATE int sqlite3IsNaN(double x){
18500  int rc;   /* The value return */
18501#if !defined(SQLITE_HAVE_ISNAN)
18502  /*
18503  ** Systems that support the isnan() library function should probably
18504  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
18505  ** found that many systems do not have a working isnan() function so
18506  ** this implementation is provided as an alternative.
18507  **
18508  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
18509  ** On the other hand, the use of -ffast-math comes with the following
18510  ** warning:
18511  **
18512  **      This option [-ffast-math] should never be turned on by any
18513  **      -O option since it can result in incorrect output for programs
18514  **      which depend on an exact implementation of IEEE or ISO
18515  **      rules/specifications for math functions.
18516  **
18517  ** Under MSVC, this NaN test may fail if compiled with a floating-
18518  ** point precision mode other than /fp:precise.  From the MSDN
18519  ** documentation:
18520  **
18521  **      The compiler [with /fp:precise] will properly handle comparisons
18522  **      involving NaN. For example, x != x evaluates to true if x is NaN
18523  **      ...
18524  */
18525#ifdef __FAST_MATH__
18526# error SQLite will not work correctly with the -ffast-math option of GCC.
18527#endif
18528  volatile double y = x;
18529  volatile double z = y;
18530  rc = (y!=z);
18531#else  /* if defined(SQLITE_HAVE_ISNAN) */
18532  rc = isnan(x);
18533#endif /* SQLITE_HAVE_ISNAN */
18534  testcase( rc );
18535  return rc;
18536}
18537
18538/*
18539** Compute a string length that is limited to what can be stored in
18540** lower 30 bits of a 32-bit signed integer.
18541**
18542** The value returned will never be negative.  Nor will it ever be greater
18543** than the actual length of the string.  For very long strings (greater
18544** than 1GiB) the value returned might be less than the true string length.
18545*/
18546SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
18547  const char *z2 = z;
18548  if( z==0 ) return 0;
18549  while( *z2 ){ z2++; }
18550  return 0x3fffffff & (int)(z2 - z);
18551}
18552
18553/*
18554** Set the most recent error code and error string for the sqlite
18555** handle "db". The error code is set to "err_code".
18556**
18557** If it is not NULL, string zFormat specifies the format of the
18558** error string in the style of the printf functions: The following
18559** format characters are allowed:
18560**
18561**      %s      Insert a string
18562**      %z      A string that should be freed after use
18563**      %d      Insert an integer
18564**      %T      Insert a token
18565**      %S      Insert the first element of a SrcList
18566**
18567** zFormat and any string tokens that follow it are assumed to be
18568** encoded in UTF-8.
18569**
18570** To clear the most recent error for sqlite handle "db", sqlite3Error
18571** should be called with err_code set to SQLITE_OK and zFormat set
18572** to NULL.
18573*/
18574SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
18575  if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
18576    db->errCode = err_code;
18577    if( zFormat ){
18578      char *z;
18579      va_list ap;
18580      va_start(ap, zFormat);
18581      z = sqlite3VMPrintf(db, zFormat, ap);
18582      va_end(ap);
18583      sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
18584    }else{
18585      sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
18586    }
18587  }
18588}
18589
18590/*
18591** Add an error message to pParse->zErrMsg and increment pParse->nErr.
18592** The following formatting characters are allowed:
18593**
18594**      %s      Insert a string
18595**      %z      A string that should be freed after use
18596**      %d      Insert an integer
18597**      %T      Insert a token
18598**      %S      Insert the first element of a SrcList
18599**
18600** This function should be used to report any error that occurs whilst
18601** compiling an SQL statement (i.e. within sqlite3_prepare()). The
18602** last thing the sqlite3_prepare() function does is copy the error
18603** stored by this function into the database handle using sqlite3Error().
18604** Function sqlite3Error() should be used during statement execution
18605** (sqlite3_step() etc.).
18606*/
18607SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
18608  char *zMsg;
18609  va_list ap;
18610  sqlite3 *db = pParse->db;
18611  va_start(ap, zFormat);
18612  zMsg = sqlite3VMPrintf(db, zFormat, ap);
18613  va_end(ap);
18614  if( db->suppressErr ){
18615    sqlite3DbFree(db, zMsg);
18616  }else{
18617    pParse->nErr++;
18618    sqlite3DbFree(db, pParse->zErrMsg);
18619    pParse->zErrMsg = zMsg;
18620    pParse->rc = SQLITE_ERROR;
18621  }
18622}
18623
18624/*
18625** Convert an SQL-style quoted string into a normal string by removing
18626** the quote characters.  The conversion is done in-place.  If the
18627** input does not begin with a quote character, then this routine
18628** is a no-op.
18629**
18630** The input string must be zero-terminated.  A new zero-terminator
18631** is added to the dequoted string.
18632**
18633** The return value is -1 if no dequoting occurs or the length of the
18634** dequoted string, exclusive of the zero terminator, if dequoting does
18635** occur.
18636**
18637** 2002-Feb-14: This routine is extended to remove MS-Access style
18638** brackets from around identifers.  For example:  "[a-b-c]" becomes
18639** "a-b-c".
18640*/
18641SQLITE_PRIVATE int sqlite3Dequote(char *z){
18642  char quote;
18643  int i, j;
18644  if( z==0 ) return -1;
18645  quote = z[0];
18646  switch( quote ){
18647    case '\'':  break;
18648    case '"':   break;
18649    case '`':   break;                /* For MySQL compatibility */
18650    case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
18651    default:    return -1;
18652  }
18653  for(i=1, j=0; ALWAYS(z[i]); i++){
18654    if( z[i]==quote ){
18655      if( z[i+1]==quote ){
18656        z[j++] = quote;
18657        i++;
18658      }else{
18659        break;
18660      }
18661    }else{
18662      z[j++] = z[i];
18663    }
18664  }
18665  z[j] = 0;
18666  return j;
18667}
18668
18669/* Convenient short-hand */
18670#define UpperToLower sqlite3UpperToLower
18671
18672/*
18673** Some systems have stricmp().  Others have strcasecmp().  Because
18674** there is no consistency, we will define our own.
18675*/
18676SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
18677  register unsigned char *a, *b;
18678  a = (unsigned char *)zLeft;
18679  b = (unsigned char *)zRight;
18680  while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
18681  return UpperToLower[*a] - UpperToLower[*b];
18682}
18683SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
18684  register unsigned char *a, *b;
18685  a = (unsigned char *)zLeft;
18686  b = (unsigned char *)zRight;
18687  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
18688  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
18689}
18690
18691/*
18692** Return TRUE if z is a pure numeric string.  Return FALSE and leave
18693** *realnum unchanged if the string contains any character which is not
18694** part of a number.
18695**
18696** If the string is pure numeric, set *realnum to TRUE if the string
18697** contains the '.' character or an "E+000" style exponentiation suffix.
18698** Otherwise set *realnum to FALSE.  Note that just becaue *realnum is
18699** false does not mean that the number can be successfully converted into
18700** an integer - it might be too big.
18701**
18702** An empty string is considered non-numeric.
18703*/
18704SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
18705  int incr = (enc==SQLITE_UTF8?1:2);
18706  if( enc==SQLITE_UTF16BE ) z++;
18707  if( *z=='-' || *z=='+' ) z += incr;
18708  if( !sqlite3Isdigit(*z) ){
18709    return 0;
18710  }
18711  z += incr;
18712  *realnum = 0;
18713  while( sqlite3Isdigit(*z) ){ z += incr; }
18714  if( *z=='.' ){
18715    z += incr;
18716    if( !sqlite3Isdigit(*z) ) return 0;
18717    while( sqlite3Isdigit(*z) ){ z += incr; }
18718    *realnum = 1;
18719  }
18720  if( *z=='e' || *z=='E' ){
18721    z += incr;
18722    if( *z=='+' || *z=='-' ) z += incr;
18723    if( !sqlite3Isdigit(*z) ) return 0;
18724    while( sqlite3Isdigit(*z) ){ z += incr; }
18725    *realnum = 1;
18726  }
18727  return *z==0;
18728}
18729
18730/*
18731** The string z[] is an ASCII representation of a real number.
18732** Convert this string to a double.
18733**
18734** This routine assumes that z[] really is a valid number.  If it
18735** is not, the result is undefined.
18736**
18737** This routine is used instead of the library atof() function because
18738** the library atof() might want to use "," as the decimal point instead
18739** of "." depending on how locale is set.  But that would cause problems
18740** for SQL.  So this routine always uses "." regardless of locale.
18741*/
18742SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
18743#ifndef SQLITE_OMIT_FLOATING_POINT
18744  const char *zBegin = z;
18745  /* sign * significand * (10 ^ (esign * exponent)) */
18746  int sign = 1;   /* sign of significand */
18747  i64 s = 0;      /* significand */
18748  int d = 0;      /* adjust exponent for shifting decimal point */
18749  int esign = 1;  /* sign of exponent */
18750  int e = 0;      /* exponent */
18751  double result;
18752  int nDigits = 0;
18753
18754  /* skip leading spaces */
18755  while( sqlite3Isspace(*z) ) z++;
18756  /* get sign of significand */
18757  if( *z=='-' ){
18758    sign = -1;
18759    z++;
18760  }else if( *z=='+' ){
18761    z++;
18762  }
18763  /* skip leading zeroes */
18764  while( z[0]=='0' ) z++, nDigits++;
18765
18766  /* copy max significant digits to significand */
18767  while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
18768    s = s*10 + (*z - '0');
18769    z++, nDigits++;
18770  }
18771  /* skip non-significant significand digits
18772  ** (increase exponent by d to shift decimal left) */
18773  while( sqlite3Isdigit(*z) ) z++, nDigits++, d++;
18774
18775  /* if decimal point is present */
18776  if( *z=='.' ){
18777    z++;
18778    /* copy digits from after decimal to significand
18779    ** (decrease exponent by d to shift decimal right) */
18780    while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
18781      s = s*10 + (*z - '0');
18782      z++, nDigits++, d--;
18783    }
18784    /* skip non-significant digits */
18785    while( sqlite3Isdigit(*z) ) z++, nDigits++;
18786  }
18787
18788  /* if exponent is present */
18789  if( *z=='e' || *z=='E' ){
18790    z++;
18791    /* get sign of exponent */
18792    if( *z=='-' ){
18793      esign = -1;
18794      z++;
18795    }else if( *z=='+' ){
18796      z++;
18797    }
18798    /* copy digits to exponent */
18799    while( sqlite3Isdigit(*z) ){
18800      e = e*10 + (*z - '0');
18801      z++;
18802    }
18803  }
18804
18805  /* adjust exponent by d, and update sign */
18806  e = (e*esign) + d;
18807  if( e<0 ) {
18808    esign = -1;
18809    e *= -1;
18810  } else {
18811    esign = 1;
18812  }
18813
18814  /* if 0 significand */
18815  if( !s ) {
18816    /* In the IEEE 754 standard, zero is signed.
18817    ** Add the sign if we've seen at least one digit */
18818    result = (sign<0 && nDigits) ? -(double)0 : (double)0;
18819  } else {
18820    /* attempt to reduce exponent */
18821    if( esign>0 ){
18822      while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
18823    }else{
18824      while( !(s%10) && e>0 ) e--,s/=10;
18825    }
18826
18827    /* adjust the sign of significand */
18828    s = sign<0 ? -s : s;
18829
18830    /* if exponent, scale significand as appropriate
18831    ** and store in result. */
18832    if( e ){
18833      double scale = 1.0;
18834      /* attempt to handle extremely small/large numbers better */
18835      if( e>307 && e<342 ){
18836        while( e%308 ) { scale *= 1.0e+1; e -= 1; }
18837        if( esign<0 ){
18838          result = s / scale;
18839          result /= 1.0e+308;
18840        }else{
18841          result = s * scale;
18842          result *= 1.0e+308;
18843        }
18844      }else{
18845        /* 1.0e+22 is the largest power of 10 than can be
18846        ** represented exactly. */
18847        while( e%22 ) { scale *= 1.0e+1; e -= 1; }
18848        while( e>0 ) { scale *= 1.0e+22; e -= 22; }
18849        if( esign<0 ){
18850          result = s / scale;
18851        }else{
18852          result = s * scale;
18853        }
18854      }
18855    } else {
18856      result = (double)s;
18857    }
18858  }
18859
18860  /* store the result */
18861  *pResult = result;
18862
18863  /* return number of characters used */
18864  return (int)(z - zBegin);
18865#else
18866  return sqlite3Atoi64(z, pResult);
18867#endif /* SQLITE_OMIT_FLOATING_POINT */
18868}
18869
18870/*
18871** Compare the 19-character string zNum against the text representation
18872** value 2^63:  9223372036854775808.  Return negative, zero, or positive
18873** if zNum is less than, equal to, or greater than the string.
18874**
18875** Unlike memcmp() this routine is guaranteed to return the difference
18876** in the values of the last digit if the only difference is in the
18877** last digit.  So, for example,
18878**
18879**      compare2pow63("9223372036854775800")
18880**
18881** will return -8.
18882*/
18883static int compare2pow63(const char *zNum){
18884  int c;
18885  c = memcmp(zNum,"922337203685477580",18)*10;
18886  if( c==0 ){
18887    c = zNum[18] - '8';
18888  }
18889  return c;
18890}
18891
18892
18893/*
18894** Return TRUE if zNum is a 64-bit signed integer and write
18895** the value of the integer into *pNum.  If zNum is not an integer
18896** or is an integer that is too large to be expressed with 64 bits,
18897** then return false.
18898**
18899** When this routine was originally written it dealt with only
18900** 32-bit numbers.  At that time, it was much faster than the
18901** atoi() library routine in RedHat 7.2.
18902*/
18903SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
18904  i64 v = 0;
18905  int neg;
18906  int i, c;
18907  const char *zStart;
18908  while( sqlite3Isspace(*zNum) ) zNum++;
18909  if( *zNum=='-' ){
18910    neg = 1;
18911    zNum++;
18912  }else if( *zNum=='+' ){
18913    neg = 0;
18914    zNum++;
18915  }else{
18916    neg = 0;
18917  }
18918  zStart = zNum;
18919  while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
18920  for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
18921    v = v*10 + c - '0';
18922  }
18923  *pNum = neg ? -v : v;
18924  if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
18925    /* zNum is empty or contains non-numeric text or is longer
18926    ** than 19 digits (thus guaranting that it is too large) */
18927    return 0;
18928  }else if( i<19 ){
18929    /* Less than 19 digits, so we know that it fits in 64 bits */
18930    return 1;
18931  }else{
18932    /* 19-digit numbers must be no larger than 9223372036854775807 if positive
18933    ** or 9223372036854775808 if negative.  Note that 9223372036854665808
18934    ** is 2^63. */
18935    return compare2pow63(zNum)<neg;
18936  }
18937}
18938
18939/*
18940** The string zNum represents an unsigned integer.  The zNum string
18941** consists of one or more digit characters and is terminated by
18942** a zero character.  Any stray characters in zNum result in undefined
18943** behavior.
18944**
18945** If the unsigned integer that zNum represents will fit in a
18946** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
18947**
18948** If the negFlag parameter is true, that means that zNum really represents
18949** a negative number.  (The leading "-" is omitted from zNum.)  This
18950** parameter is needed to determine a boundary case.  A string
18951** of "9223373036854775808" returns false if negFlag is false or true
18952** if negFlag is true.
18953**
18954** Leading zeros are ignored.
18955*/
18956SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
18957  int i;
18958  int neg = 0;
18959
18960  assert( zNum[0]>='0' && zNum[0]<='9' ); /* zNum is an unsigned number */
18961
18962  if( negFlag ) neg = 1-neg;
18963  while( *zNum=='0' ){
18964    zNum++;   /* Skip leading zeros.  Ticket #2454 */
18965  }
18966  for(i=0; zNum[i]; i++){ assert( zNum[i]>='0' && zNum[i]<='9' ); }
18967  if( i<19 ){
18968    /* Guaranteed to fit if less than 19 digits */
18969    return 1;
18970  }else if( i>19 ){
18971    /* Guaranteed to be too big if greater than 19 digits */
18972    return 0;
18973  }else{
18974    /* Compare against 2^63. */
18975    return compare2pow63(zNum)<neg;
18976  }
18977}
18978
18979/*
18980** If zNum represents an integer that will fit in 32-bits, then set
18981** *pValue to that integer and return true.  Otherwise return false.
18982**
18983** Any non-numeric characters that following zNum are ignored.
18984** This is different from sqlite3Atoi64() which requires the
18985** input number to be zero-terminated.
18986*/
18987SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
18988  sqlite_int64 v = 0;
18989  int i, c;
18990  int neg = 0;
18991  if( zNum[0]=='-' ){
18992    neg = 1;
18993    zNum++;
18994  }else if( zNum[0]=='+' ){
18995    zNum++;
18996  }
18997  while( zNum[0]=='0' ) zNum++;
18998  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
18999    v = v*10 + c;
19000  }
19001
19002  /* The longest decimal representation of a 32 bit integer is 10 digits:
19003  **
19004  **             1234567890
19005  **     2^31 -> 2147483648
19006  */
19007  if( i>10 ){
19008    return 0;
19009  }
19010  if( v-neg>2147483647 ){
19011    return 0;
19012  }
19013  if( neg ){
19014    v = -v;
19015  }
19016  *pValue = (int)v;
19017  return 1;
19018}
19019
19020/*
19021** The variable-length integer encoding is as follows:
19022**
19023** KEY:
19024**         A = 0xxxxxxx    7 bits of data and one flag bit
19025**         B = 1xxxxxxx    7 bits of data and one flag bit
19026**         C = xxxxxxxx    8 bits of data
19027**
19028**  7 bits - A
19029** 14 bits - BA
19030** 21 bits - BBA
19031** 28 bits - BBBA
19032** 35 bits - BBBBA
19033** 42 bits - BBBBBA
19034** 49 bits - BBBBBBA
19035** 56 bits - BBBBBBBA
19036** 64 bits - BBBBBBBBC
19037*/
19038
19039/*
19040** Write a 64-bit variable-length integer to memory starting at p[0].
19041** The length of data write will be between 1 and 9 bytes.  The number
19042** of bytes written is returned.
19043**
19044** A variable-length integer consists of the lower 7 bits of each byte
19045** for all bytes that have the 8th bit set and one byte with the 8th
19046** bit clear.  Except, if we get to the 9th byte, it stores the full
19047** 8 bits and is the last byte.
19048*/
19049SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
19050  int i, j, n;
19051  u8 buf[10];
19052  if( v & (((u64)0xff000000)<<32) ){
19053    p[8] = (u8)v;
19054    v >>= 8;
19055    for(i=7; i>=0; i--){
19056      p[i] = (u8)((v & 0x7f) | 0x80);
19057      v >>= 7;
19058    }
19059    return 9;
19060  }
19061  n = 0;
19062  do{
19063    buf[n++] = (u8)((v & 0x7f) | 0x80);
19064    v >>= 7;
19065  }while( v!=0 );
19066  buf[0] &= 0x7f;
19067  assert( n<=9 );
19068  for(i=0, j=n-1; j>=0; j--, i++){
19069    p[i] = buf[j];
19070  }
19071  return n;
19072}
19073
19074/*
19075** This routine is a faster version of sqlite3PutVarint() that only
19076** works for 32-bit positive integers and which is optimized for
19077** the common case of small integers.  A MACRO version, putVarint32,
19078** is provided which inlines the single-byte case.  All code should use
19079** the MACRO version as this function assumes the single-byte case has
19080** already been handled.
19081*/
19082SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
19083#ifndef putVarint32
19084  if( (v & ~0x7f)==0 ){
19085    p[0] = v;
19086    return 1;
19087  }
19088#endif
19089  if( (v & ~0x3fff)==0 ){
19090    p[0] = (u8)((v>>7) | 0x80);
19091    p[1] = (u8)(v & 0x7f);
19092    return 2;
19093  }
19094  return sqlite3PutVarint(p, v);
19095}
19096
19097/*
19098** Read a 64-bit variable-length integer from memory starting at p[0].
19099** Return the number of bytes read.  The value is stored in *v.
19100*/
19101SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
19102  u32 a,b,s;
19103
19104  a = *p;
19105  /* a: p0 (unmasked) */
19106  if (!(a&0x80))
19107  {
19108    *v = a;
19109    return 1;
19110  }
19111
19112  p++;
19113  b = *p;
19114  /* b: p1 (unmasked) */
19115  if (!(b&0x80))
19116  {
19117    a &= 0x7f;
19118    a = a<<7;
19119    a |= b;
19120    *v = a;
19121    return 2;
19122  }
19123
19124  p++;
19125  a = a<<14;
19126  a |= *p;
19127  /* a: p0<<14 | p2 (unmasked) */
19128  if (!(a&0x80))
19129  {
19130    a &= (0x7f<<14)|(0x7f);
19131    b &= 0x7f;
19132    b = b<<7;
19133    a |= b;
19134    *v = a;
19135    return 3;
19136  }
19137
19138  /* CSE1 from below */
19139  a &= (0x7f<<14)|(0x7f);
19140  p++;
19141  b = b<<14;
19142  b |= *p;
19143  /* b: p1<<14 | p3 (unmasked) */
19144  if (!(b&0x80))
19145  {
19146    b &= (0x7f<<14)|(0x7f);
19147    /* moved CSE1 up */
19148    /* a &= (0x7f<<14)|(0x7f); */
19149    a = a<<7;
19150    a |= b;
19151    *v = a;
19152    return 4;
19153  }
19154
19155  /* a: p0<<14 | p2 (masked) */
19156  /* b: p1<<14 | p3 (unmasked) */
19157  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19158  /* moved CSE1 up */
19159  /* a &= (0x7f<<14)|(0x7f); */
19160  b &= (0x7f<<14)|(0x7f);
19161  s = a;
19162  /* s: p0<<14 | p2 (masked) */
19163
19164  p++;
19165  a = a<<14;
19166  a |= *p;
19167  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
19168  if (!(a&0x80))
19169  {
19170    /* we can skip these cause they were (effectively) done above in calc'ing s */
19171    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
19172    /* b &= (0x7f<<14)|(0x7f); */
19173    b = b<<7;
19174    a |= b;
19175    s = s>>18;
19176    *v = ((u64)s)<<32 | a;
19177    return 5;
19178  }
19179
19180  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19181  s = s<<7;
19182  s |= b;
19183  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19184
19185  p++;
19186  b = b<<14;
19187  b |= *p;
19188  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
19189  if (!(b&0x80))
19190  {
19191    /* we can skip this cause it was (effectively) done above in calc'ing s */
19192    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
19193    a &= (0x7f<<14)|(0x7f);
19194    a = a<<7;
19195    a |= b;
19196    s = s>>18;
19197    *v = ((u64)s)<<32 | a;
19198    return 6;
19199  }
19200
19201  p++;
19202  a = a<<14;
19203  a |= *p;
19204  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
19205  if (!(a&0x80))
19206  {
19207    a &= (0x1f<<28)|(0x7f<<14)|(0x7f);
19208    b &= (0x7f<<14)|(0x7f);
19209    b = b<<7;
19210    a |= b;
19211    s = s>>11;
19212    *v = ((u64)s)<<32 | a;
19213    return 7;
19214  }
19215
19216  /* CSE2 from below */
19217  a &= (0x7f<<14)|(0x7f);
19218  p++;
19219  b = b<<14;
19220  b |= *p;
19221  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
19222  if (!(b&0x80))
19223  {
19224    b &= (0x1f<<28)|(0x7f<<14)|(0x7f);
19225    /* moved CSE2 up */
19226    /* a &= (0x7f<<14)|(0x7f); */
19227    a = a<<7;
19228    a |= b;
19229    s = s>>4;
19230    *v = ((u64)s)<<32 | a;
19231    return 8;
19232  }
19233
19234  p++;
19235  a = a<<15;
19236  a |= *p;
19237  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
19238
19239  /* moved CSE2 up */
19240  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
19241  b &= (0x7f<<14)|(0x7f);
19242  b = b<<8;
19243  a |= b;
19244
19245  s = s<<4;
19246  b = p[-4];
19247  b &= 0x7f;
19248  b = b>>3;
19249  s |= b;
19250
19251  *v = ((u64)s)<<32 | a;
19252
19253  return 9;
19254}
19255
19256/*
19257** Read a 32-bit variable-length integer from memory starting at p[0].
19258** Return the number of bytes read.  The value is stored in *v.
19259**
19260** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
19261** integer, then set *v to 0xffffffff.
19262**
19263** A MACRO version, getVarint32, is provided which inlines the
19264** single-byte case.  All code should use the MACRO version as
19265** this function assumes the single-byte case has already been handled.
19266*/
19267SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
19268  u32 a,b;
19269
19270  /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
19271  ** by the getVarin32() macro */
19272  a = *p;
19273  /* a: p0 (unmasked) */
19274#ifndef getVarint32
19275  if (!(a&0x80))
19276  {
19277    /* Values between 0 and 127 */
19278    *v = a;
19279    return 1;
19280  }
19281#endif
19282
19283  /* The 2-byte case */
19284  p++;
19285  b = *p;
19286  /* b: p1 (unmasked) */
19287  if (!(b&0x80))
19288  {
19289    /* Values between 128 and 16383 */
19290    a &= 0x7f;
19291    a = a<<7;
19292    *v = a | b;
19293    return 2;
19294  }
19295
19296  /* The 3-byte case */
19297  p++;
19298  a = a<<14;
19299  a |= *p;
19300  /* a: p0<<14 | p2 (unmasked) */
19301  if (!(a&0x80))
19302  {
19303    /* Values between 16384 and 2097151 */
19304    a &= (0x7f<<14)|(0x7f);
19305    b &= 0x7f;
19306    b = b<<7;
19307    *v = a | b;
19308    return 3;
19309  }
19310
19311  /* A 32-bit varint is used to store size information in btrees.
19312  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
19313  ** A 3-byte varint is sufficient, for example, to record the size
19314  ** of a 1048569-byte BLOB or string.
19315  **
19316  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
19317  ** rare larger cases can be handled by the slower 64-bit varint
19318  ** routine.
19319  */
19320#if 1
19321  {
19322    u64 v64;
19323    u8 n;
19324
19325    p -= 2;
19326    n = sqlite3GetVarint(p, &v64);
19327    assert( n>3 && n<=9 );
19328    if( (v64 & SQLITE_MAX_U32)!=v64 ){
19329      *v = 0xffffffff;
19330    }else{
19331      *v = (u32)v64;
19332    }
19333    return n;
19334  }
19335
19336#else
19337  /* For following code (kept for historical record only) shows an
19338  ** unrolling for the 3- and 4-byte varint cases.  This code is
19339  ** slightly faster, but it is also larger and much harder to test.
19340  */
19341  p++;
19342  b = b<<14;
19343  b |= *p;
19344  /* b: p1<<14 | p3 (unmasked) */
19345  if (!(b&0x80))
19346  {
19347    /* Values between 2097152 and 268435455 */
19348    b &= (0x7f<<14)|(0x7f);
19349    a &= (0x7f<<14)|(0x7f);
19350    a = a<<7;
19351    *v = a | b;
19352    return 4;
19353  }
19354
19355  p++;
19356  a = a<<14;
19357  a |= *p;
19358  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
19359  if (!(a&0x80))
19360  {
19361    /* Walues  between 268435456 and 34359738367 */
19362    a &= (0x1f<<28)|(0x7f<<14)|(0x7f);
19363    b &= (0x1f<<28)|(0x7f<<14)|(0x7f);
19364    b = b<<7;
19365    *v = a | b;
19366    return 5;
19367  }
19368
19369  /* We can only reach this point when reading a corrupt database
19370  ** file.  In that case we are not in any hurry.  Use the (relatively
19371  ** slow) general-purpose sqlite3GetVarint() routine to extract the
19372  ** value. */
19373  {
19374    u64 v64;
19375    u8 n;
19376
19377    p -= 4;
19378    n = sqlite3GetVarint(p, &v64);
19379    assert( n>5 && n<=9 );
19380    *v = (u32)v64;
19381    return n;
19382  }
19383#endif
19384}
19385
19386/*
19387** Return the number of bytes that will be needed to store the given
19388** 64-bit integer.
19389*/
19390SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
19391  int i = 0;
19392  do{
19393    i++;
19394    v >>= 7;
19395  }while( v!=0 && ALWAYS(i<9) );
19396  return i;
19397}
19398
19399
19400/*
19401** Read or write a four-byte big-endian integer value.
19402*/
19403SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
19404  return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
19405}
19406SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
19407  p[0] = (u8)(v>>24);
19408  p[1] = (u8)(v>>16);
19409  p[2] = (u8)(v>>8);
19410  p[3] = (u8)v;
19411}
19412
19413
19414
19415#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
19416/*
19417** Translate a single byte of Hex into an integer.
19418** This routine only works if h really is a valid hexadecimal
19419** character:  0..9a..fA..F
19420*/
19421static u8 hexToInt(int h){
19422  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
19423#ifdef SQLITE_ASCII
19424  h += 9*(1&(h>>6));
19425#endif
19426#ifdef SQLITE_EBCDIC
19427  h += 9*(1&~(h>>4));
19428#endif
19429  return (u8)(h & 0xf);
19430}
19431#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
19432
19433#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
19434/*
19435** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
19436** value.  Return a pointer to its binary value.  Space to hold the
19437** binary value has been obtained from malloc and must be freed by
19438** the calling routine.
19439*/
19440SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
19441  char *zBlob;
19442  int i;
19443
19444  zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
19445  n--;
19446  if( zBlob ){
19447    for(i=0; i<n; i+=2){
19448      zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
19449    }
19450    zBlob[i/2] = 0;
19451  }
19452  return zBlob;
19453}
19454#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
19455
19456/*
19457** Log an error that is an API call on a connection pointer that should
19458** not have been used.  The "type" of connection pointer is given as the
19459** argument.  The zType is a word like "NULL" or "closed" or "invalid".
19460*/
19461static void logBadConnection(const char *zType){
19462  sqlite3_log(SQLITE_MISUSE,
19463     "API call with %s database connection pointer",
19464     zType
19465  );
19466}
19467
19468/*
19469** Check to make sure we have a valid db pointer.  This test is not
19470** foolproof but it does provide some measure of protection against
19471** misuse of the interface such as passing in db pointers that are
19472** NULL or which have been previously closed.  If this routine returns
19473** 1 it means that the db pointer is valid and 0 if it should not be
19474** dereferenced for any reason.  The calling function should invoke
19475** SQLITE_MISUSE immediately.
19476**
19477** sqlite3SafetyCheckOk() requires that the db pointer be valid for
19478** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
19479** open properly and is not fit for general use but which can be
19480** used as an argument to sqlite3_errmsg() or sqlite3_close().
19481*/
19482SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
19483  u32 magic;
19484  if( db==0 ){
19485    logBadConnection("NULL");
19486    return 0;
19487  }
19488  magic = db->magic;
19489  if( magic!=SQLITE_MAGIC_OPEN ){
19490    if( !sqlite3SafetyCheckSickOrOk(db) ){
19491      logBadConnection("unopened");
19492    }
19493    return 0;
19494  }else{
19495    return 1;
19496  }
19497}
19498SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
19499  u32 magic;
19500  magic = db->magic;
19501  if( magic!=SQLITE_MAGIC_SICK &&
19502      magic!=SQLITE_MAGIC_OPEN &&
19503      magic!=SQLITE_MAGIC_BUSY ){
19504    logBadConnection("invalid");
19505    return 0;
19506  }else{
19507    return 1;
19508  }
19509}
19510
19511/************** End of util.c ************************************************/
19512/************** Begin file hash.c ********************************************/
19513/*
19514** 2001 September 22
19515**
19516** The author disclaims copyright to this source code.  In place of
19517** a legal notice, here is a blessing:
19518**
19519**    May you do good and not evil.
19520**    May you find forgiveness for yourself and forgive others.
19521**    May you share freely, never taking more than you give.
19522**
19523*************************************************************************
19524** This is the implementation of generic hash-tables
19525** used in SQLite.
19526*/
19527
19528/* Turn bulk memory into a hash table object by initializing the
19529** fields of the Hash structure.
19530**
19531** "pNew" is a pointer to the hash table that is to be initialized.
19532*/
19533SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
19534  assert( pNew!=0 );
19535  pNew->first = 0;
19536  pNew->count = 0;
19537  pNew->htsize = 0;
19538  pNew->ht = 0;
19539}
19540
19541/* Remove all entries from a hash table.  Reclaim all memory.
19542** Call this routine to delete a hash table or to reset a hash table
19543** to the empty state.
19544*/
19545SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
19546  HashElem *elem;         /* For looping over all elements of the table */
19547
19548  assert( pH!=0 );
19549  elem = pH->first;
19550  pH->first = 0;
19551  sqlite3_free(pH->ht);
19552  pH->ht = 0;
19553  pH->htsize = 0;
19554  while( elem ){
19555    HashElem *next_elem = elem->next;
19556    sqlite3_free(elem);
19557    elem = next_elem;
19558  }
19559  pH->count = 0;
19560}
19561
19562/*
19563** The hashing function.
19564*/
19565static unsigned int strHash(const char *z, int nKey){
19566  int h = 0;
19567  assert( nKey>=0 );
19568  while( nKey > 0  ){
19569    h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
19570    nKey--;
19571  }
19572  return h;
19573}
19574
19575
19576/* Link pNew element into the hash table pH.  If pEntry!=0 then also
19577** insert pNew into the pEntry hash bucket.
19578*/
19579static void insertElement(
19580  Hash *pH,              /* The complete hash table */
19581  struct _ht *pEntry,    /* The entry into which pNew is inserted */
19582  HashElem *pNew         /* The element to be inserted */
19583){
19584  HashElem *pHead;       /* First element already in pEntry */
19585  if( pEntry ){
19586    pHead = pEntry->count ? pEntry->chain : 0;
19587    pEntry->count++;
19588    pEntry->chain = pNew;
19589  }else{
19590    pHead = 0;
19591  }
19592  if( pHead ){
19593    pNew->next = pHead;
19594    pNew->prev = pHead->prev;
19595    if( pHead->prev ){ pHead->prev->next = pNew; }
19596    else             { pH->first = pNew; }
19597    pHead->prev = pNew;
19598  }else{
19599    pNew->next = pH->first;
19600    if( pH->first ){ pH->first->prev = pNew; }
19601    pNew->prev = 0;
19602    pH->first = pNew;
19603  }
19604}
19605
19606
19607/* Resize the hash table so that it cantains "new_size" buckets.
19608**
19609** The hash table might fail to resize if sqlite3_malloc() fails or
19610** if the new size is the same as the prior size.
19611** Return TRUE if the resize occurs and false if not.
19612*/
19613static int rehash(Hash *pH, unsigned int new_size){
19614  struct _ht *new_ht;            /* The new hash table */
19615  HashElem *elem, *next_elem;    /* For looping over existing elements */
19616
19617#if SQLITE_MALLOC_SOFT_LIMIT>0
19618  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
19619    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
19620  }
19621  if( new_size==pH->htsize ) return 0;
19622#endif
19623
19624  /* The inability to allocates space for a larger hash table is
19625  ** a performance hit but it is not a fatal error.  So mark the
19626  ** allocation as a benign.
19627  */
19628  sqlite3BeginBenignMalloc();
19629  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
19630  sqlite3EndBenignMalloc();
19631
19632  if( new_ht==0 ) return 0;
19633  sqlite3_free(pH->ht);
19634  pH->ht = new_ht;
19635  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
19636  memset(new_ht, 0, new_size*sizeof(struct _ht));
19637  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
19638    unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
19639    next_elem = elem->next;
19640    insertElement(pH, &new_ht[h], elem);
19641  }
19642  return 1;
19643}
19644
19645/* This function (for internal use only) locates an element in an
19646** hash table that matches the given key.  The hash for this key has
19647** already been computed and is passed as the 4th parameter.
19648*/
19649static HashElem *findElementGivenHash(
19650  const Hash *pH,     /* The pH to be searched */
19651  const char *pKey,   /* The key we are searching for */
19652  int nKey,           /* Bytes in key (not counting zero terminator) */
19653  unsigned int h      /* The hash for this key. */
19654){
19655  HashElem *elem;                /* Used to loop thru the element list */
19656  int count;                     /* Number of elements left to test */
19657
19658  if( pH->ht ){
19659    struct _ht *pEntry = &pH->ht[h];
19660    elem = pEntry->chain;
19661    count = pEntry->count;
19662  }else{
19663    elem = pH->first;
19664    count = pH->count;
19665  }
19666  while( count-- && ALWAYS(elem) ){
19667    if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
19668      return elem;
19669    }
19670    elem = elem->next;
19671  }
19672  return 0;
19673}
19674
19675/* Remove a single entry from the hash table given a pointer to that
19676** element and a hash on the element's key.
19677*/
19678static void removeElementGivenHash(
19679  Hash *pH,         /* The pH containing "elem" */
19680  HashElem* elem,   /* The element to be removed from the pH */
19681  unsigned int h    /* Hash value for the element */
19682){
19683  struct _ht *pEntry;
19684  if( elem->prev ){
19685    elem->prev->next = elem->next;
19686  }else{
19687    pH->first = elem->next;
19688  }
19689  if( elem->next ){
19690    elem->next->prev = elem->prev;
19691  }
19692  if( pH->ht ){
19693    pEntry = &pH->ht[h];
19694    if( pEntry->chain==elem ){
19695      pEntry->chain = elem->next;
19696    }
19697    pEntry->count--;
19698    assert( pEntry->count>=0 );
19699  }
19700  sqlite3_free( elem );
19701  pH->count--;
19702  if( pH->count<=0 ){
19703    assert( pH->first==0 );
19704    assert( pH->count==0 );
19705    sqlite3HashClear(pH);
19706  }
19707}
19708
19709/* Attempt to locate an element of the hash table pH with a key
19710** that matches pKey,nKey.  Return the data for this element if it is
19711** found, or NULL if there is no match.
19712*/
19713SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
19714  HashElem *elem;    /* The element that matches key */
19715  unsigned int h;    /* A hash on key */
19716
19717  assert( pH!=0 );
19718  assert( pKey!=0 );
19719  assert( nKey>=0 );
19720  if( pH->ht ){
19721    h = strHash(pKey, nKey) % pH->htsize;
19722  }else{
19723    h = 0;
19724  }
19725  elem = findElementGivenHash(pH, pKey, nKey, h);
19726  return elem ? elem->data : 0;
19727}
19728
19729/* Insert an element into the hash table pH.  The key is pKey,nKey
19730** and the data is "data".
19731**
19732** If no element exists with a matching key, then a new
19733** element is created and NULL is returned.
19734**
19735** If another element already exists with the same key, then the
19736** new data replaces the old data and the old data is returned.
19737** The key is not copied in this instance.  If a malloc fails, then
19738** the new data is returned and the hash table is unchanged.
19739**
19740** If the "data" parameter to this function is NULL, then the
19741** element corresponding to "key" is removed from the hash table.
19742*/
19743SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
19744  unsigned int h;       /* the hash of the key modulo hash table size */
19745  HashElem *elem;       /* Used to loop thru the element list */
19746  HashElem *new_elem;   /* New element added to the pH */
19747
19748  assert( pH!=0 );
19749  assert( pKey!=0 );
19750  assert( nKey>=0 );
19751  if( pH->htsize ){
19752    h = strHash(pKey, nKey) % pH->htsize;
19753  }else{
19754    h = 0;
19755  }
19756  elem = findElementGivenHash(pH,pKey,nKey,h);
19757  if( elem ){
19758    void *old_data = elem->data;
19759    if( data==0 ){
19760      removeElementGivenHash(pH,elem,h);
19761    }else{
19762      elem->data = data;
19763      elem->pKey = pKey;
19764      assert(nKey==elem->nKey);
19765    }
19766    return old_data;
19767  }
19768  if( data==0 ) return 0;
19769  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
19770  if( new_elem==0 ) return data;
19771  new_elem->pKey = pKey;
19772  new_elem->nKey = nKey;
19773  new_elem->data = data;
19774  pH->count++;
19775  if( pH->count>=10 && pH->count > 2*pH->htsize ){
19776    if( rehash(pH, pH->count*2) ){
19777      assert( pH->htsize>0 );
19778      h = strHash(pKey, nKey) % pH->htsize;
19779    }
19780  }
19781  if( pH->ht ){
19782    insertElement(pH, &pH->ht[h], new_elem);
19783  }else{
19784    insertElement(pH, 0, new_elem);
19785  }
19786  return 0;
19787}
19788
19789/************** End of hash.c ************************************************/
19790/************** Begin file opcodes.c *****************************************/
19791/* Automatically generated.  Do not edit */
19792/* See the mkopcodec.awk script for details. */
19793#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
19794SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
19795 static const char *const azName[] = { "?",
19796     /*   1 */ "Goto",
19797     /*   2 */ "Gosub",
19798     /*   3 */ "Return",
19799     /*   4 */ "Yield",
19800     /*   5 */ "HaltIfNull",
19801     /*   6 */ "Halt",
19802     /*   7 */ "Integer",
19803     /*   8 */ "Int64",
19804     /*   9 */ "String",
19805     /*  10 */ "Null",
19806     /*  11 */ "Blob",
19807     /*  12 */ "Variable",
19808     /*  13 */ "Move",
19809     /*  14 */ "Copy",
19810     /*  15 */ "SCopy",
19811     /*  16 */ "ResultRow",
19812     /*  17 */ "CollSeq",
19813     /*  18 */ "Function",
19814     /*  19 */ "Not",
19815     /*  20 */ "AddImm",
19816     /*  21 */ "MustBeInt",
19817     /*  22 */ "RealAffinity",
19818     /*  23 */ "Permutation",
19819     /*  24 */ "Compare",
19820     /*  25 */ "Jump",
19821     /*  26 */ "If",
19822     /*  27 */ "IfNot",
19823     /*  28 */ "Column",
19824     /*  29 */ "Affinity",
19825     /*  30 */ "MakeRecord",
19826     /*  31 */ "Count",
19827     /*  32 */ "Savepoint",
19828     /*  33 */ "AutoCommit",
19829     /*  34 */ "Transaction",
19830     /*  35 */ "ReadCookie",
19831     /*  36 */ "SetCookie",
19832     /*  37 */ "VerifyCookie",
19833     /*  38 */ "OpenRead",
19834     /*  39 */ "OpenWrite",
19835     /*  40 */ "OpenEphemeral",
19836     /*  41 */ "OpenPseudo",
19837     /*  42 */ "Close",
19838     /*  43 */ "SeekLt",
19839     /*  44 */ "SeekLe",
19840     /*  45 */ "SeekGe",
19841     /*  46 */ "SeekGt",
19842     /*  47 */ "Seek",
19843     /*  48 */ "NotFound",
19844     /*  49 */ "Found",
19845     /*  50 */ "IsUnique",
19846     /*  51 */ "NotExists",
19847     /*  52 */ "Sequence",
19848     /*  53 */ "NewRowid",
19849     /*  54 */ "Insert",
19850     /*  55 */ "InsertInt",
19851     /*  56 */ "Delete",
19852     /*  57 */ "ResetCount",
19853     /*  58 */ "RowKey",
19854     /*  59 */ "RowData",
19855     /*  60 */ "Rowid",
19856     /*  61 */ "NullRow",
19857     /*  62 */ "Last",
19858     /*  63 */ "Sort",
19859     /*  64 */ "Rewind",
19860     /*  65 */ "Prev",
19861     /*  66 */ "Next",
19862     /*  67 */ "IdxInsert",
19863     /*  68 */ "Or",
19864     /*  69 */ "And",
19865     /*  70 */ "IdxDelete",
19866     /*  71 */ "IdxRowid",
19867     /*  72 */ "IdxLT",
19868     /*  73 */ "IsNull",
19869     /*  74 */ "NotNull",
19870     /*  75 */ "Ne",
19871     /*  76 */ "Eq",
19872     /*  77 */ "Gt",
19873     /*  78 */ "Le",
19874     /*  79 */ "Lt",
19875     /*  80 */ "Ge",
19876     /*  81 */ "IdxGE",
19877     /*  82 */ "BitAnd",
19878     /*  83 */ "BitOr",
19879     /*  84 */ "ShiftLeft",
19880     /*  85 */ "ShiftRight",
19881     /*  86 */ "Add",
19882     /*  87 */ "Subtract",
19883     /*  88 */ "Multiply",
19884     /*  89 */ "Divide",
19885     /*  90 */ "Remainder",
19886     /*  91 */ "Concat",
19887     /*  92 */ "Destroy",
19888     /*  93 */ "BitNot",
19889     /*  94 */ "String8",
19890     /*  95 */ "Clear",
19891     /*  96 */ "CreateIndex",
19892     /*  97 */ "CreateTable",
19893     /*  98 */ "ParseSchema",
19894     /*  99 */ "LoadAnalysis",
19895     /* 100 */ "DropTable",
19896     /* 101 */ "DropIndex",
19897     /* 102 */ "DropTrigger",
19898     /* 103 */ "IntegrityCk",
19899     /* 104 */ "RowSetAdd",
19900     /* 105 */ "RowSetRead",
19901     /* 106 */ "RowSetTest",
19902     /* 107 */ "Program",
19903     /* 108 */ "Param",
19904     /* 109 */ "FkCounter",
19905     /* 110 */ "FkIfZero",
19906     /* 111 */ "MemMax",
19907     /* 112 */ "IfPos",
19908     /* 113 */ "IfNeg",
19909     /* 114 */ "IfZero",
19910     /* 115 */ "AggStep",
19911     /* 116 */ "AggFinal",
19912     /* 117 */ "Vacuum",
19913     /* 118 */ "IncrVacuum",
19914     /* 119 */ "Expire",
19915     /* 120 */ "TableLock",
19916     /* 121 */ "VBegin",
19917     /* 122 */ "VCreate",
19918     /* 123 */ "VDestroy",
19919     /* 124 */ "VOpen",
19920     /* 125 */ "VFilter",
19921     /* 126 */ "VColumn",
19922     /* 127 */ "VNext",
19923     /* 128 */ "VRename",
19924     /* 129 */ "VUpdate",
19925     /* 130 */ "Real",
19926     /* 131 */ "Pagecount",
19927     /* 132 */ "Trace",
19928     /* 133 */ "Noop",
19929     /* 134 */ "Explain",
19930     /* 135 */ "NotUsed_135",
19931     /* 136 */ "NotUsed_136",
19932     /* 137 */ "NotUsed_137",
19933     /* 138 */ "NotUsed_138",
19934     /* 139 */ "NotUsed_139",
19935     /* 140 */ "NotUsed_140",
19936     /* 141 */ "ToText",
19937     /* 142 */ "ToBlob",
19938     /* 143 */ "ToNumeric",
19939     /* 144 */ "ToInt",
19940     /* 145 */ "ToReal",
19941  };
19942  return azName[i];
19943}
19944#endif
19945
19946/************** End of opcodes.c *********************************************/
19947/************** Begin file os_os2.c ******************************************/
19948/*
19949** 2006 Feb 14
19950**
19951** The author disclaims copyright to this source code.  In place of
19952** a legal notice, here is a blessing:
19953**
19954**    May you do good and not evil.
19955**    May you find forgiveness for yourself and forgive others.
19956**    May you share freely, never taking more than you give.
19957**
19958******************************************************************************
19959**
19960** This file contains code that is specific to OS/2.
19961*/
19962
19963
19964#if SQLITE_OS_OS2
19965
19966/*
19967** A Note About Memory Allocation:
19968**
19969** This driver uses malloc()/free() directly rather than going through
19970** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
19971** are designed for use on embedded systems where memory is scarce and
19972** malloc failures happen frequently.  OS/2 does not typically run on
19973** embedded systems, and when it does the developers normally have bigger
19974** problems to worry about than running out of memory.  So there is not
19975** a compelling need to use the wrappers.
19976**
19977** But there is a good reason to not use the wrappers.  If we use the
19978** wrappers then we will get simulated malloc() failures within this
19979** driver.  And that causes all kinds of problems for our tests.  We
19980** could enhance SQLite to deal with simulated malloc failures within
19981** the OS driver, but the code to deal with those failure would not
19982** be exercised on Linux (which does not need to malloc() in the driver)
19983** and so we would have difficulty writing coverage tests for that
19984** code.  Better to leave the code out, we think.
19985**
19986** The point of this discussion is as follows:  When creating a new
19987** OS layer for an embedded system, if you use this file as an example,
19988** avoid the use of malloc()/free().  Those routines work ok on OS/2
19989** desktops but not so well in embedded systems.
19990*/
19991
19992/*
19993** Macros used to determine whether or not to use threads.
19994*/
19995#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
19996# define SQLITE_OS2_THREADS 1
19997#endif
19998
19999/*
20000** Include code that is common to all os_*.c files
20001*/
20002/************** Include os_common.h in the middle of os_os2.c ****************/
20003/************** Begin file os_common.h ***************************************/
20004/*
20005** 2004 May 22
20006**
20007** The author disclaims copyright to this source code.  In place of
20008** a legal notice, here is a blessing:
20009**
20010**    May you do good and not evil.
20011**    May you find forgiveness for yourself and forgive others.
20012**    May you share freely, never taking more than you give.
20013**
20014******************************************************************************
20015**
20016** This file contains macros and a little bit of code that is common to
20017** all of the platform-specific files (os_*.c) and is #included into those
20018** files.
20019**
20020** This file should be #included by the os_*.c files only.  It is not a
20021** general purpose header file.
20022*/
20023#ifndef _OS_COMMON_H_
20024#define _OS_COMMON_H_
20025
20026/*
20027** At least two bugs have slipped in because we changed the MEMORY_DEBUG
20028** macro to SQLITE_DEBUG and some older makefiles have not yet made the
20029** switch.  The following code should catch this problem at compile-time.
20030*/
20031#ifdef MEMORY_DEBUG
20032# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
20033#endif
20034
20035#ifdef SQLITE_DEBUG
20036SQLITE_PRIVATE int sqlite3OSTrace = 0;
20037#define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
20038#define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
20039#define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
20040#define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
20041#define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
20042#define OSTRACE6(X,Y,Z,A,B,C) \
20043    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
20044#define OSTRACE7(X,Y,Z,A,B,C,D) \
20045    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
20046#else
20047#define OSTRACE1(X)
20048#define OSTRACE2(X,Y)
20049#define OSTRACE3(X,Y,Z)
20050#define OSTRACE4(X,Y,Z,A)
20051#define OSTRACE5(X,Y,Z,A,B)
20052#define OSTRACE6(X,Y,Z,A,B,C)
20053#define OSTRACE7(X,Y,Z,A,B,C,D)
20054#endif
20055
20056/*
20057** Macros for performance tracing.  Normally turned off.  Only works
20058** on i486 hardware.
20059*/
20060#ifdef SQLITE_PERFORMANCE_TRACE
20061
20062/*
20063** hwtime.h contains inline assembler code for implementing
20064** high-performance timing routines.
20065*/
20066/************** Include hwtime.h in the middle of os_common.h ****************/
20067/************** Begin file hwtime.h ******************************************/
20068/*
20069** 2008 May 27
20070**
20071** The author disclaims copyright to this source code.  In place of
20072** a legal notice, here is a blessing:
20073**
20074**    May you do good and not evil.
20075**    May you find forgiveness for yourself and forgive others.
20076**    May you share freely, never taking more than you give.
20077**
20078******************************************************************************
20079**
20080** This file contains inline asm code for retrieving "high-performance"
20081** counters for x86 class CPUs.
20082*/
20083#ifndef _HWTIME_H_
20084#define _HWTIME_H_
20085
20086/*
20087** The following routine only works on pentium-class (or newer) processors.
20088** It uses the RDTSC opcode to read the cycle count value out of the
20089** processor and returns that value.  This can be used for high-res
20090** profiling.
20091*/
20092#if (defined(__GNUC__) || defined(_MSC_VER)) && \
20093      (defined(i386) || defined(__i386__) || defined(_M_IX86))
20094
20095  #if defined(__GNUC__)
20096
20097  __inline__ sqlite_uint64 sqlite3Hwtime(void){
20098     unsigned int lo, hi;
20099     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
20100     return (sqlite_uint64)hi << 32 | lo;
20101  }
20102
20103  #elif defined(_MSC_VER)
20104
20105  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
20106     __asm {
20107        rdtsc
20108        ret       ; return value at EDX:EAX
20109     }
20110  }
20111
20112  #endif
20113
20114#elif (defined(__GNUC__) && defined(__x86_64__))
20115
20116  __inline__ sqlite_uint64 sqlite3Hwtime(void){
20117      unsigned long val;
20118      __asm__ __volatile__ ("rdtsc" : "=A" (val));
20119      return val;
20120  }
20121
20122#elif (defined(__GNUC__) && defined(__ppc__))
20123
20124  __inline__ sqlite_uint64 sqlite3Hwtime(void){
20125      unsigned long long retval;
20126      unsigned long junk;
20127      __asm__ __volatile__ ("\n\
20128          1:      mftbu   %1\n\
20129                  mftb    %L0\n\
20130                  mftbu   %0\n\
20131                  cmpw    %0,%1\n\
20132                  bne     1b"
20133                  : "=r" (retval), "=r" (junk));
20134      return retval;
20135  }
20136
20137#else
20138
20139  #error Need implementation of sqlite3Hwtime() for your platform.
20140
20141  /*
20142  ** To compile without implementing sqlite3Hwtime() for your platform,
20143  ** you can remove the above #error and use the following
20144  ** stub function.  You will lose timing support for many
20145  ** of the debugging and testing utilities, but it should at
20146  ** least compile and run.
20147  */
20148SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
20149
20150#endif
20151
20152#endif /* !defined(_HWTIME_H_) */
20153
20154/************** End of hwtime.h **********************************************/
20155/************** Continuing where we left off in os_common.h ******************/
20156
20157static sqlite_uint64 g_start;
20158static sqlite_uint64 g_elapsed;
20159#define TIMER_START       g_start=sqlite3Hwtime()
20160#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
20161#define TIMER_ELAPSED     g_elapsed
20162#else
20163#define TIMER_START
20164#define TIMER_END
20165#define TIMER_ELAPSED     ((sqlite_uint64)0)
20166#endif
20167
20168/*
20169** If we compile with the SQLITE_TEST macro set, then the following block
20170** of code will give us the ability to simulate a disk I/O error.  This
20171** is used for testing the I/O recovery logic.
20172*/
20173#ifdef SQLITE_TEST
20174SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
20175SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
20176SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
20177SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
20178SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
20179SQLITE_API int sqlite3_diskfull_pending = 0;
20180SQLITE_API int sqlite3_diskfull = 0;
20181#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
20182#define SimulateIOError(CODE)  \
20183  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
20184       || sqlite3_io_error_pending-- == 1 )  \
20185              { local_ioerr(); CODE; }
20186static void local_ioerr(){
20187  IOTRACE(("IOERR\n"));
20188  sqlite3_io_error_hit++;
20189  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
20190}
20191#define SimulateDiskfullError(CODE) \
20192   if( sqlite3_diskfull_pending ){ \
20193     if( sqlite3_diskfull_pending == 1 ){ \
20194       local_ioerr(); \
20195       sqlite3_diskfull = 1; \
20196       sqlite3_io_error_hit = 1; \
20197       CODE; \
20198     }else{ \
20199       sqlite3_diskfull_pending--; \
20200     } \
20201   }
20202#else
20203#define SimulateIOErrorBenign(X)
20204#define SimulateIOError(A)
20205#define SimulateDiskfullError(A)
20206#endif
20207
20208/*
20209** When testing, keep a count of the number of open files.
20210*/
20211#ifdef SQLITE_TEST
20212SQLITE_API int sqlite3_open_file_count = 0;
20213#define OpenCounter(X)  sqlite3_open_file_count+=(X)
20214#else
20215#define OpenCounter(X)
20216#endif
20217
20218#endif /* !defined(_OS_COMMON_H_) */
20219
20220/************** End of os_common.h *******************************************/
20221/************** Continuing where we left off in os_os2.c *********************/
20222
20223/*
20224** The os2File structure is subclass of sqlite3_file specific for the OS/2
20225** protability layer.
20226*/
20227typedef struct os2File os2File;
20228struct os2File {
20229  const sqlite3_io_methods *pMethod;  /* Always the first entry */
20230  HFILE h;                  /* Handle for accessing the file */
20231  char* pathToDel;          /* Name of file to delete on close, NULL if not */
20232  unsigned char locktype;   /* Type of lock currently held on this file */
20233};
20234
20235#define LOCK_TIMEOUT 10L /* the default locking timeout */
20236
20237/*****************************************************************************
20238** The next group of routines implement the I/O methods specified
20239** by the sqlite3_io_methods object.
20240******************************************************************************/
20241
20242/*
20243** Close a file.
20244*/
20245static int os2Close( sqlite3_file *id ){
20246  APIRET rc = NO_ERROR;
20247  os2File *pFile;
20248  if( id && (pFile = (os2File*)id) != 0 ){
20249    OSTRACE2( "CLOSE %d\n", pFile->h );
20250    rc = DosClose( pFile->h );
20251    pFile->locktype = NO_LOCK;
20252    if( pFile->pathToDel != NULL ){
20253      rc = DosForceDelete( (PSZ)pFile->pathToDel );
20254      free( pFile->pathToDel );
20255      pFile->pathToDel = NULL;
20256    }
20257    id = 0;
20258    OpenCounter( -1 );
20259  }
20260
20261  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20262}
20263
20264/*
20265** Read data from a file into a buffer.  Return SQLITE_OK if all
20266** bytes were read successfully and SQLITE_IOERR if anything goes
20267** wrong.
20268*/
20269static int os2Read(
20270  sqlite3_file *id,               /* File to read from */
20271  void *pBuf,                     /* Write content into this buffer */
20272  int amt,                        /* Number of bytes to read */
20273  sqlite3_int64 offset            /* Begin reading at this offset */
20274){
20275  ULONG fileLocation = 0L;
20276  ULONG got;
20277  os2File *pFile = (os2File*)id;
20278  assert( id!=0 );
20279  SimulateIOError( return SQLITE_IOERR_READ );
20280  OSTRACE3( "READ %d lock=%d\n", pFile->h, pFile->locktype );
20281  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20282    return SQLITE_IOERR;
20283  }
20284  if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
20285    return SQLITE_IOERR_READ;
20286  }
20287  if( got == (ULONG)amt )
20288    return SQLITE_OK;
20289  else {
20290    /* Unread portions of the input buffer must be zero-filled */
20291    memset(&((char*)pBuf)[got], 0, amt-got);
20292    return SQLITE_IOERR_SHORT_READ;
20293  }
20294}
20295
20296/*
20297** Write data from a buffer into a file.  Return SQLITE_OK on success
20298** or some other error code on failure.
20299*/
20300static int os2Write(
20301  sqlite3_file *id,               /* File to write into */
20302  const void *pBuf,               /* The bytes to be written */
20303  int amt,                        /* Number of bytes to write */
20304  sqlite3_int64 offset            /* Offset into the file to begin writing at */
20305){
20306  ULONG fileLocation = 0L;
20307  APIRET rc = NO_ERROR;
20308  ULONG wrote;
20309  os2File *pFile = (os2File*)id;
20310  assert( id!=0 );
20311  SimulateIOError( return SQLITE_IOERR_WRITE );
20312  SimulateDiskfullError( return SQLITE_FULL );
20313  OSTRACE3( "WRITE %d lock=%d\n", pFile->h, pFile->locktype );
20314  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20315    return SQLITE_IOERR;
20316  }
20317  assert( amt>0 );
20318  while( amt > 0 &&
20319         ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
20320         wrote > 0
20321  ){
20322    amt -= wrote;
20323    pBuf = &((char*)pBuf)[wrote];
20324  }
20325
20326  return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
20327}
20328
20329/*
20330** Truncate an open file to a specified size
20331*/
20332static int os2Truncate( sqlite3_file *id, i64 nByte ){
20333  APIRET rc = NO_ERROR;
20334  os2File *pFile = (os2File*)id;
20335  OSTRACE3( "TRUNCATE %d %lld\n", pFile->h, nByte );
20336  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
20337  rc = DosSetFileSize( pFile->h, nByte );
20338  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
20339}
20340
20341#ifdef SQLITE_TEST
20342/*
20343** Count the number of fullsyncs and normal syncs.  This is used to test
20344** that syncs and fullsyncs are occuring at the right times.
20345*/
20346SQLITE_API int sqlite3_sync_count = 0;
20347SQLITE_API int sqlite3_fullsync_count = 0;
20348#endif
20349
20350/*
20351** Make sure all writes to a particular file are committed to disk.
20352*/
20353static int os2Sync( sqlite3_file *id, int flags ){
20354  os2File *pFile = (os2File*)id;
20355  OSTRACE3( "SYNC %d lock=%d\n", pFile->h, pFile->locktype );
20356#ifdef SQLITE_TEST
20357  if( flags & SQLITE_SYNC_FULL){
20358    sqlite3_fullsync_count++;
20359  }
20360  sqlite3_sync_count++;
20361#endif
20362  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
20363  ** no-op
20364  */
20365#ifdef SQLITE_NO_SYNC
20366  UNUSED_PARAMETER(pFile);
20367  return SQLITE_OK;
20368#else
20369  return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20370#endif
20371}
20372
20373/*
20374** Determine the current size of a file in bytes
20375*/
20376static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
20377  APIRET rc = NO_ERROR;
20378  FILESTATUS3 fsts3FileInfo;
20379  memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
20380  assert( id!=0 );
20381  SimulateIOError( return SQLITE_IOERR_FSTAT );
20382  rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
20383  if( rc == NO_ERROR ){
20384    *pSize = fsts3FileInfo.cbFile;
20385    return SQLITE_OK;
20386  }else{
20387    return SQLITE_IOERR_FSTAT;
20388  }
20389}
20390
20391/*
20392** Acquire a reader lock.
20393*/
20394static int getReadLock( os2File *pFile ){
20395  FILELOCK  LockArea,
20396            UnlockArea;
20397  APIRET res;
20398  memset(&LockArea, 0, sizeof(LockArea));
20399  memset(&UnlockArea, 0, sizeof(UnlockArea));
20400  LockArea.lOffset = SHARED_FIRST;
20401  LockArea.lRange = SHARED_SIZE;
20402  UnlockArea.lOffset = 0L;
20403  UnlockArea.lRange = 0L;
20404  res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20405  OSTRACE3( "GETREADLOCK %d res=%d\n", pFile->h, res );
20406  return res;
20407}
20408
20409/*
20410** Undo a readlock
20411*/
20412static int unlockReadLock( os2File *id ){
20413  FILELOCK  LockArea,
20414            UnlockArea;
20415  APIRET res;
20416  memset(&LockArea, 0, sizeof(LockArea));
20417  memset(&UnlockArea, 0, sizeof(UnlockArea));
20418  LockArea.lOffset = 0L;
20419  LockArea.lRange = 0L;
20420  UnlockArea.lOffset = SHARED_FIRST;
20421  UnlockArea.lRange = SHARED_SIZE;
20422  res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20423  OSTRACE3( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res );
20424  return res;
20425}
20426
20427/*
20428** Lock the file with the lock specified by parameter locktype - one
20429** of the following:
20430**
20431**     (1) SHARED_LOCK
20432**     (2) RESERVED_LOCK
20433**     (3) PENDING_LOCK
20434**     (4) EXCLUSIVE_LOCK
20435**
20436** Sometimes when requesting one lock state, additional lock states
20437** are inserted in between.  The locking might fail on one of the later
20438** transitions leaving the lock state different from what it started but
20439** still short of its goal.  The following chart shows the allowed
20440** transitions and the inserted intermediate states:
20441**
20442**    UNLOCKED -> SHARED
20443**    SHARED -> RESERVED
20444**    SHARED -> (PENDING) -> EXCLUSIVE
20445**    RESERVED -> (PENDING) -> EXCLUSIVE
20446**    PENDING -> EXCLUSIVE
20447**
20448** This routine will only increase a lock.  The os2Unlock() routine
20449** erases all locks at once and returns us immediately to locking level 0.
20450** It is not possible to lower the locking level one step at a time.  You
20451** must go straight to locking level 0.
20452*/
20453static int os2Lock( sqlite3_file *id, int locktype ){
20454  int rc = SQLITE_OK;       /* Return code from subroutines */
20455  APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
20456  int newLocktype;       /* Set pFile->locktype to this value before exiting */
20457  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
20458  FILELOCK  LockArea,
20459            UnlockArea;
20460  os2File *pFile = (os2File*)id;
20461  memset(&LockArea, 0, sizeof(LockArea));
20462  memset(&UnlockArea, 0, sizeof(UnlockArea));
20463  assert( pFile!=0 );
20464  OSTRACE4( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype );
20465
20466  /* If there is already a lock of this type or more restrictive on the
20467  ** os2File, do nothing. Don't use the end_lock: exit path, as
20468  ** sqlite3_mutex_enter() hasn't been called yet.
20469  */
20470  if( pFile->locktype>=locktype ){
20471    OSTRACE3( "LOCK %d %d ok (already held)\n", pFile->h, locktype );
20472    return SQLITE_OK;
20473  }
20474
20475  /* Make sure the locking sequence is correct
20476  */
20477  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
20478  assert( locktype!=PENDING_LOCK );
20479  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
20480
20481  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
20482  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
20483  ** the PENDING_LOCK byte is temporary.
20484  */
20485  newLocktype = pFile->locktype;
20486  if( pFile->locktype==NO_LOCK
20487      || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
20488  ){
20489    LockArea.lOffset = PENDING_BYTE;
20490    LockArea.lRange = 1L;
20491    UnlockArea.lOffset = 0L;
20492    UnlockArea.lRange = 0L;
20493
20494    /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
20495    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
20496    if( res == NO_ERROR ){
20497      gotPendingLock = 1;
20498      OSTRACE3( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res );
20499    }
20500  }
20501
20502  /* Acquire a shared lock
20503  */
20504  if( locktype==SHARED_LOCK && res == NO_ERROR ){
20505    assert( pFile->locktype==NO_LOCK );
20506    res = getReadLock(pFile);
20507    if( res == NO_ERROR ){
20508      newLocktype = SHARED_LOCK;
20509    }
20510    OSTRACE3( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res );
20511  }
20512
20513  /* Acquire a RESERVED lock
20514  */
20515  if( locktype==RESERVED_LOCK && res == NO_ERROR ){
20516    assert( pFile->locktype==SHARED_LOCK );
20517    LockArea.lOffset = RESERVED_BYTE;
20518    LockArea.lRange = 1L;
20519    UnlockArea.lOffset = 0L;
20520    UnlockArea.lRange = 0L;
20521    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20522    if( res == NO_ERROR ){
20523      newLocktype = RESERVED_LOCK;
20524    }
20525    OSTRACE3( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res );
20526  }
20527
20528  /* Acquire a PENDING lock
20529  */
20530  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
20531    newLocktype = PENDING_LOCK;
20532    gotPendingLock = 0;
20533    OSTRACE2( "LOCK %d acquire pending lock. pending lock boolean unset.\n", pFile->h );
20534  }
20535
20536  /* Acquire an EXCLUSIVE lock
20537  */
20538  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
20539    assert( pFile->locktype>=SHARED_LOCK );
20540    res = unlockReadLock(pFile);
20541    OSTRACE2( "unreadlock = %d\n", res );
20542    LockArea.lOffset = SHARED_FIRST;
20543    LockArea.lRange = SHARED_SIZE;
20544    UnlockArea.lOffset = 0L;
20545    UnlockArea.lRange = 0L;
20546    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20547    if( res == NO_ERROR ){
20548      newLocktype = EXCLUSIVE_LOCK;
20549    }else{
20550      OSTRACE2( "OS/2 error-code = %d\n", res );
20551      getReadLock(pFile);
20552    }
20553    OSTRACE3( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res );
20554  }
20555
20556  /* If we are holding a PENDING lock that ought to be released, then
20557  ** release it now.
20558  */
20559  if( gotPendingLock && locktype==SHARED_LOCK ){
20560    int r;
20561    LockArea.lOffset = 0L;
20562    LockArea.lRange = 0L;
20563    UnlockArea.lOffset = PENDING_BYTE;
20564    UnlockArea.lRange = 1L;
20565    r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20566    OSTRACE3( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r );
20567  }
20568
20569  /* Update the state of the lock has held in the file descriptor then
20570  ** return the appropriate result code.
20571  */
20572  if( res == NO_ERROR ){
20573    rc = SQLITE_OK;
20574  }else{
20575    OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
20576              locktype, newLocktype );
20577    rc = SQLITE_BUSY;
20578  }
20579  pFile->locktype = newLocktype;
20580  OSTRACE3( "LOCK %d now %d\n", pFile->h, pFile->locktype );
20581  return rc;
20582}
20583
20584/*
20585** This routine checks if there is a RESERVED lock held on the specified
20586** file by this or any other process. If such a lock is held, return
20587** non-zero, otherwise zero.
20588*/
20589static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
20590  int r = 0;
20591  os2File *pFile = (os2File*)id;
20592  assert( pFile!=0 );
20593  if( pFile->locktype>=RESERVED_LOCK ){
20594    r = 1;
20595    OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile->h, r );
20596  }else{
20597    FILELOCK  LockArea,
20598              UnlockArea;
20599    APIRET rc = NO_ERROR;
20600    memset(&LockArea, 0, sizeof(LockArea));
20601    memset(&UnlockArea, 0, sizeof(UnlockArea));
20602    LockArea.lOffset = RESERVED_BYTE;
20603    LockArea.lRange = 1L;
20604    UnlockArea.lOffset = 0L;
20605    UnlockArea.lRange = 0L;
20606    rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20607    OSTRACE3( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc );
20608    if( rc == NO_ERROR ){
20609      APIRET rcu = NO_ERROR; /* return code for unlocking */
20610      LockArea.lOffset = 0L;
20611      LockArea.lRange = 0L;
20612      UnlockArea.lOffset = RESERVED_BYTE;
20613      UnlockArea.lRange = 1L;
20614      rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20615      OSTRACE3( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu );
20616    }
20617    r = !(rc == NO_ERROR);
20618    OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r );
20619  }
20620  *pOut = r;
20621  return SQLITE_OK;
20622}
20623
20624/*
20625** Lower the locking level on file descriptor id to locktype.  locktype
20626** must be either NO_LOCK or SHARED_LOCK.
20627**
20628** If the locking level of the file descriptor is already at or below
20629** the requested locking level, this routine is a no-op.
20630**
20631** It is not possible for this routine to fail if the second argument
20632** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
20633** might return SQLITE_IOERR;
20634*/
20635static int os2Unlock( sqlite3_file *id, int locktype ){
20636  int type;
20637  os2File *pFile = (os2File*)id;
20638  APIRET rc = SQLITE_OK;
20639  APIRET res = NO_ERROR;
20640  FILELOCK  LockArea,
20641            UnlockArea;
20642  memset(&LockArea, 0, sizeof(LockArea));
20643  memset(&UnlockArea, 0, sizeof(UnlockArea));
20644  assert( pFile!=0 );
20645  assert( locktype<=SHARED_LOCK );
20646  OSTRACE4( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype );
20647  type = pFile->locktype;
20648  if( type>=EXCLUSIVE_LOCK ){
20649    LockArea.lOffset = 0L;
20650    LockArea.lRange = 0L;
20651    UnlockArea.lOffset = SHARED_FIRST;
20652    UnlockArea.lRange = SHARED_SIZE;
20653    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20654    OSTRACE3( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res );
20655    if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
20656      /* This should never happen.  We should always be able to
20657      ** reacquire the read lock */
20658      OSTRACE3( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype );
20659      rc = SQLITE_IOERR_UNLOCK;
20660    }
20661  }
20662  if( type>=RESERVED_LOCK ){
20663    LockArea.lOffset = 0L;
20664    LockArea.lRange = 0L;
20665    UnlockArea.lOffset = RESERVED_BYTE;
20666    UnlockArea.lRange = 1L;
20667    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20668    OSTRACE3( "UNLOCK %d reserved res=%d\n", pFile->h, res );
20669  }
20670  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
20671    res = unlockReadLock(pFile);
20672    OSTRACE5( "UNLOCK %d is %d want %d res=%d\n", pFile->h, type, locktype, res );
20673  }
20674  if( type>=PENDING_LOCK ){
20675    LockArea.lOffset = 0L;
20676    LockArea.lRange = 0L;
20677    UnlockArea.lOffset = PENDING_BYTE;
20678    UnlockArea.lRange = 1L;
20679    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20680    OSTRACE3( "UNLOCK %d pending res=%d\n", pFile->h, res );
20681  }
20682  pFile->locktype = locktype;
20683  OSTRACE3( "UNLOCK %d now %d\n", pFile->h, pFile->locktype );
20684  return rc;
20685}
20686
20687/*
20688** Control and query of the open file handle.
20689*/
20690static int os2FileControl(sqlite3_file *id, int op, void *pArg){
20691  switch( op ){
20692    case SQLITE_FCNTL_LOCKSTATE: {
20693      *(int*)pArg = ((os2File*)id)->locktype;
20694      OSTRACE3( "FCNTL_LOCKSTATE %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
20695      return SQLITE_OK;
20696    }
20697  }
20698  return SQLITE_ERROR;
20699}
20700
20701/*
20702** Return the sector size in bytes of the underlying block device for
20703** the specified file. This is almost always 512 bytes, but may be
20704** larger for some devices.
20705**
20706** SQLite code assumes this function cannot fail. It also assumes that
20707** if two files are created in the same file-system directory (i.e.
20708** a database and its journal file) that the sector size will be the
20709** same for both.
20710*/
20711static int os2SectorSize(sqlite3_file *id){
20712  return SQLITE_DEFAULT_SECTOR_SIZE;
20713}
20714
20715/*
20716** Return a vector of device characteristics.
20717*/
20718static int os2DeviceCharacteristics(sqlite3_file *id){
20719  return 0;
20720}
20721
20722
20723/*
20724** Character set conversion objects used by conversion routines.
20725*/
20726static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
20727static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
20728
20729/*
20730** Helper function to initialize the conversion objects from and to UTF-8.
20731*/
20732static void initUconvObjects( void ){
20733  if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
20734    ucUtf8 = NULL;
20735  if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
20736    uclCp = NULL;
20737}
20738
20739/*
20740** Helper function to free the conversion objects from and to UTF-8.
20741*/
20742static void freeUconvObjects( void ){
20743  if ( ucUtf8 )
20744    UniFreeUconvObject( ucUtf8 );
20745  if ( uclCp )
20746    UniFreeUconvObject( uclCp );
20747  ucUtf8 = NULL;
20748  uclCp = NULL;
20749}
20750
20751/*
20752** Helper function to convert UTF-8 filenames to local OS/2 codepage.
20753** The two-step process: first convert the incoming UTF-8 string
20754** into UCS-2 and then from UCS-2 to the current codepage.
20755** The returned char pointer has to be freed.
20756*/
20757static char *convertUtf8PathToCp( const char *in ){
20758  UniChar tempPath[CCHMAXPATH];
20759  char *out = (char *)calloc( CCHMAXPATH, 1 );
20760
20761  if( !out )
20762    return NULL;
20763
20764  if( !ucUtf8 || !uclCp )
20765    initUconvObjects();
20766
20767  /* determine string for the conversion of UTF-8 which is CP1208 */
20768  if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
20769    return out; /* if conversion fails, return the empty string */
20770
20771  /* conversion for current codepage which can be used for paths */
20772  UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
20773
20774  return out;
20775}
20776
20777/*
20778** Helper function to convert filenames from local codepage to UTF-8.
20779** The two-step process: first convert the incoming codepage-specific
20780** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
20781** The returned char pointer has to be freed.
20782**
20783** This function is non-static to be able to use this in shell.c and
20784** similar applications that take command line arguments.
20785*/
20786char *convertCpPathToUtf8( const char *in ){
20787  UniChar tempPath[CCHMAXPATH];
20788  char *out = (char *)calloc( CCHMAXPATH, 1 );
20789
20790  if( !out )
20791    return NULL;
20792
20793  if( !ucUtf8 || !uclCp )
20794    initUconvObjects();
20795
20796  /* conversion for current codepage which can be used for paths */
20797  if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
20798    return out; /* if conversion fails, return the empty string */
20799
20800  /* determine string for the conversion of UTF-8 which is CP1208 */
20801  UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
20802
20803  return out;
20804}
20805
20806/*
20807** This vector defines all the methods that can operate on an
20808** sqlite3_file for os2.
20809*/
20810static const sqlite3_io_methods os2IoMethod = {
20811  1,                        /* iVersion */
20812  os2Close,
20813  os2Read,
20814  os2Write,
20815  os2Truncate,
20816  os2Sync,
20817  os2FileSize,
20818  os2Lock,
20819  os2Unlock,
20820  os2CheckReservedLock,
20821  os2FileControl,
20822  os2SectorSize,
20823  os2DeviceCharacteristics
20824};
20825
20826/***************************************************************************
20827** Here ends the I/O methods that form the sqlite3_io_methods object.
20828**
20829** The next block of code implements the VFS methods.
20830****************************************************************************/
20831
20832/*
20833** Create a temporary file name in zBuf.  zBuf must be big enough to
20834** hold at pVfs->mxPathname characters.
20835*/
20836static int getTempname(int nBuf, char *zBuf ){
20837  static const unsigned char zChars[] =
20838    "abcdefghijklmnopqrstuvwxyz"
20839    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
20840    "0123456789";
20841  int i, j;
20842  char zTempPathBuf[3];
20843  PSZ zTempPath = (PSZ)&zTempPathBuf;
20844  if( sqlite3_temp_directory ){
20845    zTempPath = sqlite3_temp_directory;
20846  }else{
20847    if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
20848      if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
20849        if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
20850           ULONG ulDriveNum = 0, ulDriveMap = 0;
20851           DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
20852           sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
20853        }
20854      }
20855    }
20856  }
20857  /* Strip off a trailing slashes or backslashes, otherwise we would get *
20858   * multiple (back)slashes which causes DosOpen() to fail.              *
20859   * Trailing spaces are not allowed, either.                            */
20860  j = sqlite3Strlen30(zTempPath);
20861  while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
20862                    || zTempPath[j-1] == ' ' ) ){
20863    j--;
20864  }
20865  zTempPath[j] = '\0';
20866  if( !sqlite3_temp_directory ){
20867    char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
20868    sqlite3_snprintf( nBuf-30, zBuf,
20869                      "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
20870    free( zTempPathUTF );
20871  }else{
20872    sqlite3_snprintf( nBuf-30, zBuf,
20873                      "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
20874  }
20875  j = sqlite3Strlen30( zBuf );
20876  sqlite3_randomness( 20, &zBuf[j] );
20877  for( i = 0; i < 20; i++, j++ ){
20878    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
20879  }
20880  zBuf[j] = 0;
20881  OSTRACE2( "TEMP FILENAME: %s\n", zBuf );
20882  return SQLITE_OK;
20883}
20884
20885
20886/*
20887** Turn a relative pathname into a full pathname.  Write the full
20888** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
20889** bytes in size.
20890*/
20891static int os2FullPathname(
20892  sqlite3_vfs *pVfs,          /* Pointer to vfs object */
20893  const char *zRelative,      /* Possibly relative input path */
20894  int nFull,                  /* Size of output buffer in bytes */
20895  char *zFull                 /* Output buffer */
20896){
20897  char *zRelativeCp = convertUtf8PathToCp( zRelative );
20898  char zFullCp[CCHMAXPATH] = "\0";
20899  char *zFullUTF;
20900  APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
20901                                CCHMAXPATH );
20902  free( zRelativeCp );
20903  zFullUTF = convertCpPathToUtf8( zFullCp );
20904  sqlite3_snprintf( nFull, zFull, zFullUTF );
20905  free( zFullUTF );
20906  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20907}
20908
20909
20910/*
20911** Open a file.
20912*/
20913static int os2Open(
20914  sqlite3_vfs *pVfs,            /* Not used */
20915  const char *zName,            /* Name of the file */
20916  sqlite3_file *id,             /* Write the SQLite file handle here */
20917  int flags,                    /* Open mode flags */
20918  int *pOutFlags                /* Status return flags */
20919){
20920  HFILE h;
20921  ULONG ulFileAttribute = FILE_NORMAL;
20922  ULONG ulOpenFlags = 0;
20923  ULONG ulOpenMode = 0;
20924  os2File *pFile = (os2File*)id;
20925  APIRET rc = NO_ERROR;
20926  ULONG ulAction;
20927  char *zNameCp;
20928  char zTmpname[CCHMAXPATH+1];    /* Buffer to hold name of temp file */
20929
20930  /* If the second argument to this function is NULL, generate a
20931  ** temporary file name to use
20932  */
20933  if( !zName ){
20934    int rc = getTempname(CCHMAXPATH+1, zTmpname);
20935    if( rc!=SQLITE_OK ){
20936      return rc;
20937    }
20938    zName = zTmpname;
20939  }
20940
20941
20942  memset( pFile, 0, sizeof(*pFile) );
20943
20944  OSTRACE2( "OPEN want %d\n", flags );
20945
20946  if( flags & SQLITE_OPEN_READWRITE ){
20947    ulOpenMode |= OPEN_ACCESS_READWRITE;
20948    OSTRACE1( "OPEN read/write\n" );
20949  }else{
20950    ulOpenMode |= OPEN_ACCESS_READONLY;
20951    OSTRACE1( "OPEN read only\n" );
20952  }
20953
20954  if( flags & SQLITE_OPEN_CREATE ){
20955    ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
20956    OSTRACE1( "OPEN open new/create\n" );
20957  }else{
20958    ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
20959    OSTRACE1( "OPEN open existing\n" );
20960  }
20961
20962  if( flags & SQLITE_OPEN_MAIN_DB ){
20963    ulOpenMode |= OPEN_SHARE_DENYNONE;
20964    OSTRACE1( "OPEN share read/write\n" );
20965  }else{
20966    ulOpenMode |= OPEN_SHARE_DENYWRITE;
20967    OSTRACE1( "OPEN share read only\n" );
20968  }
20969
20970  if( flags & SQLITE_OPEN_DELETEONCLOSE ){
20971    char pathUtf8[CCHMAXPATH];
20972#ifdef NDEBUG /* when debugging we want to make sure it is deleted */
20973    ulFileAttribute = FILE_HIDDEN;
20974#endif
20975    os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
20976    pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
20977    OSTRACE1( "OPEN hidden/delete on close file attributes\n" );
20978  }else{
20979    pFile->pathToDel = NULL;
20980    OSTRACE1( "OPEN normal file attribute\n" );
20981  }
20982
20983  /* always open in random access mode for possibly better speed */
20984  ulOpenMode |= OPEN_FLAGS_RANDOM;
20985  ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
20986  ulOpenMode |= OPEN_FLAGS_NOINHERIT;
20987
20988  zNameCp = convertUtf8PathToCp( zName );
20989  rc = DosOpen( (PSZ)zNameCp,
20990                &h,
20991                &ulAction,
20992                0L,
20993                ulFileAttribute,
20994                ulOpenFlags,
20995                ulOpenMode,
20996                (PEAOP2)NULL );
20997  free( zNameCp );
20998  if( rc != NO_ERROR ){
20999    OSTRACE7( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
21000              rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode );
21001    if( pFile->pathToDel )
21002      free( pFile->pathToDel );
21003    pFile->pathToDel = NULL;
21004    if( flags & SQLITE_OPEN_READWRITE ){
21005      OSTRACE2( "OPEN %d Invalid handle\n", ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) );
21006      return os2Open( pVfs, zName, id,
21007                      ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
21008                      pOutFlags );
21009    }else{
21010      return SQLITE_CANTOPEN;
21011    }
21012  }
21013
21014  if( pOutFlags ){
21015    *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
21016  }
21017
21018  pFile->pMethod = &os2IoMethod;
21019  pFile->h = h;
21020  OpenCounter(+1);
21021  OSTRACE3( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags );
21022  return SQLITE_OK;
21023}
21024
21025/*
21026** Delete the named file.
21027*/
21028static int os2Delete(
21029  sqlite3_vfs *pVfs,                     /* Not used on os2 */
21030  const char *zFilename,                 /* Name of file to delete */
21031  int syncDir                            /* Not used on os2 */
21032){
21033  APIRET rc = NO_ERROR;
21034  char *zFilenameCp = convertUtf8PathToCp( zFilename );
21035  SimulateIOError( return SQLITE_IOERR_DELETE );
21036  rc = DosDelete( (PSZ)zFilenameCp );
21037  free( zFilenameCp );
21038  OSTRACE2( "DELETE \"%s\"\n", zFilename );
21039  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
21040}
21041
21042/*
21043** Check the existance and status of a file.
21044*/
21045static int os2Access(
21046  sqlite3_vfs *pVfs,        /* Not used on os2 */
21047  const char *zFilename,    /* Name of file to check */
21048  int flags,                /* Type of test to make on this file */
21049  int *pOut                 /* Write results here */
21050){
21051  FILESTATUS3 fsts3ConfigInfo;
21052  APIRET rc = NO_ERROR;
21053  char *zFilenameCp = convertUtf8PathToCp( zFilename );
21054
21055  memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
21056  rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
21057                         &fsts3ConfigInfo, sizeof(FILESTATUS3) );
21058  free( zFilenameCp );
21059  OSTRACE4( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
21060            fsts3ConfigInfo.attrFile, flags, rc );
21061  switch( flags ){
21062    case SQLITE_ACCESS_READ:
21063    case SQLITE_ACCESS_EXISTS:
21064      rc = (rc == NO_ERROR);
21065      OSTRACE3( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc );
21066      break;
21067    case SQLITE_ACCESS_READWRITE:
21068      rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
21069      OSTRACE3( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc );
21070      break;
21071    default:
21072      assert( !"Invalid flags argument" );
21073  }
21074  *pOut = rc;
21075  return SQLITE_OK;
21076}
21077
21078
21079#ifndef SQLITE_OMIT_LOAD_EXTENSION
21080/*
21081** Interfaces for opening a shared library, finding entry points
21082** within the shared library, and closing the shared library.
21083*/
21084/*
21085** Interfaces for opening a shared library, finding entry points
21086** within the shared library, and closing the shared library.
21087*/
21088static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
21089  UCHAR loadErr[256];
21090  HMODULE hmod;
21091  APIRET rc;
21092  char *zFilenameCp = convertUtf8PathToCp(zFilename);
21093  rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
21094  free(zFilenameCp);
21095  return rc != NO_ERROR ? 0 : (void*)hmod;
21096}
21097/*
21098** A no-op since the error code is returned on the DosLoadModule call.
21099** os2Dlopen returns zero if DosLoadModule is not successful.
21100*/
21101static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
21102/* no-op */
21103}
21104static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
21105  PFN pfn;
21106  APIRET rc;
21107  rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
21108  if( rc != NO_ERROR ){
21109    /* if the symbol itself was not found, search again for the same
21110     * symbol with an extra underscore, that might be needed depending
21111     * on the calling convention */
21112    char _zSymbol[256] = "_";
21113    strncat(_zSymbol, zSymbol, 255);
21114    rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
21115  }
21116  return rc != NO_ERROR ? 0 : (void*)pfn;
21117}
21118static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
21119  DosFreeModule((HMODULE)pHandle);
21120}
21121#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
21122  #define os2DlOpen 0
21123  #define os2DlError 0
21124  #define os2DlSym 0
21125  #define os2DlClose 0
21126#endif
21127
21128
21129/*
21130** Write up to nBuf bytes of randomness into zBuf.
21131*/
21132static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
21133  int n = 0;
21134#if defined(SQLITE_TEST)
21135  n = nBuf;
21136  memset(zBuf, 0, nBuf);
21137#else
21138  int sizeofULong = sizeof(ULONG);
21139  if( (int)sizeof(DATETIME) <= nBuf - n ){
21140    DATETIME x;
21141    DosGetDateTime(&x);
21142    memcpy(&zBuf[n], &x, sizeof(x));
21143    n += sizeof(x);
21144  }
21145
21146  if( sizeofULong <= nBuf - n ){
21147    PPIB ppib;
21148    DosGetInfoBlocks(NULL, &ppib);
21149    memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
21150    n += sizeofULong;
21151  }
21152
21153  if( sizeofULong <= nBuf - n ){
21154    PTIB ptib;
21155    DosGetInfoBlocks(&ptib, NULL);
21156    memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
21157    n += sizeofULong;
21158  }
21159
21160  /* if we still haven't filled the buffer yet the following will */
21161  /* grab everything once instead of making several calls for a single item */
21162  if( sizeofULong <= nBuf - n ){
21163    ULONG ulSysInfo[QSV_MAX];
21164    DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
21165
21166    memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
21167    n += sizeofULong;
21168
21169    if( sizeofULong <= nBuf - n ){
21170      memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
21171      n += sizeofULong;
21172    }
21173    if( sizeofULong <= nBuf - n ){
21174      memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
21175      n += sizeofULong;
21176    }
21177    if( sizeofULong <= nBuf - n ){
21178      memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
21179      n += sizeofULong;
21180    }
21181    if( sizeofULong <= nBuf - n ){
21182      memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
21183      n += sizeofULong;
21184    }
21185  }
21186#endif
21187
21188  return n;
21189}
21190
21191/*
21192** Sleep for a little while.  Return the amount of time slept.
21193** The argument is the number of microseconds we want to sleep.
21194** The return value is the number of microseconds of sleep actually
21195** requested from the underlying operating system, a number which
21196** might be greater than or equal to the argument, but not less
21197** than the argument.
21198*/
21199static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
21200  DosSleep( (microsec/1000) );
21201  return microsec;
21202}
21203
21204/*
21205** The following variable, if set to a non-zero value, becomes the result
21206** returned from sqlite3OsCurrentTime().  This is used for testing.
21207*/
21208#ifdef SQLITE_TEST
21209SQLITE_API int sqlite3_current_time = 0;
21210#endif
21211
21212/*
21213** Find the current time (in Universal Coordinated Time).  Write the
21214** current time and date as a Julian Day number into *prNow and
21215** return 0.  Return 1 if the time and date cannot be found.
21216*/
21217int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
21218  double now;
21219  SHORT minute; /* needs to be able to cope with negative timezone offset */
21220  USHORT second, hour,
21221         day, month, year;
21222  DATETIME dt;
21223  DosGetDateTime( &dt );
21224  second = (USHORT)dt.seconds;
21225  minute = (SHORT)dt.minutes + dt.timezone;
21226  hour = (USHORT)dt.hours;
21227  day = (USHORT)dt.day;
21228  month = (USHORT)dt.month;
21229  year = (USHORT)dt.year;
21230
21231  /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
21232     http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
21233  /* Calculate the Julian days */
21234  now = day - 32076 +
21235    1461*(year + 4800 + (month - 14)/12)/4 +
21236    367*(month - 2 - (month - 14)/12*12)/12 -
21237    3*((year + 4900 + (month - 14)/12)/100)/4;
21238
21239  /* Add the fractional hours, mins and seconds */
21240  now += (hour + 12.0)/24.0;
21241  now += minute/1440.0;
21242  now += second/86400.0;
21243  *prNow = now;
21244#ifdef SQLITE_TEST
21245  if( sqlite3_current_time ){
21246    *prNow = sqlite3_current_time/86400.0 + 2440587.5;
21247  }
21248#endif
21249  return 0;
21250}
21251
21252static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
21253  return 0;
21254}
21255
21256/*
21257** Initialize and deinitialize the operating system interface.
21258*/
21259SQLITE_API int sqlite3_os_init(void){
21260  static sqlite3_vfs os2Vfs = {
21261    1,                 /* iVersion */
21262    sizeof(os2File),   /* szOsFile */
21263    CCHMAXPATH,        /* mxPathname */
21264    0,                 /* pNext */
21265    "os2",             /* zName */
21266    0,                 /* pAppData */
21267
21268    os2Open,           /* xOpen */
21269    os2Delete,         /* xDelete */
21270    os2Access,         /* xAccess */
21271    os2FullPathname,   /* xFullPathname */
21272    os2DlOpen,         /* xDlOpen */
21273    os2DlError,        /* xDlError */
21274    os2DlSym,          /* xDlSym */
21275    os2DlClose,        /* xDlClose */
21276    os2Randomness,     /* xRandomness */
21277    os2Sleep,          /* xSleep */
21278    os2CurrentTime,    /* xCurrentTime */
21279    os2GetLastError    /* xGetLastError */
21280  };
21281  sqlite3_vfs_register(&os2Vfs, 1);
21282  initUconvObjects();
21283  return SQLITE_OK;
21284}
21285SQLITE_API int sqlite3_os_end(void){
21286  freeUconvObjects();
21287  return SQLITE_OK;
21288}
21289
21290#endif /* SQLITE_OS_OS2 */
21291
21292/************** End of os_os2.c **********************************************/
21293/************** Begin file os_unix.c *****************************************/
21294/*
21295** 2004 May 22
21296**
21297** The author disclaims copyright to this source code.  In place of
21298** a legal notice, here is a blessing:
21299**
21300**    May you do good and not evil.
21301**    May you find forgiveness for yourself and forgive others.
21302**    May you share freely, never taking more than you give.
21303**
21304******************************************************************************
21305**
21306** This file contains the VFS implementation for unix-like operating systems
21307** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
21308**
21309** There are actually several different VFS implementations in this file.
21310** The differences are in the way that file locking is done.  The default
21311** implementation uses Posix Advisory Locks.  Alternative implementations
21312** use flock(), dot-files, various proprietary locking schemas, or simply
21313** skip locking all together.
21314**
21315** This source file is organized into divisions where the logic for various
21316** subfunctions is contained within the appropriate division.  PLEASE
21317** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
21318** in the correct division and should be clearly labeled.
21319**
21320** The layout of divisions is as follows:
21321**
21322**   *  General-purpose declarations and utility functions.
21323**   *  Unique file ID logic used by VxWorks.
21324**   *  Various locking primitive implementations (all except proxy locking):
21325**      + for Posix Advisory Locks
21326**      + for no-op locks
21327**      + for dot-file locks
21328**      + for flock() locking
21329**      + for named semaphore locks (VxWorks only)
21330**      + for AFP filesystem locks (MacOSX only)
21331**   *  sqlite3_file methods not associated with locking.
21332**   *  Definitions of sqlite3_io_methods objects for all locking
21333**      methods plus "finder" functions for each locking method.
21334**   *  sqlite3_vfs method implementations.
21335**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
21336**   *  Definitions of sqlite3_vfs objects for all locking methods
21337**      plus implementations of sqlite3_os_init() and sqlite3_os_end().
21338*/
21339#if SQLITE_OS_UNIX              /* This file is used on unix only */
21340
21341/*
21342** There are various methods for file locking used for concurrency
21343** control:
21344**
21345**   1. POSIX locking (the default),
21346**   2. No locking,
21347**   3. Dot-file locking,
21348**   4. flock() locking,
21349**   5. AFP locking (OSX only),
21350**   6. Named POSIX semaphores (VXWorks only),
21351**   7. proxy locking. (OSX only)
21352**
21353** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
21354** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
21355** selection of the appropriate locking style based on the filesystem
21356** where the database is located.
21357*/
21358#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
21359#  if defined(__APPLE__)
21360#    define SQLITE_ENABLE_LOCKING_STYLE 1
21361#  else
21362#    define SQLITE_ENABLE_LOCKING_STYLE 0
21363#  endif
21364#endif
21365
21366/*
21367** Define the OS_VXWORKS pre-processor macro to 1 if building on
21368** vxworks, or 0 otherwise.
21369*/
21370#ifndef OS_VXWORKS
21371#  if defined(__RTP__) || defined(_WRS_KERNEL)
21372#    define OS_VXWORKS 1
21373#  else
21374#    define OS_VXWORKS 0
21375#  endif
21376#endif
21377
21378/*
21379** These #defines should enable >2GB file support on Posix if the
21380** underlying operating system supports it.  If the OS lacks
21381** large file support, these should be no-ops.
21382**
21383** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
21384** on the compiler command line.  This is necessary if you are compiling
21385** on a recent machine (ex: RedHat 7.2) but you want your code to work
21386** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
21387** without this option, LFS is enable.  But LFS does not exist in the kernel
21388** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
21389** portability you should omit LFS.
21390**
21391** The previous paragraph was written in 2005.  (This paragraph is written
21392** on 2008-11-28.) These days, all Linux kernels support large files, so
21393** you should probably leave LFS enabled.  But some embedded platforms might
21394** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
21395*/
21396#ifndef SQLITE_DISABLE_LFS
21397# define _LARGE_FILE       1
21398# ifndef _FILE_OFFSET_BITS
21399#   define _FILE_OFFSET_BITS 64
21400# endif
21401# define _LARGEFILE_SOURCE 1
21402#endif
21403
21404/*
21405** standard include files.
21406*/
21407#include <sys/types.h>
21408#include <sys/stat.h>
21409#include <fcntl.h>
21410#include <unistd.h>
21411#include <sys/time.h>
21412#include <errno.h>
21413
21414#if SQLITE_ENABLE_LOCKING_STYLE
21415# include <sys/ioctl.h>
21416# if OS_VXWORKS
21417#  include <semaphore.h>
21418#  include <limits.h>
21419# else
21420#  include <sys/file.h>
21421#  include <sys/param.h>
21422#  include <sys/mount.h>
21423# endif
21424#endif /* SQLITE_ENABLE_LOCKING_STYLE */
21425
21426/*
21427** If we are to be thread-safe, include the pthreads header and define
21428** the SQLITE_UNIX_THREADS macro.
21429*/
21430#if SQLITE_THREADSAFE
21431# define SQLITE_UNIX_THREADS 1
21432#endif
21433
21434/*
21435** Default permissions when creating a new file
21436*/
21437#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
21438# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
21439#endif
21440
21441/*
21442 ** Default permissions when creating auto proxy dir
21443 */
21444#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
21445# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
21446#endif
21447
21448/*
21449** Maximum supported path-length.
21450*/
21451#define MAX_PATHNAME 512
21452
21453/*
21454** Only set the lastErrno if the error code is a real error and not
21455** a normal expected return code of SQLITE_BUSY or SQLITE_OK
21456*/
21457#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
21458
21459
21460/*
21461** Sometimes, after a file handle is closed by SQLite, the file descriptor
21462** cannot be closed immediately. In these cases, instances of the following
21463** structure are used to store the file descriptor while waiting for an
21464** opportunity to either close or reuse it.
21465*/
21466typedef struct UnixUnusedFd UnixUnusedFd;
21467struct UnixUnusedFd {
21468  int fd;                   /* File descriptor to close */
21469  int flags;                /* Flags this file descriptor was opened with */
21470  UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
21471};
21472
21473/*
21474** The unixFile structure is subclass of sqlite3_file specific to the unix
21475** VFS implementations.
21476*/
21477typedef struct unixFile unixFile;
21478struct unixFile {
21479  sqlite3_io_methods const *pMethod;  /* Always the first entry */
21480  struct unixOpenCnt *pOpen;       /* Info about all open fd's on this inode */
21481  struct unixLockInfo *pLock;      /* Info about locks on this inode */
21482  int h;                           /* The file descriptor */
21483  int dirfd;                       /* File descriptor for the directory */
21484  unsigned char locktype;          /* The type of lock held on this fd */
21485  int lastErrno;                   /* The unix errno from the last I/O error */
21486  void *lockingContext;            /* Locking style specific state */
21487  UnixUnusedFd *pUnused;           /* Pre-allocated UnixUnusedFd */
21488  int fileFlags;                   /* Miscellanous flags */
21489#if SQLITE_ENABLE_LOCKING_STYLE
21490  int openFlags;                   /* The flags specified at open() */
21491#endif
21492#if SQLITE_THREADSAFE && defined(__linux__)
21493  pthread_t tid;                   /* The thread that "owns" this unixFile */
21494#endif
21495#if OS_VXWORKS
21496  int isDelete;                    /* Delete on close if true */
21497  struct vxworksFileId *pId;       /* Unique file ID */
21498#endif
21499#ifndef NDEBUG
21500  /* The next group of variables are used to track whether or not the
21501  ** transaction counter in bytes 24-27 of database files are updated
21502  ** whenever any part of the database changes.  An assertion fault will
21503  ** occur if a file is updated without also updating the transaction
21504  ** counter.  This test is made to avoid new problems similar to the
21505  ** one described by ticket #3584.
21506  */
21507  unsigned char transCntrChng;   /* True if the transaction counter changed */
21508  unsigned char dbUpdate;        /* True if any part of database file changed */
21509  unsigned char inNormalWrite;   /* True if in a normal write operation */
21510#endif
21511#ifdef SQLITE_TEST
21512  /* In test mode, increase the size of this structure a bit so that
21513  ** it is larger than the struct CrashFile defined in test6.c.
21514  */
21515  char aPadding[32];
21516#endif
21517};
21518
21519/*
21520** The following macros define bits in unixFile.fileFlags
21521*/
21522#define SQLITE_WHOLE_FILE_LOCKING  0x0001   /* Use whole-file locking */
21523
21524/*
21525** Include code that is common to all os_*.c files
21526*/
21527/************** Include os_common.h in the middle of os_unix.c ***************/
21528/************** Begin file os_common.h ***************************************/
21529/*
21530** 2004 May 22
21531**
21532** The author disclaims copyright to this source code.  In place of
21533** a legal notice, here is a blessing:
21534**
21535**    May you do good and not evil.
21536**    May you find forgiveness for yourself and forgive others.
21537**    May you share freely, never taking more than you give.
21538**
21539******************************************************************************
21540**
21541** This file contains macros and a little bit of code that is common to
21542** all of the platform-specific files (os_*.c) and is #included into those
21543** files.
21544**
21545** This file should be #included by the os_*.c files only.  It is not a
21546** general purpose header file.
21547*/
21548#ifndef _OS_COMMON_H_
21549#define _OS_COMMON_H_
21550
21551/*
21552** At least two bugs have slipped in because we changed the MEMORY_DEBUG
21553** macro to SQLITE_DEBUG and some older makefiles have not yet made the
21554** switch.  The following code should catch this problem at compile-time.
21555*/
21556#ifdef MEMORY_DEBUG
21557# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
21558#endif
21559
21560#ifdef SQLITE_DEBUG
21561SQLITE_PRIVATE int sqlite3OSTrace = 0;
21562#define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
21563#define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
21564#define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
21565#define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
21566#define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
21567#define OSTRACE6(X,Y,Z,A,B,C) \
21568    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
21569#define OSTRACE7(X,Y,Z,A,B,C,D) \
21570    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
21571#else
21572#define OSTRACE1(X)
21573#define OSTRACE2(X,Y)
21574#define OSTRACE3(X,Y,Z)
21575#define OSTRACE4(X,Y,Z,A)
21576#define OSTRACE5(X,Y,Z,A,B)
21577#define OSTRACE6(X,Y,Z,A,B,C)
21578#define OSTRACE7(X,Y,Z,A,B,C,D)
21579#endif
21580
21581/*
21582** Macros for performance tracing.  Normally turned off.  Only works
21583** on i486 hardware.
21584*/
21585#ifdef SQLITE_PERFORMANCE_TRACE
21586
21587/*
21588** hwtime.h contains inline assembler code for implementing
21589** high-performance timing routines.
21590*/
21591/************** Include hwtime.h in the middle of os_common.h ****************/
21592/************** Begin file hwtime.h ******************************************/
21593/*
21594** 2008 May 27
21595**
21596** The author disclaims copyright to this source code.  In place of
21597** a legal notice, here is a blessing:
21598**
21599**    May you do good and not evil.
21600**    May you find forgiveness for yourself and forgive others.
21601**    May you share freely, never taking more than you give.
21602**
21603******************************************************************************
21604**
21605** This file contains inline asm code for retrieving "high-performance"
21606** counters for x86 class CPUs.
21607*/
21608#ifndef _HWTIME_H_
21609#define _HWTIME_H_
21610
21611/*
21612** The following routine only works on pentium-class (or newer) processors.
21613** It uses the RDTSC opcode to read the cycle count value out of the
21614** processor and returns that value.  This can be used for high-res
21615** profiling.
21616*/
21617#if (defined(__GNUC__) || defined(_MSC_VER)) && \
21618      (defined(i386) || defined(__i386__) || defined(_M_IX86))
21619
21620  #if defined(__GNUC__)
21621
21622  __inline__ sqlite_uint64 sqlite3Hwtime(void){
21623     unsigned int lo, hi;
21624     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
21625     return (sqlite_uint64)hi << 32 | lo;
21626  }
21627
21628  #elif defined(_MSC_VER)
21629
21630  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
21631     __asm {
21632        rdtsc
21633        ret       ; return value at EDX:EAX
21634     }
21635  }
21636
21637  #endif
21638
21639#elif (defined(__GNUC__) && defined(__x86_64__))
21640
21641  __inline__ sqlite_uint64 sqlite3Hwtime(void){
21642      unsigned long val;
21643      __asm__ __volatile__ ("rdtsc" : "=A" (val));
21644      return val;
21645  }
21646
21647#elif (defined(__GNUC__) && defined(__ppc__))
21648
21649  __inline__ sqlite_uint64 sqlite3Hwtime(void){
21650      unsigned long long retval;
21651      unsigned long junk;
21652      __asm__ __volatile__ ("\n\
21653          1:      mftbu   %1\n\
21654                  mftb    %L0\n\
21655                  mftbu   %0\n\
21656                  cmpw    %0,%1\n\
21657                  bne     1b"
21658                  : "=r" (retval), "=r" (junk));
21659      return retval;
21660  }
21661
21662#else
21663
21664  #error Need implementation of sqlite3Hwtime() for your platform.
21665
21666  /*
21667  ** To compile without implementing sqlite3Hwtime() for your platform,
21668  ** you can remove the above #error and use the following
21669  ** stub function.  You will lose timing support for many
21670  ** of the debugging and testing utilities, but it should at
21671  ** least compile and run.
21672  */
21673SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
21674
21675#endif
21676
21677#endif /* !defined(_HWTIME_H_) */
21678
21679/************** End of hwtime.h **********************************************/
21680/************** Continuing where we left off in os_common.h ******************/
21681
21682static sqlite_uint64 g_start;
21683static sqlite_uint64 g_elapsed;
21684#define TIMER_START       g_start=sqlite3Hwtime()
21685#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
21686#define TIMER_ELAPSED     g_elapsed
21687#else
21688#define TIMER_START
21689#define TIMER_END
21690#define TIMER_ELAPSED     ((sqlite_uint64)0)
21691#endif
21692
21693/*
21694** If we compile with the SQLITE_TEST macro set, then the following block
21695** of code will give us the ability to simulate a disk I/O error.  This
21696** is used for testing the I/O recovery logic.
21697*/
21698#ifdef SQLITE_TEST
21699SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
21700SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
21701SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
21702SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
21703SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
21704SQLITE_API int sqlite3_diskfull_pending = 0;
21705SQLITE_API int sqlite3_diskfull = 0;
21706#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
21707#define SimulateIOError(CODE)  \
21708  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
21709       || sqlite3_io_error_pending-- == 1 )  \
21710              { local_ioerr(); CODE; }
21711static void local_ioerr(){
21712  IOTRACE(("IOERR\n"));
21713  sqlite3_io_error_hit++;
21714  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
21715}
21716#define SimulateDiskfullError(CODE) \
21717   if( sqlite3_diskfull_pending ){ \
21718     if( sqlite3_diskfull_pending == 1 ){ \
21719       local_ioerr(); \
21720       sqlite3_diskfull = 1; \
21721       sqlite3_io_error_hit = 1; \
21722       CODE; \
21723     }else{ \
21724       sqlite3_diskfull_pending--; \
21725     } \
21726   }
21727#else
21728#define SimulateIOErrorBenign(X)
21729#define SimulateIOError(A)
21730#define SimulateDiskfullError(A)
21731#endif
21732
21733/*
21734** When testing, keep a count of the number of open files.
21735*/
21736#ifdef SQLITE_TEST
21737SQLITE_API int sqlite3_open_file_count = 0;
21738#define OpenCounter(X)  sqlite3_open_file_count+=(X)
21739#else
21740#define OpenCounter(X)
21741#endif
21742
21743#endif /* !defined(_OS_COMMON_H_) */
21744
21745/************** End of os_common.h *******************************************/
21746/************** Continuing where we left off in os_unix.c ********************/
21747
21748/*
21749** Define various macros that are missing from some systems.
21750*/
21751#ifndef O_LARGEFILE
21752# define O_LARGEFILE 0
21753#endif
21754#ifdef SQLITE_DISABLE_LFS
21755# undef O_LARGEFILE
21756# define O_LARGEFILE 0
21757#endif
21758#ifndef O_NOFOLLOW
21759# define O_NOFOLLOW 0
21760#endif
21761#ifndef O_BINARY
21762# define O_BINARY 0
21763#endif
21764
21765/*
21766** The DJGPP compiler environment looks mostly like Unix, but it
21767** lacks the fcntl() system call.  So redefine fcntl() to be something
21768** that always succeeds.  This means that locking does not occur under
21769** DJGPP.  But it is DOS - what did you expect?
21770*/
21771#ifdef __DJGPP__
21772# define fcntl(A,B,C) 0
21773#endif
21774
21775/*
21776** The threadid macro resolves to the thread-id or to 0.  Used for
21777** testing and debugging only.
21778*/
21779#if SQLITE_THREADSAFE
21780#define threadid pthread_self()
21781#else
21782#define threadid 0
21783#endif
21784
21785
21786/*
21787** Helper functions to obtain and relinquish the global mutex. The
21788** global mutex is used to protect the unixOpenCnt, unixLockInfo and
21789** vxworksFileId objects used by this file, all of which may be
21790** shared by multiple threads.
21791**
21792** Function unixMutexHeld() is used to assert() that the global mutex
21793** is held when required. This function is only used as part of assert()
21794** statements. e.g.
21795**
21796**   unixEnterMutex()
21797**     assert( unixMutexHeld() );
21798**   unixEnterLeave()
21799*/
21800static void unixEnterMutex(void){
21801  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
21802}
21803static void unixLeaveMutex(void){
21804  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
21805}
21806#ifdef SQLITE_DEBUG
21807static int unixMutexHeld(void) {
21808  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
21809}
21810#endif
21811
21812
21813#ifdef SQLITE_DEBUG
21814/*
21815** Helper function for printing out trace information from debugging
21816** binaries. This returns the string represetation of the supplied
21817** integer lock-type.
21818*/
21819static const char *locktypeName(int locktype){
21820  switch( locktype ){
21821    case NO_LOCK: return "NONE";
21822    case SHARED_LOCK: return "SHARED";
21823    case RESERVED_LOCK: return "RESERVED";
21824    case PENDING_LOCK: return "PENDING";
21825    case EXCLUSIVE_LOCK: return "EXCLUSIVE";
21826  }
21827  return "ERROR";
21828}
21829#endif
21830
21831#ifdef SQLITE_LOCK_TRACE
21832/*
21833** Print out information about all locking operations.
21834**
21835** This routine is used for troubleshooting locks on multithreaded
21836** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
21837** command-line option on the compiler.  This code is normally
21838** turned off.
21839*/
21840static int lockTrace(int fd, int op, struct flock *p){
21841  char *zOpName, *zType;
21842  int s;
21843  int savedErrno;
21844  if( op==F_GETLK ){
21845    zOpName = "GETLK";
21846  }else if( op==F_SETLK ){
21847    zOpName = "SETLK";
21848  }else{
21849    s = fcntl(fd, op, p);
21850    sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
21851    return s;
21852  }
21853  if( p->l_type==F_RDLCK ){
21854    zType = "RDLCK";
21855  }else if( p->l_type==F_WRLCK ){
21856    zType = "WRLCK";
21857  }else if( p->l_type==F_UNLCK ){
21858    zType = "UNLCK";
21859  }else{
21860    assert( 0 );
21861  }
21862  assert( p->l_whence==SEEK_SET );
21863  s = fcntl(fd, op, p);
21864  savedErrno = errno;
21865  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
21866     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
21867     (int)p->l_pid, s);
21868  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
21869    struct flock l2;
21870    l2 = *p;
21871    fcntl(fd, F_GETLK, &l2);
21872    if( l2.l_type==F_RDLCK ){
21873      zType = "RDLCK";
21874    }else if( l2.l_type==F_WRLCK ){
21875      zType = "WRLCK";
21876    }else if( l2.l_type==F_UNLCK ){
21877      zType = "UNLCK";
21878    }else{
21879      assert( 0 );
21880    }
21881    sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
21882       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
21883  }
21884  errno = savedErrno;
21885  return s;
21886}
21887#define fcntl lockTrace
21888#endif /* SQLITE_LOCK_TRACE */
21889
21890
21891
21892/*
21893** This routine translates a standard POSIX errno code into something
21894** useful to the clients of the sqlite3 functions.  Specifically, it is
21895** intended to translate a variety of "try again" errors into SQLITE_BUSY
21896** and a variety of "please close the file descriptor NOW" errors into
21897** SQLITE_IOERR
21898**
21899** Errors during initialization of locks, or file system support for locks,
21900** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
21901*/
21902static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
21903  switch (posixError) {
21904  case 0:
21905    return SQLITE_OK;
21906
21907  case EAGAIN:
21908  case ETIMEDOUT:
21909  case EBUSY:
21910  case EINTR:
21911  case ENOLCK:
21912    /* random NFS retry error, unless during file system support
21913     * introspection, in which it actually means what it says */
21914    return SQLITE_BUSY;
21915
21916  case EACCES:
21917    /* EACCES is like EAGAIN during locking operations, but not any other time*/
21918    if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
21919	(sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
21920	(sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
21921	(sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
21922      return SQLITE_BUSY;
21923    }
21924    /* else fall through */
21925  case EPERM:
21926    return SQLITE_PERM;
21927
21928  case EDEADLK:
21929    return SQLITE_IOERR_BLOCKED;
21930
21931#if EOPNOTSUPP!=ENOTSUP
21932  case EOPNOTSUPP:
21933    /* something went terribly awry, unless during file system support
21934     * introspection, in which it actually means what it says */
21935#endif
21936#ifdef ENOTSUP
21937  case ENOTSUP:
21938    /* invalid fd, unless during file system support introspection, in which
21939     * it actually means what it says */
21940#endif
21941  case EIO:
21942  case EBADF:
21943  case EINVAL:
21944  case ENOTCONN:
21945  case ENODEV:
21946  case ENXIO:
21947  case ENOENT:
21948  case ESTALE:
21949  case ENOSYS:
21950    /* these should force the client to close the file and reconnect */
21951
21952  default:
21953    return sqliteIOErr;
21954  }
21955}
21956
21957
21958
21959/******************************************************************************
21960****************** Begin Unique File ID Utility Used By VxWorks ***************
21961**
21962** On most versions of unix, we can get a unique ID for a file by concatenating
21963** the device number and the inode number.  But this does not work on VxWorks.
21964** On VxWorks, a unique file id must be based on the canonical filename.
21965**
21966** A pointer to an instance of the following structure can be used as a
21967** unique file ID in VxWorks.  Each instance of this structure contains
21968** a copy of the canonical filename.  There is also a reference count.
21969** The structure is reclaimed when the number of pointers to it drops to
21970** zero.
21971**
21972** There are never very many files open at one time and lookups are not
21973** a performance-critical path, so it is sufficient to put these
21974** structures on a linked list.
21975*/
21976struct vxworksFileId {
21977  struct vxworksFileId *pNext;  /* Next in a list of them all */
21978  int nRef;                     /* Number of references to this one */
21979  int nName;                    /* Length of the zCanonicalName[] string */
21980  char *zCanonicalName;         /* Canonical filename */
21981};
21982
21983#if OS_VXWORKS
21984/*
21985** All unique filenames are held on a linked list headed by this
21986** variable:
21987*/
21988static struct vxworksFileId *vxworksFileList = 0;
21989
21990/*
21991** Simplify a filename into its canonical form
21992** by making the following changes:
21993**
21994**  * removing any trailing and duplicate /
21995**  * convert /./ into just /
21996**  * convert /A/../ where A is any simple name into just /
21997**
21998** Changes are made in-place.  Return the new name length.
21999**
22000** The original filename is in z[0..n-1].  Return the number of
22001** characters in the simplified name.
22002*/
22003static int vxworksSimplifyName(char *z, int n){
22004  int i, j;
22005  while( n>1 && z[n-1]=='/' ){ n--; }
22006  for(i=j=0; i<n; i++){
22007    if( z[i]=='/' ){
22008      if( z[i+1]=='/' ) continue;
22009      if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
22010        i += 1;
22011        continue;
22012      }
22013      if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
22014        while( j>0 && z[j-1]!='/' ){ j--; }
22015        if( j>0 ){ j--; }
22016        i += 2;
22017        continue;
22018      }
22019    }
22020    z[j++] = z[i];
22021  }
22022  z[j] = 0;
22023  return j;
22024}
22025
22026/*
22027** Find a unique file ID for the given absolute pathname.  Return
22028** a pointer to the vxworksFileId object.  This pointer is the unique
22029** file ID.
22030**
22031** The nRef field of the vxworksFileId object is incremented before
22032** the object is returned.  A new vxworksFileId object is created
22033** and added to the global list if necessary.
22034**
22035** If a memory allocation error occurs, return NULL.
22036*/
22037static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
22038  struct vxworksFileId *pNew;         /* search key and new file ID */
22039  struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
22040  int n;                              /* Length of zAbsoluteName string */
22041
22042  assert( zAbsoluteName[0]=='/' );
22043  n = (int)strlen(zAbsoluteName);
22044  pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
22045  if( pNew==0 ) return 0;
22046  pNew->zCanonicalName = (char*)&pNew[1];
22047  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
22048  n = vxworksSimplifyName(pNew->zCanonicalName, n);
22049
22050  /* Search for an existing entry that matching the canonical name.
22051  ** If found, increment the reference count and return a pointer to
22052  ** the existing file ID.
22053  */
22054  unixEnterMutex();
22055  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
22056    if( pCandidate->nName==n
22057     && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
22058    ){
22059       sqlite3_free(pNew);
22060       pCandidate->nRef++;
22061       unixLeaveMutex();
22062       return pCandidate;
22063    }
22064  }
22065
22066  /* No match was found.  We will make a new file ID */
22067  pNew->nRef = 1;
22068  pNew->nName = n;
22069  pNew->pNext = vxworksFileList;
22070  vxworksFileList = pNew;
22071  unixLeaveMutex();
22072  return pNew;
22073}
22074
22075/*
22076** Decrement the reference count on a vxworksFileId object.  Free
22077** the object when the reference count reaches zero.
22078*/
22079static void vxworksReleaseFileId(struct vxworksFileId *pId){
22080  unixEnterMutex();
22081  assert( pId->nRef>0 );
22082  pId->nRef--;
22083  if( pId->nRef==0 ){
22084    struct vxworksFileId **pp;
22085    for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
22086    assert( *pp==pId );
22087    *pp = pId->pNext;
22088    sqlite3_free(pId);
22089  }
22090  unixLeaveMutex();
22091}
22092#endif /* OS_VXWORKS */
22093/*************** End of Unique File ID Utility Used By VxWorks ****************
22094******************************************************************************/
22095
22096
22097/******************************************************************************
22098*************************** Posix Advisory Locking ****************************
22099**
22100** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
22101** section 6.5.2.2 lines 483 through 490 specify that when a process
22102** sets or clears a lock, that operation overrides any prior locks set
22103** by the same process.  It does not explicitly say so, but this implies
22104** that it overrides locks set by the same process using a different
22105** file descriptor.  Consider this test case:
22106**
22107**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
22108**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
22109**
22110** Suppose ./file1 and ./file2 are really the same file (because
22111** one is a hard or symbolic link to the other) then if you set
22112** an exclusive lock on fd1, then try to get an exclusive lock
22113** on fd2, it works.  I would have expected the second lock to
22114** fail since there was already a lock on the file due to fd1.
22115** But not so.  Since both locks came from the same process, the
22116** second overrides the first, even though they were on different
22117** file descriptors opened on different file names.
22118**
22119** This means that we cannot use POSIX locks to synchronize file access
22120** among competing threads of the same process.  POSIX locks will work fine
22121** to synchronize access for threads in separate processes, but not
22122** threads within the same process.
22123**
22124** To work around the problem, SQLite has to manage file locks internally
22125** on its own.  Whenever a new database is opened, we have to find the
22126** specific inode of the database file (the inode is determined by the
22127** st_dev and st_ino fields of the stat structure that fstat() fills in)
22128** and check for locks already existing on that inode.  When locks are
22129** created or removed, we have to look at our own internal record of the
22130** locks to see if another thread has previously set a lock on that same
22131** inode.
22132**
22133** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
22134** For VxWorks, we have to use the alternative unique ID system based on
22135** canonical filename and implemented in the previous division.)
22136**
22137** The sqlite3_file structure for POSIX is no longer just an integer file
22138** descriptor.  It is now a structure that holds the integer file
22139** descriptor and a pointer to a structure that describes the internal
22140** locks on the corresponding inode.  There is one locking structure
22141** per inode, so if the same inode is opened twice, both unixFile structures
22142** point to the same locking structure.  The locking structure keeps
22143** a reference count (so we will know when to delete it) and a "cnt"
22144** field that tells us its internal lock status.  cnt==0 means the
22145** file is unlocked.  cnt==-1 means the file has an exclusive lock.
22146** cnt>0 means there are cnt shared locks on the file.
22147**
22148** Any attempt to lock or unlock a file first checks the locking
22149** structure.  The fcntl() system call is only invoked to set a
22150** POSIX lock if the internal lock structure transitions between
22151** a locked and an unlocked state.
22152**
22153** But wait:  there are yet more problems with POSIX advisory locks.
22154**
22155** If you close a file descriptor that points to a file that has locks,
22156** all locks on that file that are owned by the current process are
22157** released.  To work around this problem, each unixFile structure contains
22158** a pointer to an unixOpenCnt structure.  There is one unixOpenCnt structure
22159** per open inode, which means that multiple unixFile can point to a single
22160** unixOpenCnt.  When an attempt is made to close an unixFile, if there are
22161** other unixFile open on the same inode that are holding locks, the call
22162** to close() the file descriptor is deferred until all of the locks clear.
22163** The unixOpenCnt structure keeps a list of file descriptors that need to
22164** be closed and that list is walked (and cleared) when the last lock
22165** clears.
22166**
22167** Yet another problem:  LinuxThreads do not play well with posix locks.
22168**
22169** Many older versions of linux use the LinuxThreads library which is
22170** not posix compliant.  Under LinuxThreads, a lock created by thread
22171** A cannot be modified or overridden by a different thread B.
22172** Only thread A can modify the lock.  Locking behavior is correct
22173** if the appliation uses the newer Native Posix Thread Library (NPTL)
22174** on linux - with NPTL a lock created by thread A can override locks
22175** in thread B.  But there is no way to know at compile-time which
22176** threading library is being used.  So there is no way to know at
22177** compile-time whether or not thread A can override locks on thread B.
22178** We have to do a run-time check to discover the behavior of the
22179** current process.
22180**
22181** On systems where thread A is unable to modify locks created by
22182** thread B, we have to keep track of which thread created each
22183** lock.  Hence there is an extra field in the key to the unixLockInfo
22184** structure to record this information.  And on those systems it
22185** is illegal to begin a transaction in one thread and finish it
22186** in another.  For this latter restriction, there is no work-around.
22187** It is a limitation of LinuxThreads.
22188*/
22189
22190/*
22191** Set or check the unixFile.tid field.  This field is set when an unixFile
22192** is first opened.  All subsequent uses of the unixFile verify that the
22193** same thread is operating on the unixFile.  Some operating systems do
22194** not allow locks to be overridden by other threads and that restriction
22195** means that sqlite3* database handles cannot be moved from one thread
22196** to another while locks are held.
22197**
22198** Version 3.3.1 (2006-01-15):  unixFile can be moved from one thread to
22199** another as long as we are running on a system that supports threads
22200** overriding each others locks (which is now the most common behavior)
22201** or if no locks are held.  But the unixFile.pLock field needs to be
22202** recomputed because its key includes the thread-id.  See the
22203** transferOwnership() function below for additional information
22204*/
22205#if SQLITE_THREADSAFE && defined(__linux__)
22206# define SET_THREADID(X)   (X)->tid = pthread_self()
22207# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
22208                            !pthread_equal((X)->tid, pthread_self()))
22209#else
22210# define SET_THREADID(X)
22211# define CHECK_THREADID(X) 0
22212#endif
22213
22214/*
22215** An instance of the following structure serves as the key used
22216** to locate a particular unixOpenCnt structure given its inode.  This
22217** is the same as the unixLockKey except that the thread ID is omitted.
22218*/
22219struct unixFileId {
22220  dev_t dev;                  /* Device number */
22221#if OS_VXWORKS
22222  struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
22223#else
22224  ino_t ino;                  /* Inode number */
22225#endif
22226};
22227
22228/*
22229** An instance of the following structure serves as the key used
22230** to locate a particular unixLockInfo structure given its inode.
22231**
22232** If threads cannot override each others locks (LinuxThreads), then we
22233** set the unixLockKey.tid field to the thread ID.  If threads can override
22234** each others locks (Posix and NPTL) then tid is always set to zero.
22235** tid is omitted if we compile without threading support or on an OS
22236** other than linux.
22237*/
22238struct unixLockKey {
22239  struct unixFileId fid;  /* Unique identifier for the file */
22240#if SQLITE_THREADSAFE && defined(__linux__)
22241  pthread_t tid;  /* Thread ID of lock owner. Zero if not using LinuxThreads */
22242#endif
22243};
22244
22245/*
22246** An instance of the following structure is allocated for each open
22247** inode.  Or, on LinuxThreads, there is one of these structures for
22248** each inode opened by each thread.
22249**
22250** A single inode can have multiple file descriptors, so each unixFile
22251** structure contains a pointer to an instance of this object and this
22252** object keeps a count of the number of unixFile pointing to it.
22253*/
22254struct unixLockInfo {
22255  struct unixLockKey lockKey;     /* The lookup key */
22256  int cnt;                        /* Number of SHARED locks held */
22257  int locktype;                   /* One of SHARED_LOCK, RESERVED_LOCK etc. */
22258  int nRef;                       /* Number of pointers to this structure */
22259  struct unixLockInfo *pNext;     /* List of all unixLockInfo objects */
22260  struct unixLockInfo *pPrev;     /*    .... doubly linked */
22261};
22262
22263/*
22264** An instance of the following structure is allocated for each open
22265** inode.  This structure keeps track of the number of locks on that
22266** inode.  If a close is attempted against an inode that is holding
22267** locks, the close is deferred until all locks clear by adding the
22268** file descriptor to be closed to the pending list.
22269**
22270** TODO:  Consider changing this so that there is only a single file
22271** descriptor for each open file, even when it is opened multiple times.
22272** The close() system call would only occur when the last database
22273** using the file closes.
22274*/
22275struct unixOpenCnt {
22276  struct unixFileId fileId;   /* The lookup key */
22277  int nRef;                   /* Number of pointers to this structure */
22278  int nLock;                  /* Number of outstanding locks */
22279  UnixUnusedFd *pUnused;      /* Unused file descriptors to close */
22280#if OS_VXWORKS
22281  sem_t *pSem;                     /* Named POSIX semaphore */
22282  char aSemName[MAX_PATHNAME+2];   /* Name of that semaphore */
22283#endif
22284  struct unixOpenCnt *pNext, *pPrev;   /* List of all unixOpenCnt objects */
22285};
22286
22287/*
22288** Lists of all unixLockInfo and unixOpenCnt objects.  These used to be hash
22289** tables.  But the number of objects is rarely more than a dozen and
22290** never exceeds a few thousand.  And lookup is not on a critical
22291** path so a simple linked list will suffice.
22292*/
22293static struct unixLockInfo *lockList = 0;
22294static struct unixOpenCnt *openList = 0;
22295
22296/*
22297** This variable remembers whether or not threads can override each others
22298** locks.
22299**
22300**    0:  No.  Threads cannot override each others locks.  (LinuxThreads)
22301**    1:  Yes.  Threads can override each others locks.  (Posix & NLPT)
22302**   -1:  We don't know yet.
22303**
22304** On some systems, we know at compile-time if threads can override each
22305** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
22306** will be set appropriately.  On other systems, we have to check at
22307** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
22308** undefined.
22309**
22310** This variable normally has file scope only.  But during testing, we make
22311** it a global so that the test code can change its value in order to verify
22312** that the right stuff happens in either case.
22313*/
22314#if SQLITE_THREADSAFE && defined(__linux__)
22315#  ifndef SQLITE_THREAD_OVERRIDE_LOCK
22316#    define SQLITE_THREAD_OVERRIDE_LOCK -1
22317#  endif
22318#  ifdef SQLITE_TEST
22319int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22320#  else
22321static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22322#  endif
22323#endif
22324
22325/*
22326** This structure holds information passed into individual test
22327** threads by the testThreadLockingBehavior() routine.
22328*/
22329struct threadTestData {
22330  int fd;                /* File to be locked */
22331  struct flock lock;     /* The locking operation */
22332  int result;            /* Result of the locking operation */
22333};
22334
22335#if SQLITE_THREADSAFE && defined(__linux__)
22336/*
22337** This function is used as the main routine for a thread launched by
22338** testThreadLockingBehavior(). It tests whether the shared-lock obtained
22339** by the main thread in testThreadLockingBehavior() conflicts with a
22340** hypothetical write-lock obtained by this thread on the same file.
22341**
22342** The write-lock is not actually acquired, as this is not possible if
22343** the file is open in read-only mode (see ticket #3472).
22344*/
22345static void *threadLockingTest(void *pArg){
22346  struct threadTestData *pData = (struct threadTestData*)pArg;
22347  pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
22348  return pArg;
22349}
22350#endif /* SQLITE_THREADSAFE && defined(__linux__) */
22351
22352
22353#if SQLITE_THREADSAFE && defined(__linux__)
22354/*
22355** This procedure attempts to determine whether or not threads
22356** can override each others locks then sets the
22357** threadsOverrideEachOthersLocks variable appropriately.
22358*/
22359static void testThreadLockingBehavior(int fd_orig){
22360  int fd;
22361  int rc;
22362  struct threadTestData d;
22363  struct flock l;
22364  pthread_t t;
22365
22366  fd = dup(fd_orig);
22367  if( fd<0 ) return;
22368  memset(&l, 0, sizeof(l));
22369  l.l_type = F_RDLCK;
22370  l.l_len = 1;
22371  l.l_start = 0;
22372  l.l_whence = SEEK_SET;
22373  rc = fcntl(fd_orig, F_SETLK, &l);
22374  if( rc!=0 ) return;
22375  memset(&d, 0, sizeof(d));
22376  d.fd = fd;
22377  d.lock = l;
22378  d.lock.l_type = F_WRLCK;
22379  if( pthread_create(&t, 0, threadLockingTest, &d)==0 ){
22380    pthread_join(t, 0);
22381  }
22382  close(fd);
22383  if( d.result!=0 ) return;
22384  threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
22385}
22386#endif /* SQLITE_THREADSAFE && defined(__linux__) */
22387
22388/*
22389** Release a unixLockInfo structure previously allocated by findLockInfo().
22390**
22391** The mutex entered using the unixEnterMutex() function must be held
22392** when this function is called.
22393*/
22394static void releaseLockInfo(struct unixLockInfo *pLock){
22395  assert( unixMutexHeld() );
22396  if( pLock ){
22397    pLock->nRef--;
22398    if( pLock->nRef==0 ){
22399      if( pLock->pPrev ){
22400        assert( pLock->pPrev->pNext==pLock );
22401        pLock->pPrev->pNext = pLock->pNext;
22402      }else{
22403        assert( lockList==pLock );
22404        lockList = pLock->pNext;
22405      }
22406      if( pLock->pNext ){
22407        assert( pLock->pNext->pPrev==pLock );
22408        pLock->pNext->pPrev = pLock->pPrev;
22409      }
22410      sqlite3_free(pLock);
22411    }
22412  }
22413}
22414
22415/*
22416** Release a unixOpenCnt structure previously allocated by findLockInfo().
22417**
22418** The mutex entered using the unixEnterMutex() function must be held
22419** when this function is called.
22420*/
22421static void releaseOpenCnt(struct unixOpenCnt *pOpen){
22422  assert( unixMutexHeld() );
22423  if( pOpen ){
22424    pOpen->nRef--;
22425    if( pOpen->nRef==0 ){
22426      if( pOpen->pPrev ){
22427        assert( pOpen->pPrev->pNext==pOpen );
22428        pOpen->pPrev->pNext = pOpen->pNext;
22429      }else{
22430        assert( openList==pOpen );
22431        openList = pOpen->pNext;
22432      }
22433      if( pOpen->pNext ){
22434        assert( pOpen->pNext->pPrev==pOpen );
22435        pOpen->pNext->pPrev = pOpen->pPrev;
22436      }
22437#if SQLITE_THREADSAFE && defined(__linux__)
22438      assert( !pOpen->pUnused || threadsOverrideEachOthersLocks==0 );
22439#endif
22440
22441      /* If pOpen->pUnused is not null, then memory and file-descriptors
22442      ** are leaked.
22443      **
22444      ** This will only happen if, under Linuxthreads, the user has opened
22445      ** a transaction in one thread, then attempts to close the database
22446      ** handle from another thread (without first unlocking the db file).
22447      ** This is a misuse.  */
22448      sqlite3_free(pOpen);
22449    }
22450  }
22451}
22452
22453/*
22454** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
22455** describes that file descriptor.  Create new ones if necessary.  The
22456** return values might be uninitialized if an error occurs.
22457**
22458** The mutex entered using the unixEnterMutex() function must be held
22459** when this function is called.
22460**
22461** Return an appropriate error code.
22462*/
22463static int findLockInfo(
22464  unixFile *pFile,               /* Unix file with file desc used in the key */
22465  struct unixLockInfo **ppLock,  /* Return the unixLockInfo structure here */
22466  struct unixOpenCnt **ppOpen    /* Return the unixOpenCnt structure here */
22467){
22468  int rc;                        /* System call return code */
22469  int fd;                        /* The file descriptor for pFile */
22470  struct unixLockKey lockKey;    /* Lookup key for the unixLockInfo structure */
22471  struct unixFileId fileId;      /* Lookup key for the unixOpenCnt struct */
22472  struct stat statbuf;           /* Low-level file information */
22473  struct unixLockInfo *pLock = 0;/* Candidate unixLockInfo object */
22474  struct unixOpenCnt *pOpen;     /* Candidate unixOpenCnt object */
22475
22476  assert( unixMutexHeld() );
22477
22478  /* Get low-level information about the file that we can used to
22479  ** create a unique name for the file.
22480  */
22481  fd = pFile->h;
22482  rc = fstat(fd, &statbuf);
22483  if( rc!=0 ){
22484    pFile->lastErrno = errno;
22485#ifdef EOVERFLOW
22486    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
22487#endif
22488    return SQLITE_IOERR;
22489  }
22490
22491#ifdef __APPLE__
22492  /* On OS X on an msdos filesystem, the inode number is reported
22493  ** incorrectly for zero-size files.  See ticket #3260.  To work
22494  ** around this problem (we consider it a bug in OS X, not SQLite)
22495  ** we always increase the file size to 1 by writing a single byte
22496  ** prior to accessing the inode number.  The one byte written is
22497  ** an ASCII 'S' character which also happens to be the first byte
22498  ** in the header of every SQLite database.  In this way, if there
22499  ** is a race condition such that another thread has already populated
22500  ** the first page of the database, no damage is done.
22501  */
22502  if( statbuf.st_size==0 ){
22503    rc = write(fd, "S", 1);
22504    if( rc!=1 ){
22505      return SQLITE_IOERR;
22506    }
22507    rc = fstat(fd, &statbuf);
22508    if( rc!=0 ){
22509      pFile->lastErrno = errno;
22510      return SQLITE_IOERR;
22511    }
22512  }
22513#endif
22514
22515  memset(&lockKey, 0, sizeof(lockKey));
22516  lockKey.fid.dev = statbuf.st_dev;
22517#if OS_VXWORKS
22518  lockKey.fid.pId = pFile->pId;
22519#else
22520  lockKey.fid.ino = statbuf.st_ino;
22521#endif
22522#if SQLITE_THREADSAFE && defined(__linux__)
22523  if( threadsOverrideEachOthersLocks<0 ){
22524    testThreadLockingBehavior(fd);
22525  }
22526  lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
22527#endif
22528  fileId = lockKey.fid;
22529  if( ppLock!=0 ){
22530    pLock = lockList;
22531    while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
22532      pLock = pLock->pNext;
22533    }
22534    if( pLock==0 ){
22535      pLock = sqlite3_malloc( sizeof(*pLock) );
22536      if( pLock==0 ){
22537        rc = SQLITE_NOMEM;
22538        goto exit_findlockinfo;
22539      }
22540      memcpy(&pLock->lockKey,&lockKey,sizeof(lockKey));
22541      pLock->nRef = 1;
22542      pLock->cnt = 0;
22543      pLock->locktype = 0;
22544      pLock->pNext = lockList;
22545      pLock->pPrev = 0;
22546      if( lockList ) lockList->pPrev = pLock;
22547      lockList = pLock;
22548    }else{
22549      pLock->nRef++;
22550    }
22551    *ppLock = pLock;
22552  }
22553  if( ppOpen!=0 ){
22554    pOpen = openList;
22555    while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
22556      pOpen = pOpen->pNext;
22557    }
22558    if( pOpen==0 ){
22559      pOpen = sqlite3_malloc( sizeof(*pOpen) );
22560      if( pOpen==0 ){
22561        releaseLockInfo(pLock);
22562        rc = SQLITE_NOMEM;
22563        goto exit_findlockinfo;
22564      }
22565      memset(pOpen, 0, sizeof(*pOpen));
22566      pOpen->fileId = fileId;
22567      pOpen->nRef = 1;
22568      pOpen->pNext = openList;
22569      if( openList ) openList->pPrev = pOpen;
22570      openList = pOpen;
22571    }else{
22572      pOpen->nRef++;
22573    }
22574    *ppOpen = pOpen;
22575  }
22576
22577exit_findlockinfo:
22578  return rc;
22579}
22580
22581/*
22582** If we are currently in a different thread than the thread that the
22583** unixFile argument belongs to, then transfer ownership of the unixFile
22584** over to the current thread.
22585**
22586** A unixFile is only owned by a thread on systems that use LinuxThreads.
22587**
22588** Ownership transfer is only allowed if the unixFile is currently unlocked.
22589** If the unixFile is locked and an ownership is wrong, then return
22590** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
22591*/
22592#if SQLITE_THREADSAFE && defined(__linux__)
22593static int transferOwnership(unixFile *pFile){
22594  int rc;
22595  pthread_t hSelf;
22596  if( threadsOverrideEachOthersLocks ){
22597    /* Ownership transfers not needed on this system */
22598    return SQLITE_OK;
22599  }
22600  hSelf = pthread_self();
22601  if( pthread_equal(pFile->tid, hSelf) ){
22602    /* We are still in the same thread */
22603    OSTRACE1("No-transfer, same thread\n");
22604    return SQLITE_OK;
22605  }
22606  if( pFile->locktype!=NO_LOCK ){
22607    /* We cannot change ownership while we are holding a lock! */
22608    return SQLITE_MISUSE_BKPT;
22609  }
22610  OSTRACE4("Transfer ownership of %d from %d to %d\n",
22611            pFile->h, pFile->tid, hSelf);
22612  pFile->tid = hSelf;
22613  if (pFile->pLock != NULL) {
22614    releaseLockInfo(pFile->pLock);
22615    rc = findLockInfo(pFile, &pFile->pLock, 0);
22616    OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
22617           locktypeName(pFile->locktype),
22618           locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
22619    return rc;
22620  } else {
22621    return SQLITE_OK;
22622  }
22623}
22624#else  /* if not SQLITE_THREADSAFE */
22625  /* On single-threaded builds, ownership transfer is a no-op */
22626# define transferOwnership(X) SQLITE_OK
22627#endif /* SQLITE_THREADSAFE */
22628
22629
22630/*
22631** This routine checks if there is a RESERVED lock held on the specified
22632** file by this or any other process. If such a lock is held, set *pResOut
22633** to a non-zero value otherwise *pResOut is set to zero.  The return value
22634** is set to SQLITE_OK unless an I/O error occurs during lock checking.
22635*/
22636static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
22637  int rc = SQLITE_OK;
22638  int reserved = 0;
22639  unixFile *pFile = (unixFile*)id;
22640
22641  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
22642
22643  assert( pFile );
22644  unixEnterMutex(); /* Because pFile->pLock is shared across threads */
22645
22646  /* Check if a thread in this process holds such a lock */
22647  if( pFile->pLock->locktype>SHARED_LOCK ){
22648    reserved = 1;
22649  }
22650
22651  /* Otherwise see if some other process holds it.
22652  */
22653#ifndef __DJGPP__
22654  if( !reserved ){
22655    struct flock lock;
22656    lock.l_whence = SEEK_SET;
22657    lock.l_start = RESERVED_BYTE;
22658    lock.l_len = 1;
22659    lock.l_type = F_WRLCK;
22660    if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
22661      int tErrno = errno;
22662      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
22663      pFile->lastErrno = tErrno;
22664    } else if( lock.l_type!=F_UNLCK ){
22665      reserved = 1;
22666    }
22667  }
22668#endif
22669
22670  unixLeaveMutex();
22671  OSTRACE4("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved);
22672
22673  *pResOut = reserved;
22674  return rc;
22675}
22676
22677/*
22678** Perform a file locking operation on a range of bytes in a file.
22679** The "op" parameter should be one of F_RDLCK, F_WRLCK, or F_UNLCK.
22680** Return 0 on success or -1 for failure.  On failure, write the error
22681** code into *pErrcode.
22682**
22683** If the SQLITE_WHOLE_FILE_LOCKING bit is clear, then only lock
22684** the range of bytes on the locking page between SHARED_FIRST and
22685** SHARED_SIZE.  If SQLITE_WHOLE_FILE_LOCKING is set, then lock all
22686** bytes from 0 up to but not including PENDING_BYTE, and all bytes
22687** that follow SHARED_FIRST.
22688**
22689** In other words, of SQLITE_WHOLE_FILE_LOCKING if false (the historical
22690** default case) then only lock a small range of bytes from SHARED_FIRST
22691** through SHARED_FIRST+SHARED_SIZE-1.  But if SQLITE_WHOLE_FILE_LOCKING is
22692** true then lock every byte in the file except for PENDING_BYTE and
22693** RESERVED_BYTE.
22694**
22695** SQLITE_WHOLE_FILE_LOCKING=true overlaps SQLITE_WHOLE_FILE_LOCKING=false
22696** and so the locking schemes are compatible.  One type of lock will
22697** effectively exclude the other type.  The reason for using the
22698** SQLITE_WHOLE_FILE_LOCKING=true is that by indicating the full range
22699** of bytes to be read or written, we give hints to NFS to help it
22700** maintain cache coherency.  On the other hand, whole file locking
22701** is slower, so we don't want to use it except for NFS.
22702*/
22703static int rangeLock(unixFile *pFile, int op, int *pErrcode){
22704  struct flock lock;
22705  int rc;
22706  lock.l_type = op;
22707  lock.l_start = SHARED_FIRST;
22708  lock.l_whence = SEEK_SET;
22709  if( (pFile->fileFlags & SQLITE_WHOLE_FILE_LOCKING)==0 ){
22710    lock.l_len = SHARED_SIZE;
22711    rc = fcntl(pFile->h, F_SETLK, &lock);
22712    *pErrcode = errno;
22713  }else{
22714    lock.l_len = 0;
22715    rc = fcntl(pFile->h, F_SETLK, &lock);
22716    *pErrcode = errno;
22717    if( NEVER(op==F_UNLCK) || rc!=(-1) ){
22718      lock.l_start = 0;
22719      lock.l_len = PENDING_BYTE;
22720      rc = fcntl(pFile->h, F_SETLK, &lock);
22721      if( ALWAYS(op!=F_UNLCK) && rc==(-1) ){
22722        *pErrcode = errno;
22723        lock.l_type = F_UNLCK;
22724        lock.l_start = SHARED_FIRST;
22725        lock.l_len = 0;
22726        fcntl(pFile->h, F_SETLK, &lock);
22727      }
22728    }
22729  }
22730  return rc;
22731}
22732
22733/*
22734** Lock the file with the lock specified by parameter locktype - one
22735** of the following:
22736**
22737**     (1) SHARED_LOCK
22738**     (2) RESERVED_LOCK
22739**     (3) PENDING_LOCK
22740**     (4) EXCLUSIVE_LOCK
22741**
22742** Sometimes when requesting one lock state, additional lock states
22743** are inserted in between.  The locking might fail on one of the later
22744** transitions leaving the lock state different from what it started but
22745** still short of its goal.  The following chart shows the allowed
22746** transitions and the inserted intermediate states:
22747**
22748**    UNLOCKED -> SHARED
22749**    SHARED -> RESERVED
22750**    SHARED -> (PENDING) -> EXCLUSIVE
22751**    RESERVED -> (PENDING) -> EXCLUSIVE
22752**    PENDING -> EXCLUSIVE
22753**
22754** This routine will only increase a lock.  Use the sqlite3OsUnlock()
22755** routine to lower a locking level.
22756*/
22757static int unixLock(sqlite3_file *id, int locktype){
22758  /* The following describes the implementation of the various locks and
22759  ** lock transitions in terms of the POSIX advisory shared and exclusive
22760  ** lock primitives (called read-locks and write-locks below, to avoid
22761  ** confusion with SQLite lock names). The algorithms are complicated
22762  ** slightly in order to be compatible with windows systems simultaneously
22763  ** accessing the same database file, in case that is ever required.
22764  **
22765  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
22766  ** byte', each single bytes at well known offsets, and the 'shared byte
22767  ** range', a range of 510 bytes at a well known offset.
22768  **
22769  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
22770  ** byte'.  If this is successful, a random byte from the 'shared byte
22771  ** range' is read-locked and the lock on the 'pending byte' released.
22772  **
22773  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
22774  ** A RESERVED lock is implemented by grabbing a write-lock on the
22775  ** 'reserved byte'.
22776  **
22777  ** A process may only obtain a PENDING lock after it has obtained a
22778  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
22779  ** on the 'pending byte'. This ensures that no new SHARED locks can be
22780  ** obtained, but existing SHARED locks are allowed to persist. A process
22781  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
22782  ** This property is used by the algorithm for rolling back a journal file
22783  ** after a crash.
22784  **
22785  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
22786  ** implemented by obtaining a write-lock on the entire 'shared byte
22787  ** range'. Since all other locks require a read-lock on one of the bytes
22788  ** within this range, this ensures that no other locks are held on the
22789  ** database.
22790  **
22791  ** The reason a single byte cannot be used instead of the 'shared byte
22792  ** range' is that some versions of windows do not support read-locks. By
22793  ** locking a random byte from a range, concurrent SHARED locks may exist
22794  ** even if the locking primitive used is always a write-lock.
22795  */
22796  int rc = SQLITE_OK;
22797  unixFile *pFile = (unixFile*)id;
22798  struct unixLockInfo *pLock = pFile->pLock;
22799  struct flock lock;
22800  int s = 0;
22801  int tErrno;
22802
22803  assert( pFile );
22804  OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
22805      locktypeName(locktype), locktypeName(pFile->locktype),
22806      locktypeName(pLock->locktype), pLock->cnt , getpid());
22807
22808  /* If there is already a lock of this type or more restrictive on the
22809  ** unixFile, do nothing. Don't use the end_lock: exit path, as
22810  ** unixEnterMutex() hasn't been called yet.
22811  */
22812  if( pFile->locktype>=locktype ){
22813    OSTRACE3("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
22814            locktypeName(locktype));
22815    return SQLITE_OK;
22816  }
22817
22818  /* Make sure the locking sequence is correct.
22819  **  (1) We never move from unlocked to anything higher than shared lock.
22820  **  (2) SQLite never explicitly requests a pendig lock.
22821  **  (3) A shared lock is always held when a reserve lock is requested.
22822  */
22823  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
22824  assert( locktype!=PENDING_LOCK );
22825  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
22826
22827  /* This mutex is needed because pFile->pLock is shared across threads
22828  */
22829  unixEnterMutex();
22830
22831  /* Make sure the current thread owns the pFile.
22832  */
22833  rc = transferOwnership(pFile);
22834  if( rc!=SQLITE_OK ){
22835    unixLeaveMutex();
22836    return rc;
22837  }
22838  pLock = pFile->pLock;
22839
22840  /* If some thread using this PID has a lock via a different unixFile*
22841  ** handle that precludes the requested lock, return BUSY.
22842  */
22843  if( (pFile->locktype!=pLock->locktype &&
22844          (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
22845  ){
22846    rc = SQLITE_BUSY;
22847    goto end_lock;
22848  }
22849
22850  /* If a SHARED lock is requested, and some thread using this PID already
22851  ** has a SHARED or RESERVED lock, then increment reference counts and
22852  ** return SQLITE_OK.
22853  */
22854  if( locktype==SHARED_LOCK &&
22855      (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
22856    assert( locktype==SHARED_LOCK );
22857    assert( pFile->locktype==0 );
22858    assert( pLock->cnt>0 );
22859    pFile->locktype = SHARED_LOCK;
22860    pLock->cnt++;
22861    pFile->pOpen->nLock++;
22862    goto end_lock;
22863  }
22864
22865
22866  /* A PENDING lock is needed before acquiring a SHARED lock and before
22867  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
22868  ** be released.
22869  */
22870  lock.l_len = 1L;
22871  lock.l_whence = SEEK_SET;
22872  if( locktype==SHARED_LOCK
22873      || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
22874  ){
22875    lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
22876    lock.l_start = PENDING_BYTE;
22877    s = fcntl(pFile->h, F_SETLK, &lock);
22878    if( s==(-1) ){
22879      tErrno = errno;
22880      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
22881      if( IS_LOCK_ERROR(rc) ){
22882        pFile->lastErrno = tErrno;
22883      }
22884      goto end_lock;
22885    }
22886  }
22887
22888
22889  /* If control gets to this point, then actually go ahead and make
22890  ** operating system calls for the specified lock.
22891  */
22892  if( locktype==SHARED_LOCK ){
22893    assert( pLock->cnt==0 );
22894    assert( pLock->locktype==0 );
22895
22896    /* Now get the read-lock */
22897    s = rangeLock(pFile, F_RDLCK, &tErrno);
22898
22899    /* Drop the temporary PENDING lock */
22900    lock.l_start = PENDING_BYTE;
22901    lock.l_len = 1L;
22902    lock.l_type = F_UNLCK;
22903    if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
22904      if( s != -1 ){
22905        /* This could happen with a network mount */
22906        tErrno = errno;
22907        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
22908        if( IS_LOCK_ERROR(rc) ){
22909          pFile->lastErrno = tErrno;
22910        }
22911        goto end_lock;
22912      }
22913    }
22914    if( s==(-1) ){
22915      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
22916      if( IS_LOCK_ERROR(rc) ){
22917        pFile->lastErrno = tErrno;
22918      }
22919    }else{
22920      pFile->locktype = SHARED_LOCK;
22921      pFile->pOpen->nLock++;
22922      pLock->cnt = 1;
22923    }
22924  }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
22925    /* We are trying for an exclusive lock but another thread in this
22926    ** same process is still holding a shared lock. */
22927    rc = SQLITE_BUSY;
22928  }else{
22929    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
22930    ** assumed that there is a SHARED or greater lock on the file
22931    ** already.
22932    */
22933    assert( 0!=pFile->locktype );
22934    lock.l_type = F_WRLCK;
22935    switch( locktype ){
22936      case RESERVED_LOCK:
22937        lock.l_start = RESERVED_BYTE;
22938        s = fcntl(pFile->h, F_SETLK, &lock);
22939        tErrno = errno;
22940        break;
22941      case EXCLUSIVE_LOCK:
22942        s = rangeLock(pFile, F_WRLCK, &tErrno);
22943        break;
22944      default:
22945        assert(0);
22946    }
22947    if( s==(-1) ){
22948      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
22949      if( IS_LOCK_ERROR(rc) ){
22950        pFile->lastErrno = tErrno;
22951      }
22952    }
22953  }
22954
22955
22956#ifndef NDEBUG
22957  /* Set up the transaction-counter change checking flags when
22958  ** transitioning from a SHARED to a RESERVED lock.  The change
22959  ** from SHARED to RESERVED marks the beginning of a normal
22960  ** write operation (not a hot journal rollback).
22961  */
22962  if( rc==SQLITE_OK
22963   && pFile->locktype<=SHARED_LOCK
22964   && locktype==RESERVED_LOCK
22965  ){
22966    pFile->transCntrChng = 0;
22967    pFile->dbUpdate = 0;
22968    pFile->inNormalWrite = 1;
22969  }
22970#endif
22971
22972
22973  if( rc==SQLITE_OK ){
22974    pFile->locktype = locktype;
22975    pLock->locktype = locktype;
22976  }else if( locktype==EXCLUSIVE_LOCK ){
22977    pFile->locktype = PENDING_LOCK;
22978    pLock->locktype = PENDING_LOCK;
22979  }
22980
22981end_lock:
22982  unixLeaveMutex();
22983  OSTRACE4("LOCK    %d %s %s (unix)\n", pFile->h, locktypeName(locktype),
22984      rc==SQLITE_OK ? "ok" : "failed");
22985  return rc;
22986}
22987
22988/*
22989** Close all file descriptors accumuated in the unixOpenCnt->pUnused list.
22990** If all such file descriptors are closed without error, the list is
22991** cleared and SQLITE_OK returned.
22992**
22993** Otherwise, if an error occurs, then successfully closed file descriptor
22994** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
22995** not deleted and SQLITE_IOERR_CLOSE returned.
22996*/
22997static int closePendingFds(unixFile *pFile){
22998  int rc = SQLITE_OK;
22999  struct unixOpenCnt *pOpen = pFile->pOpen;
23000  UnixUnusedFd *pError = 0;
23001  UnixUnusedFd *p;
23002  UnixUnusedFd *pNext;
23003  for(p=pOpen->pUnused; p; p=pNext){
23004    pNext = p->pNext;
23005    if( close(p->fd) ){
23006      pFile->lastErrno = errno;
23007      rc = SQLITE_IOERR_CLOSE;
23008      p->pNext = pError;
23009      pError = p;
23010    }else{
23011      sqlite3_free(p);
23012    }
23013  }
23014  pOpen->pUnused = pError;
23015  return rc;
23016}
23017
23018/*
23019** Add the file descriptor used by file handle pFile to the corresponding
23020** pUnused list.
23021*/
23022static void setPendingFd(unixFile *pFile){
23023  struct unixOpenCnt *pOpen = pFile->pOpen;
23024  UnixUnusedFd *p = pFile->pUnused;
23025  p->pNext = pOpen->pUnused;
23026  pOpen->pUnused = p;
23027  pFile->h = -1;
23028  pFile->pUnused = 0;
23029}
23030
23031/*
23032** Lower the locking level on file descriptor pFile to locktype.  locktype
23033** must be either NO_LOCK or SHARED_LOCK.
23034**
23035** If the locking level of the file descriptor is already at or below
23036** the requested locking level, this routine is a no-op.
23037*/
23038static int unixUnlock(sqlite3_file *id, int locktype){
23039  unixFile *pFile = (unixFile*)id; /* The open file */
23040  struct unixLockInfo *pLock;      /* Structure describing current lock state */
23041  struct flock lock;               /* Information passed into fcntl() */
23042  int rc = SQLITE_OK;              /* Return code from this interface */
23043  int h;                           /* The underlying file descriptor */
23044  int tErrno;                      /* Error code from system call errors */
23045
23046  assert( pFile );
23047  OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, locktype,
23048      pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
23049
23050  assert( locktype<=SHARED_LOCK );
23051  if( pFile->locktype<=locktype ){
23052    return SQLITE_OK;
23053  }
23054  if( CHECK_THREADID(pFile) ){
23055    return SQLITE_MISUSE_BKPT;
23056  }
23057  unixEnterMutex();
23058  h = pFile->h;
23059  pLock = pFile->pLock;
23060  assert( pLock->cnt!=0 );
23061  if( pFile->locktype>SHARED_LOCK ){
23062    assert( pLock->locktype==pFile->locktype );
23063    SimulateIOErrorBenign(1);
23064    SimulateIOError( h=(-1) )
23065    SimulateIOErrorBenign(0);
23066
23067#ifndef NDEBUG
23068    /* When reducing a lock such that other processes can start
23069    ** reading the database file again, make sure that the
23070    ** transaction counter was updated if any part of the database
23071    ** file changed.  If the transaction counter is not updated,
23072    ** other connections to the same file might not realize that
23073    ** the file has changed and hence might not know to flush their
23074    ** cache.  The use of a stale cache can lead to database corruption.
23075    */
23076    assert( pFile->inNormalWrite==0
23077         || pFile->dbUpdate==0
23078         || pFile->transCntrChng==1 );
23079    pFile->inNormalWrite = 0;
23080#endif
23081
23082
23083    if( locktype==SHARED_LOCK ){
23084      if( rangeLock(pFile, F_RDLCK, &tErrno)==(-1) ){
23085        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
23086        if( IS_LOCK_ERROR(rc) ){
23087          pFile->lastErrno = tErrno;
23088        }
23089        goto end_unlock;
23090      }
23091    }
23092    lock.l_type = F_UNLCK;
23093    lock.l_whence = SEEK_SET;
23094    lock.l_start = PENDING_BYTE;
23095    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
23096    if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23097      pLock->locktype = SHARED_LOCK;
23098    }else{
23099      tErrno = errno;
23100      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23101      if( IS_LOCK_ERROR(rc) ){
23102        pFile->lastErrno = tErrno;
23103      }
23104      goto end_unlock;
23105    }
23106  }
23107  if( locktype==NO_LOCK ){
23108    struct unixOpenCnt *pOpen;
23109
23110    /* Decrement the shared lock counter.  Release the lock using an
23111    ** OS call only when all threads in this same process have released
23112    ** the lock.
23113    */
23114    pLock->cnt--;
23115    if( pLock->cnt==0 ){
23116      lock.l_type = F_UNLCK;
23117      lock.l_whence = SEEK_SET;
23118      lock.l_start = lock.l_len = 0L;
23119      SimulateIOErrorBenign(1);
23120      SimulateIOError( h=(-1) )
23121      SimulateIOErrorBenign(0);
23122      if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23123        pLock->locktype = NO_LOCK;
23124      }else{
23125        tErrno = errno;
23126        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23127        if( IS_LOCK_ERROR(rc) ){
23128          pFile->lastErrno = tErrno;
23129        }
23130        pLock->locktype = NO_LOCK;
23131        pFile->locktype = NO_LOCK;
23132      }
23133    }
23134
23135    /* Decrement the count of locks against this same file.  When the
23136    ** count reaches zero, close any other file descriptors whose close
23137    ** was deferred because of outstanding locks.
23138    */
23139    pOpen = pFile->pOpen;
23140    pOpen->nLock--;
23141    assert( pOpen->nLock>=0 );
23142    if( pOpen->nLock==0 ){
23143      int rc2 = closePendingFds(pFile);
23144      if( rc==SQLITE_OK ){
23145        rc = rc2;
23146      }
23147    }
23148  }
23149
23150end_unlock:
23151  unixLeaveMutex();
23152  if( rc==SQLITE_OK ) pFile->locktype = locktype;
23153  return rc;
23154}
23155
23156/*
23157** This function performs the parts of the "close file" operation
23158** common to all locking schemes. It closes the directory and file
23159** handles, if they are valid, and sets all fields of the unixFile
23160** structure to 0.
23161**
23162** It is *not* necessary to hold the mutex when this routine is called,
23163** even on VxWorks.  A mutex will be acquired on VxWorks by the
23164** vxworksReleaseFileId() routine.
23165*/
23166static int closeUnixFile(sqlite3_file *id){
23167  unixFile *pFile = (unixFile*)id;
23168  if( pFile ){
23169    if( pFile->dirfd>=0 ){
23170      int err = close(pFile->dirfd);
23171      if( err ){
23172        pFile->lastErrno = errno;
23173        return SQLITE_IOERR_DIR_CLOSE;
23174      }else{
23175        pFile->dirfd=-1;
23176      }
23177    }
23178    if( pFile->h>=0 ){
23179      int err = close(pFile->h);
23180      if( err ){
23181        pFile->lastErrno = errno;
23182        return SQLITE_IOERR_CLOSE;
23183      }
23184    }
23185#if OS_VXWORKS
23186    if( pFile->pId ){
23187      if( pFile->isDelete ){
23188        unlink(pFile->pId->zCanonicalName);
23189      }
23190      vxworksReleaseFileId(pFile->pId);
23191      pFile->pId = 0;
23192    }
23193#endif
23194    OSTRACE2("CLOSE   %-3d\n", pFile->h);
23195    OpenCounter(-1);
23196    sqlite3_free(pFile->pUnused);
23197    memset(pFile, 0, sizeof(unixFile));
23198  }
23199  return SQLITE_OK;
23200}
23201
23202/*
23203** Close a file.
23204*/
23205static int unixClose(sqlite3_file *id){
23206  int rc = SQLITE_OK;
23207  if( id ){
23208    unixFile *pFile = (unixFile *)id;
23209    unixUnlock(id, NO_LOCK);
23210    unixEnterMutex();
23211    if( pFile->pOpen && pFile->pOpen->nLock ){
23212      /* If there are outstanding locks, do not actually close the file just
23213      ** yet because that would clear those locks.  Instead, add the file
23214      ** descriptor to pOpen->pUnused list.  It will be automatically closed
23215      ** when the last lock is cleared.
23216      */
23217      setPendingFd(pFile);
23218    }
23219    releaseLockInfo(pFile->pLock);
23220    releaseOpenCnt(pFile->pOpen);
23221    rc = closeUnixFile(id);
23222    unixLeaveMutex();
23223  }
23224  return rc;
23225}
23226
23227/************** End of the posix advisory lock implementation *****************
23228******************************************************************************/
23229
23230/******************************************************************************
23231****************************** No-op Locking **********************************
23232**
23233** Of the various locking implementations available, this is by far the
23234** simplest:  locking is ignored.  No attempt is made to lock the database
23235** file for reading or writing.
23236**
23237** This locking mode is appropriate for use on read-only databases
23238** (ex: databases that are burned into CD-ROM, for example.)  It can
23239** also be used if the application employs some external mechanism to
23240** prevent simultaneous access of the same database by two or more
23241** database connections.  But there is a serious risk of database
23242** corruption if this locking mode is used in situations where multiple
23243** database connections are accessing the same database file at the same
23244** time and one or more of those connections are writing.
23245*/
23246
23247static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
23248  UNUSED_PARAMETER(NotUsed);
23249  *pResOut = 0;
23250  return SQLITE_OK;
23251}
23252static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
23253  UNUSED_PARAMETER2(NotUsed, NotUsed2);
23254  return SQLITE_OK;
23255}
23256static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
23257  UNUSED_PARAMETER2(NotUsed, NotUsed2);
23258  return SQLITE_OK;
23259}
23260
23261/*
23262** Close the file.
23263*/
23264static int nolockClose(sqlite3_file *id) {
23265  return closeUnixFile(id);
23266}
23267
23268/******************* End of the no-op lock implementation *********************
23269******************************************************************************/
23270
23271/******************************************************************************
23272************************* Begin dot-file Locking ******************************
23273**
23274** The dotfile locking implementation uses the existance of separate lock
23275** files in order to control access to the database.  This works on just
23276** about every filesystem imaginable.  But there are serious downsides:
23277**
23278**    (1)  There is zero concurrency.  A single reader blocks all other
23279**         connections from reading or writing the database.
23280**
23281**    (2)  An application crash or power loss can leave stale lock files
23282**         sitting around that need to be cleared manually.
23283**
23284** Nevertheless, a dotlock is an appropriate locking mode for use if no
23285** other locking strategy is available.
23286**
23287** Dotfile locking works by creating a file in the same directory as the
23288** database and with the same name but with a ".lock" extension added.
23289** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
23290** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
23291*/
23292
23293/*
23294** The file suffix added to the data base filename in order to create the
23295** lock file.
23296*/
23297#define DOTLOCK_SUFFIX ".lock"
23298
23299/*
23300** This routine checks if there is a RESERVED lock held on the specified
23301** file by this or any other process. If such a lock is held, set *pResOut
23302** to a non-zero value otherwise *pResOut is set to zero.  The return value
23303** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23304**
23305** In dotfile locking, either a lock exists or it does not.  So in this
23306** variation of CheckReservedLock(), *pResOut is set to true if any lock
23307** is held on the file and false if the file is unlocked.
23308*/
23309static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
23310  int rc = SQLITE_OK;
23311  int reserved = 0;
23312  unixFile *pFile = (unixFile*)id;
23313
23314  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23315
23316  assert( pFile );
23317
23318  /* Check if a thread in this process holds such a lock */
23319  if( pFile->locktype>SHARED_LOCK ){
23320    /* Either this connection or some other connection in the same process
23321    ** holds a lock on the file.  No need to check further. */
23322    reserved = 1;
23323  }else{
23324    /* The lock is held if and only if the lockfile exists */
23325    const char *zLockFile = (const char*)pFile->lockingContext;
23326    reserved = access(zLockFile, 0)==0;
23327  }
23328  OSTRACE4("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved);
23329  *pResOut = reserved;
23330  return rc;
23331}
23332
23333/*
23334** Lock the file with the lock specified by parameter locktype - one
23335** of the following:
23336**
23337**     (1) SHARED_LOCK
23338**     (2) RESERVED_LOCK
23339**     (3) PENDING_LOCK
23340**     (4) EXCLUSIVE_LOCK
23341**
23342** Sometimes when requesting one lock state, additional lock states
23343** are inserted in between.  The locking might fail on one of the later
23344** transitions leaving the lock state different from what it started but
23345** still short of its goal.  The following chart shows the allowed
23346** transitions and the inserted intermediate states:
23347**
23348**    UNLOCKED -> SHARED
23349**    SHARED -> RESERVED
23350**    SHARED -> (PENDING) -> EXCLUSIVE
23351**    RESERVED -> (PENDING) -> EXCLUSIVE
23352**    PENDING -> EXCLUSIVE
23353**
23354** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23355** routine to lower a locking level.
23356**
23357** With dotfile locking, we really only support state (4): EXCLUSIVE.
23358** But we track the other locking levels internally.
23359*/
23360static int dotlockLock(sqlite3_file *id, int locktype) {
23361  unixFile *pFile = (unixFile*)id;
23362  int fd;
23363  char *zLockFile = (char *)pFile->lockingContext;
23364  int rc = SQLITE_OK;
23365
23366
23367  /* If we have any lock, then the lock file already exists.  All we have
23368  ** to do is adjust our internal record of the lock level.
23369  */
23370  if( pFile->locktype > NO_LOCK ){
23371    pFile->locktype = locktype;
23372#if !OS_VXWORKS
23373    /* Always update the timestamp on the old file */
23374    utimes(zLockFile, NULL);
23375#endif
23376    return SQLITE_OK;
23377  }
23378
23379  /* grab an exclusive lock */
23380  fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
23381  if( fd<0 ){
23382    /* failed to open/create the file, someone else may have stolen the lock */
23383    int tErrno = errno;
23384    if( EEXIST == tErrno ){
23385      rc = SQLITE_BUSY;
23386    } else {
23387      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23388      if( IS_LOCK_ERROR(rc) ){
23389        pFile->lastErrno = tErrno;
23390      }
23391    }
23392    return rc;
23393  }
23394  if( close(fd) ){
23395    pFile->lastErrno = errno;
23396    rc = SQLITE_IOERR_CLOSE;
23397  }
23398
23399  /* got it, set the type and return ok */
23400  pFile->locktype = locktype;
23401  return rc;
23402}
23403
23404/*
23405** Lower the locking level on file descriptor pFile to locktype.  locktype
23406** must be either NO_LOCK or SHARED_LOCK.
23407**
23408** If the locking level of the file descriptor is already at or below
23409** the requested locking level, this routine is a no-op.
23410**
23411** When the locking level reaches NO_LOCK, delete the lock file.
23412*/
23413static int dotlockUnlock(sqlite3_file *id, int locktype) {
23414  unixFile *pFile = (unixFile*)id;
23415  char *zLockFile = (char *)pFile->lockingContext;
23416
23417  assert( pFile );
23418  OSTRACE5("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, locktype,
23419	   pFile->locktype, getpid());
23420  assert( locktype<=SHARED_LOCK );
23421
23422  /* no-op if possible */
23423  if( pFile->locktype==locktype ){
23424    return SQLITE_OK;
23425  }
23426
23427  /* To downgrade to shared, simply update our internal notion of the
23428  ** lock state.  No need to mess with the file on disk.
23429  */
23430  if( locktype==SHARED_LOCK ){
23431    pFile->locktype = SHARED_LOCK;
23432    return SQLITE_OK;
23433  }
23434
23435  /* To fully unlock the database, delete the lock file */
23436  assert( locktype==NO_LOCK );
23437  if( unlink(zLockFile) ){
23438    int rc = 0;
23439    int tErrno = errno;
23440    if( ENOENT != tErrno ){
23441      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23442    }
23443    if( IS_LOCK_ERROR(rc) ){
23444      pFile->lastErrno = tErrno;
23445    }
23446    return rc;
23447  }
23448  pFile->locktype = NO_LOCK;
23449  return SQLITE_OK;
23450}
23451
23452/*
23453** Close a file.  Make sure the lock has been released before closing.
23454*/
23455static int dotlockClose(sqlite3_file *id) {
23456  int rc;
23457  if( id ){
23458    unixFile *pFile = (unixFile*)id;
23459    dotlockUnlock(id, NO_LOCK);
23460    sqlite3_free(pFile->lockingContext);
23461  }
23462  rc = closeUnixFile(id);
23463  return rc;
23464}
23465/****************** End of the dot-file lock implementation *******************
23466******************************************************************************/
23467
23468/******************************************************************************
23469************************** Begin flock Locking ********************************
23470**
23471** Use the flock() system call to do file locking.
23472**
23473** flock() locking is like dot-file locking in that the various
23474** fine-grain locking levels supported by SQLite are collapsed into
23475** a single exclusive lock.  In other words, SHARED, RESERVED, and
23476** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
23477** still works when you do this, but concurrency is reduced since
23478** only a single process can be reading the database at a time.
23479**
23480** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
23481** compiling for VXWORKS.
23482*/
23483#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
23484
23485/*
23486** This routine checks if there is a RESERVED lock held on the specified
23487** file by this or any other process. If such a lock is held, set *pResOut
23488** to a non-zero value otherwise *pResOut is set to zero.  The return value
23489** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23490*/
23491static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
23492  int rc = SQLITE_OK;
23493  int reserved = 0;
23494  unixFile *pFile = (unixFile*)id;
23495
23496  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23497
23498  assert( pFile );
23499
23500  /* Check if a thread in this process holds such a lock */
23501  if( pFile->locktype>SHARED_LOCK ){
23502    reserved = 1;
23503  }
23504
23505  /* Otherwise see if some other process holds it. */
23506  if( !reserved ){
23507    /* attempt to get the lock */
23508    int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
23509    if( !lrc ){
23510      /* got the lock, unlock it */
23511      lrc = flock(pFile->h, LOCK_UN);
23512      if ( lrc ) {
23513        int tErrno = errno;
23514        /* unlock failed with an error */
23515        lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23516        if( IS_LOCK_ERROR(lrc) ){
23517          pFile->lastErrno = tErrno;
23518          rc = lrc;
23519        }
23520      }
23521    } else {
23522      int tErrno = errno;
23523      reserved = 1;
23524      /* someone else might have it reserved */
23525      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23526      if( IS_LOCK_ERROR(lrc) ){
23527        pFile->lastErrno = tErrno;
23528        rc = lrc;
23529      }
23530    }
23531  }
23532  OSTRACE4("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved);
23533
23534#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
23535  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
23536    rc = SQLITE_OK;
23537    reserved=1;
23538  }
23539#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
23540  *pResOut = reserved;
23541  return rc;
23542}
23543
23544/*
23545** Lock the file with the lock specified by parameter locktype - one
23546** of the following:
23547**
23548**     (1) SHARED_LOCK
23549**     (2) RESERVED_LOCK
23550**     (3) PENDING_LOCK
23551**     (4) EXCLUSIVE_LOCK
23552**
23553** Sometimes when requesting one lock state, additional lock states
23554** are inserted in between.  The locking might fail on one of the later
23555** transitions leaving the lock state different from what it started but
23556** still short of its goal.  The following chart shows the allowed
23557** transitions and the inserted intermediate states:
23558**
23559**    UNLOCKED -> SHARED
23560**    SHARED -> RESERVED
23561**    SHARED -> (PENDING) -> EXCLUSIVE
23562**    RESERVED -> (PENDING) -> EXCLUSIVE
23563**    PENDING -> EXCLUSIVE
23564**
23565** flock() only really support EXCLUSIVE locks.  We track intermediate
23566** lock states in the sqlite3_file structure, but all locks SHARED or
23567** above are really EXCLUSIVE locks and exclude all other processes from
23568** access the file.
23569**
23570** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23571** routine to lower a locking level.
23572*/
23573static int flockLock(sqlite3_file *id, int locktype) {
23574  int rc = SQLITE_OK;
23575  unixFile *pFile = (unixFile*)id;
23576
23577  assert( pFile );
23578
23579  /* if we already have a lock, it is exclusive.
23580  ** Just adjust level and punt on outta here. */
23581  if (pFile->locktype > NO_LOCK) {
23582    pFile->locktype = locktype;
23583    return SQLITE_OK;
23584  }
23585
23586  /* grab an exclusive lock */
23587
23588  if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
23589    int tErrno = errno;
23590    /* didn't get, must be busy */
23591    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23592    if( IS_LOCK_ERROR(rc) ){
23593      pFile->lastErrno = tErrno;
23594    }
23595  } else {
23596    /* got it, set the type and return ok */
23597    pFile->locktype = locktype;
23598  }
23599  OSTRACE4("LOCK    %d %s %s (flock)\n", pFile->h, locktypeName(locktype),
23600           rc==SQLITE_OK ? "ok" : "failed");
23601#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
23602  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
23603    rc = SQLITE_BUSY;
23604  }
23605#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
23606  return rc;
23607}
23608
23609
23610/*
23611** Lower the locking level on file descriptor pFile to locktype.  locktype
23612** must be either NO_LOCK or SHARED_LOCK.
23613**
23614** If the locking level of the file descriptor is already at or below
23615** the requested locking level, this routine is a no-op.
23616*/
23617static int flockUnlock(sqlite3_file *id, int locktype) {
23618  unixFile *pFile = (unixFile*)id;
23619
23620  assert( pFile );
23621  OSTRACE5("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, locktype,
23622           pFile->locktype, getpid());
23623  assert( locktype<=SHARED_LOCK );
23624
23625  /* no-op if possible */
23626  if( pFile->locktype==locktype ){
23627    return SQLITE_OK;
23628  }
23629
23630  /* shared can just be set because we always have an exclusive */
23631  if (locktype==SHARED_LOCK) {
23632    pFile->locktype = locktype;
23633    return SQLITE_OK;
23634  }
23635
23636  /* no, really, unlock. */
23637  int rc = flock(pFile->h, LOCK_UN);
23638  if (rc) {
23639    int r, tErrno = errno;
23640    r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23641    if( IS_LOCK_ERROR(r) ){
23642      pFile->lastErrno = tErrno;
23643    }
23644#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
23645    if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
23646      r = SQLITE_BUSY;
23647    }
23648#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
23649
23650    return r;
23651  } else {
23652    pFile->locktype = NO_LOCK;
23653    return SQLITE_OK;
23654  }
23655}
23656
23657/*
23658** Close a file.
23659*/
23660static int flockClose(sqlite3_file *id) {
23661  if( id ){
23662    flockUnlock(id, NO_LOCK);
23663  }
23664  return closeUnixFile(id);
23665}
23666
23667#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
23668
23669/******************* End of the flock lock implementation *********************
23670******************************************************************************/
23671
23672/******************************************************************************
23673************************ Begin Named Semaphore Locking ************************
23674**
23675** Named semaphore locking is only supported on VxWorks.
23676**
23677** Semaphore locking is like dot-lock and flock in that it really only
23678** supports EXCLUSIVE locking.  Only a single process can read or write
23679** the database file at a time.  This reduces potential concurrency, but
23680** makes the lock implementation much easier.
23681*/
23682#if OS_VXWORKS
23683
23684/*
23685** This routine checks if there is a RESERVED lock held on the specified
23686** file by this or any other process. If such a lock is held, set *pResOut
23687** to a non-zero value otherwise *pResOut is set to zero.  The return value
23688** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23689*/
23690static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
23691  int rc = SQLITE_OK;
23692  int reserved = 0;
23693  unixFile *pFile = (unixFile*)id;
23694
23695  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23696
23697  assert( pFile );
23698
23699  /* Check if a thread in this process holds such a lock */
23700  if( pFile->locktype>SHARED_LOCK ){
23701    reserved = 1;
23702  }
23703
23704  /* Otherwise see if some other process holds it. */
23705  if( !reserved ){
23706    sem_t *pSem = pFile->pOpen->pSem;
23707    struct stat statBuf;
23708
23709    if( sem_trywait(pSem)==-1 ){
23710      int tErrno = errno;
23711      if( EAGAIN != tErrno ){
23712        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
23713        pFile->lastErrno = tErrno;
23714      } else {
23715        /* someone else has the lock when we are in NO_LOCK */
23716        reserved = (pFile->locktype < SHARED_LOCK);
23717      }
23718    }else{
23719      /* we could have it if we want it */
23720      sem_post(pSem);
23721    }
23722  }
23723  OSTRACE4("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved);
23724
23725  *pResOut = reserved;
23726  return rc;
23727}
23728
23729/*
23730** Lock the file with the lock specified by parameter locktype - one
23731** of the following:
23732**
23733**     (1) SHARED_LOCK
23734**     (2) RESERVED_LOCK
23735**     (3) PENDING_LOCK
23736**     (4) EXCLUSIVE_LOCK
23737**
23738** Sometimes when requesting one lock state, additional lock states
23739** are inserted in between.  The locking might fail on one of the later
23740** transitions leaving the lock state different from what it started but
23741** still short of its goal.  The following chart shows the allowed
23742** transitions and the inserted intermediate states:
23743**
23744**    UNLOCKED -> SHARED
23745**    SHARED -> RESERVED
23746**    SHARED -> (PENDING) -> EXCLUSIVE
23747**    RESERVED -> (PENDING) -> EXCLUSIVE
23748**    PENDING -> EXCLUSIVE
23749**
23750** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
23751** lock states in the sqlite3_file structure, but all locks SHARED or
23752** above are really EXCLUSIVE locks and exclude all other processes from
23753** access the file.
23754**
23755** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23756** routine to lower a locking level.
23757*/
23758static int semLock(sqlite3_file *id, int locktype) {
23759  unixFile *pFile = (unixFile*)id;
23760  int fd;
23761  sem_t *pSem = pFile->pOpen->pSem;
23762  int rc = SQLITE_OK;
23763
23764  /* if we already have a lock, it is exclusive.
23765  ** Just adjust level and punt on outta here. */
23766  if (pFile->locktype > NO_LOCK) {
23767    pFile->locktype = locktype;
23768    rc = SQLITE_OK;
23769    goto sem_end_lock;
23770  }
23771
23772  /* lock semaphore now but bail out when already locked. */
23773  if( sem_trywait(pSem)==-1 ){
23774    rc = SQLITE_BUSY;
23775    goto sem_end_lock;
23776  }
23777
23778  /* got it, set the type and return ok */
23779  pFile->locktype = locktype;
23780
23781 sem_end_lock:
23782  return rc;
23783}
23784
23785/*
23786** Lower the locking level on file descriptor pFile to locktype.  locktype
23787** must be either NO_LOCK or SHARED_LOCK.
23788**
23789** If the locking level of the file descriptor is already at or below
23790** the requested locking level, this routine is a no-op.
23791*/
23792static int semUnlock(sqlite3_file *id, int locktype) {
23793  unixFile *pFile = (unixFile*)id;
23794  sem_t *pSem = pFile->pOpen->pSem;
23795
23796  assert( pFile );
23797  assert( pSem );
23798  OSTRACE5("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, locktype,
23799	   pFile->locktype, getpid());
23800  assert( locktype<=SHARED_LOCK );
23801
23802  /* no-op if possible */
23803  if( pFile->locktype==locktype ){
23804    return SQLITE_OK;
23805  }
23806
23807  /* shared can just be set because we always have an exclusive */
23808  if (locktype==SHARED_LOCK) {
23809    pFile->locktype = locktype;
23810    return SQLITE_OK;
23811  }
23812
23813  /* no, really unlock. */
23814  if ( sem_post(pSem)==-1 ) {
23815    int rc, tErrno = errno;
23816    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23817    if( IS_LOCK_ERROR(rc) ){
23818      pFile->lastErrno = tErrno;
23819    }
23820    return rc;
23821  }
23822  pFile->locktype = NO_LOCK;
23823  return SQLITE_OK;
23824}
23825
23826/*
23827 ** Close a file.
23828 */
23829static int semClose(sqlite3_file *id) {
23830  if( id ){
23831    unixFile *pFile = (unixFile*)id;
23832    semUnlock(id, NO_LOCK);
23833    assert( pFile );
23834    unixEnterMutex();
23835    releaseLockInfo(pFile->pLock);
23836    releaseOpenCnt(pFile->pOpen);
23837    unixLeaveMutex();
23838    closeUnixFile(id);
23839  }
23840  return SQLITE_OK;
23841}
23842
23843#endif /* OS_VXWORKS */
23844/*
23845** Named semaphore locking is only available on VxWorks.
23846**
23847*************** End of the named semaphore lock implementation ****************
23848******************************************************************************/
23849
23850
23851/******************************************************************************
23852*************************** Begin AFP Locking *********************************
23853**
23854** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
23855** on Apple Macintosh computers - both OS9 and OSX.
23856**
23857** Third-party implementations of AFP are available.  But this code here
23858** only works on OSX.
23859*/
23860
23861#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
23862/*
23863** The afpLockingContext structure contains all afp lock specific state
23864*/
23865typedef struct afpLockingContext afpLockingContext;
23866struct afpLockingContext {
23867  unsigned long long sharedByte;
23868  const char *dbPath;             /* Name of the open file */
23869};
23870
23871struct ByteRangeLockPB2
23872{
23873  unsigned long long offset;        /* offset to first byte to lock */
23874  unsigned long long length;        /* nbr of bytes to lock */
23875  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
23876  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
23877  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
23878  int fd;                           /* file desc to assoc this lock with */
23879};
23880
23881#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
23882
23883/*
23884** This is a utility for setting or clearing a bit-range lock on an
23885** AFP filesystem.
23886**
23887** Return SQLITE_OK on success, SQLITE_BUSY on failure.
23888*/
23889static int afpSetLock(
23890  const char *path,              /* Name of the file to be locked or unlocked */
23891  unixFile *pFile,               /* Open file descriptor on path */
23892  unsigned long long offset,     /* First byte to be locked */
23893  unsigned long long length,     /* Number of bytes to lock */
23894  int setLockFlag                /* True to set lock.  False to clear lock */
23895){
23896  struct ByteRangeLockPB2 pb;
23897  int err;
23898
23899  pb.unLockFlag = setLockFlag ? 0 : 1;
23900  pb.startEndFlag = 0;
23901  pb.offset = offset;
23902  pb.length = length;
23903  pb.fd = pFile->h;
23904
23905  OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
23906    (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
23907    offset, length);
23908  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
23909  if ( err==-1 ) {
23910    int rc;
23911    int tErrno = errno;
23912    OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
23913             path, tErrno, strerror(tErrno));
23914#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
23915    rc = SQLITE_BUSY;
23916#else
23917    rc = sqliteErrorFromPosixError(tErrno,
23918                    setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
23919#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
23920    if( IS_LOCK_ERROR(rc) ){
23921      pFile->lastErrno = tErrno;
23922    }
23923    return rc;
23924  } else {
23925    return SQLITE_OK;
23926  }
23927}
23928
23929/*
23930** This routine checks if there is a RESERVED lock held on the specified
23931** file by this or any other process. If such a lock is held, set *pResOut
23932** to a non-zero value otherwise *pResOut is set to zero.  The return value
23933** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23934*/
23935static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
23936  int rc = SQLITE_OK;
23937  int reserved = 0;
23938  unixFile *pFile = (unixFile*)id;
23939
23940  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23941
23942  assert( pFile );
23943  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
23944
23945  /* Check if a thread in this process holds such a lock */
23946  if( pFile->locktype>SHARED_LOCK ){
23947    reserved = 1;
23948  }
23949
23950  /* Otherwise see if some other process holds it.
23951   */
23952  if( !reserved ){
23953    /* lock the RESERVED byte */
23954    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
23955    if( SQLITE_OK==lrc ){
23956      /* if we succeeded in taking the reserved lock, unlock it to restore
23957      ** the original state */
23958      lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
23959    } else {
23960      /* if we failed to get the lock then someone else must have it */
23961      reserved = 1;
23962    }
23963    if( IS_LOCK_ERROR(lrc) ){
23964      rc=lrc;
23965    }
23966  }
23967
23968  OSTRACE4("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved);
23969
23970  *pResOut = reserved;
23971  return rc;
23972}
23973
23974/*
23975** Lock the file with the lock specified by parameter locktype - one
23976** of the following:
23977**
23978**     (1) SHARED_LOCK
23979**     (2) RESERVED_LOCK
23980**     (3) PENDING_LOCK
23981**     (4) EXCLUSIVE_LOCK
23982**
23983** Sometimes when requesting one lock state, additional lock states
23984** are inserted in between.  The locking might fail on one of the later
23985** transitions leaving the lock state different from what it started but
23986** still short of its goal.  The following chart shows the allowed
23987** transitions and the inserted intermediate states:
23988**
23989**    UNLOCKED -> SHARED
23990**    SHARED -> RESERVED
23991**    SHARED -> (PENDING) -> EXCLUSIVE
23992**    RESERVED -> (PENDING) -> EXCLUSIVE
23993**    PENDING -> EXCLUSIVE
23994**
23995** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23996** routine to lower a locking level.
23997*/
23998static int afpLock(sqlite3_file *id, int locktype){
23999  int rc = SQLITE_OK;
24000  unixFile *pFile = (unixFile*)id;
24001  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
24002
24003  assert( pFile );
24004  OSTRACE5("LOCK    %d %s was %s pid=%d (afp)\n", pFile->h,
24005         locktypeName(locktype), locktypeName(pFile->locktype), getpid());
24006
24007  /* If there is already a lock of this type or more restrictive on the
24008  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
24009  ** unixEnterMutex() hasn't been called yet.
24010  */
24011  if( pFile->locktype>=locktype ){
24012    OSTRACE3("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
24013           locktypeName(locktype));
24014    return SQLITE_OK;
24015  }
24016
24017  /* Make sure the locking sequence is correct
24018  */
24019  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
24020  assert( locktype!=PENDING_LOCK );
24021  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
24022
24023  /* This mutex is needed because pFile->pLock is shared across threads
24024  */
24025  unixEnterMutex();
24026
24027  /* Make sure the current thread owns the pFile.
24028  */
24029  rc = transferOwnership(pFile);
24030  if( rc!=SQLITE_OK ){
24031    unixLeaveMutex();
24032    return rc;
24033  }
24034
24035  /* A PENDING lock is needed before acquiring a SHARED lock and before
24036  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24037  ** be released.
24038  */
24039  if( locktype==SHARED_LOCK
24040      || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
24041  ){
24042    int failed;
24043    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
24044    if (failed) {
24045      rc = failed;
24046      goto afp_end_lock;
24047    }
24048  }
24049
24050  /* If control gets to this point, then actually go ahead and make
24051  ** operating system calls for the specified lock.
24052  */
24053  if( locktype==SHARED_LOCK ){
24054    int lk, lrc1, lrc2;
24055    int lrc1Errno = 0;
24056
24057    /* Now get the read-lock SHARED_LOCK */
24058    /* note that the quality of the randomness doesn't matter that much */
24059    lk = random();
24060    context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
24061    lrc1 = afpSetLock(context->dbPath, pFile,
24062          SHARED_FIRST+context->sharedByte, 1, 1);
24063    if( IS_LOCK_ERROR(lrc1) ){
24064      lrc1Errno = pFile->lastErrno;
24065    }
24066    /* Drop the temporary PENDING lock */
24067    lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
24068
24069    if( IS_LOCK_ERROR(lrc1) ) {
24070      pFile->lastErrno = lrc1Errno;
24071      rc = lrc1;
24072      goto afp_end_lock;
24073    } else if( IS_LOCK_ERROR(lrc2) ){
24074      rc = lrc2;
24075      goto afp_end_lock;
24076    } else if( lrc1 != SQLITE_OK ) {
24077      rc = lrc1;
24078    } else {
24079      pFile->locktype = SHARED_LOCK;
24080      pFile->pOpen->nLock++;
24081    }
24082  }else{
24083    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
24084    ** assumed that there is a SHARED or greater lock on the file
24085    ** already.
24086    */
24087    int failed = 0;
24088    assert( 0!=pFile->locktype );
24089    if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
24090        /* Acquire a RESERVED lock */
24091        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
24092    }
24093    if (!failed && locktype == EXCLUSIVE_LOCK) {
24094      /* Acquire an EXCLUSIVE lock */
24095
24096      /* Remove the shared lock before trying the range.  we'll need to
24097      ** reestablish the shared lock if we can't get the  afpUnlock
24098      */
24099      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
24100                         context->sharedByte, 1, 0)) ){
24101        int failed2 = SQLITE_OK;
24102        /* now attemmpt to get the exclusive lock range */
24103        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
24104                               SHARED_SIZE, 1);
24105        if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
24106                       SHARED_FIRST + context->sharedByte, 1, 1)) ){
24107          /* Can't reestablish the shared lock.  Sqlite can't deal, this is
24108          ** a critical I/O error
24109          */
24110          rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
24111               SQLITE_IOERR_LOCK;
24112          goto afp_end_lock;
24113        }
24114      }else{
24115        rc = failed;
24116      }
24117    }
24118    if( failed ){
24119      rc = failed;
24120    }
24121  }
24122
24123  if( rc==SQLITE_OK ){
24124    pFile->locktype = locktype;
24125  }else if( locktype==EXCLUSIVE_LOCK ){
24126    pFile->locktype = PENDING_LOCK;
24127  }
24128
24129afp_end_lock:
24130  unixLeaveMutex();
24131  OSTRACE4("LOCK    %d %s %s (afp)\n", pFile->h, locktypeName(locktype),
24132         rc==SQLITE_OK ? "ok" : "failed");
24133  return rc;
24134}
24135
24136/*
24137** Lower the locking level on file descriptor pFile to locktype.  locktype
24138** must be either NO_LOCK or SHARED_LOCK.
24139**
24140** If the locking level of the file descriptor is already at or below
24141** the requested locking level, this routine is a no-op.
24142*/
24143static int afpUnlock(sqlite3_file *id, int locktype) {
24144  int rc = SQLITE_OK;
24145  unixFile *pFile = (unixFile*)id;
24146  afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext;
24147
24148  assert( pFile );
24149  OSTRACE5("UNLOCK  %d %d was %d pid=%d (afp)\n", pFile->h, locktype,
24150         pFile->locktype, getpid());
24151
24152  assert( locktype<=SHARED_LOCK );
24153  if( pFile->locktype<=locktype ){
24154    return SQLITE_OK;
24155  }
24156  if( CHECK_THREADID(pFile) ){
24157    return SQLITE_MISUSE_BKPT;
24158  }
24159  unixEnterMutex();
24160  if( pFile->locktype>SHARED_LOCK ){
24161
24162    if( pFile->locktype==EXCLUSIVE_LOCK ){
24163      rc = afpSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
24164      if( rc==SQLITE_OK && locktype==SHARED_LOCK ){
24165        /* only re-establish the shared lock if necessary */
24166        int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
24167        rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1);
24168      }
24169    }
24170    if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
24171      rc = afpSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0);
24172    }
24173    if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){
24174      rc = afpSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0);
24175    }
24176  }else if( locktype==NO_LOCK ){
24177    /* clear the shared lock */
24178    int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
24179    rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0);
24180  }
24181
24182  if( rc==SQLITE_OK ){
24183    if( locktype==NO_LOCK ){
24184      struct unixOpenCnt *pOpen = pFile->pOpen;
24185      pOpen->nLock--;
24186      assert( pOpen->nLock>=0 );
24187      if( pOpen->nLock==0 ){
24188        rc = closePendingFds(pFile);
24189      }
24190    }
24191  }
24192  unixLeaveMutex();
24193  if( rc==SQLITE_OK ){
24194    pFile->locktype = locktype;
24195  }
24196  return rc;
24197}
24198
24199/*
24200** Close a file & cleanup AFP specific locking context
24201*/
24202static int afpClose(sqlite3_file *id) {
24203  if( id ){
24204    unixFile *pFile = (unixFile*)id;
24205    afpUnlock(id, NO_LOCK);
24206    unixEnterMutex();
24207    if( pFile->pOpen && pFile->pOpen->nLock ){
24208      /* If there are outstanding locks, do not actually close the file just
24209      ** yet because that would clear those locks.  Instead, add the file
24210      ** descriptor to pOpen->aPending.  It will be automatically closed when
24211      ** the last lock is cleared.
24212      */
24213      setPendingFd(pFile);
24214    }
24215    releaseOpenCnt(pFile->pOpen);
24216    sqlite3_free(pFile->lockingContext);
24217    closeUnixFile(id);
24218    unixLeaveMutex();
24219  }
24220  return SQLITE_OK;
24221}
24222
24223#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24224/*
24225** The code above is the AFP lock implementation.  The code is specific
24226** to MacOSX and does not work on other unix platforms.  No alternative
24227** is available.  If you don't compile for a mac, then the "unix-afp"
24228** VFS is not available.
24229**
24230********************* End of the AFP lock implementation **********************
24231******************************************************************************/
24232
24233
24234/******************************************************************************
24235**************** Non-locking sqlite3_file methods *****************************
24236**
24237** The next division contains implementations for all methods of the
24238** sqlite3_file object other than the locking methods.  The locking
24239** methods were defined in divisions above (one locking method per
24240** division).  Those methods that are common to all locking modes
24241** are gather together into this division.
24242*/
24243
24244/*
24245** Seek to the offset passed as the second argument, then read cnt
24246** bytes into pBuf. Return the number of bytes actually read.
24247**
24248** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
24249** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
24250** one system to another.  Since SQLite does not define USE_PREAD
24251** any any form by default, we will not attempt to define _XOPEN_SOURCE.
24252** See tickets #2741 and #2681.
24253**
24254** To avoid stomping the errno value on a failed read the lastErrno value
24255** is set before returning.
24256*/
24257static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
24258  int got;
24259  i64 newOffset;
24260  TIMER_START;
24261#if defined(USE_PREAD)
24262  got = pread(id->h, pBuf, cnt, offset);
24263  SimulateIOError( got = -1 );
24264#elif defined(USE_PREAD64)
24265  got = pread64(id->h, pBuf, cnt, offset);
24266  SimulateIOError( got = -1 );
24267#else
24268  newOffset = lseek(id->h, offset, SEEK_SET);
24269  SimulateIOError( newOffset-- );
24270  if( newOffset!=offset ){
24271    if( newOffset == -1 ){
24272      ((unixFile*)id)->lastErrno = errno;
24273    }else{
24274      ((unixFile*)id)->lastErrno = 0;
24275    }
24276    return -1;
24277  }
24278  got = read(id->h, pBuf, cnt);
24279#endif
24280  TIMER_END;
24281  if( got<0 ){
24282    ((unixFile*)id)->lastErrno = errno;
24283  }
24284  OSTRACE5("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
24285  return got;
24286}
24287
24288/*
24289** Read data from a file into a buffer.  Return SQLITE_OK if all
24290** bytes were read successfully and SQLITE_IOERR if anything goes
24291** wrong.
24292*/
24293static int unixRead(
24294  sqlite3_file *id,
24295  void *pBuf,
24296  int amt,
24297  sqlite3_int64 offset
24298){
24299  unixFile *pFile = (unixFile *)id;
24300  int got;
24301  assert( id );
24302
24303  /* If this is a database file (not a journal, master-journal or temp
24304  ** file), the bytes in the locking range should never be read or written. */
24305  assert( pFile->pUnused==0
24306       || offset>=PENDING_BYTE+512
24307       || offset+amt<=PENDING_BYTE
24308  );
24309
24310  got = seekAndRead(pFile, offset, pBuf, amt);
24311  if( got==amt ){
24312    return SQLITE_OK;
24313  }else if( got<0 ){
24314    /* lastErrno set by seekAndRead */
24315    return SQLITE_IOERR_READ;
24316  }else{
24317    pFile->lastErrno = 0; /* not a system error */
24318    /* Unread parts of the buffer must be zero-filled */
24319    memset(&((char*)pBuf)[got], 0, amt-got);
24320    return SQLITE_IOERR_SHORT_READ;
24321  }
24322}
24323
24324/*
24325** Seek to the offset in id->offset then read cnt bytes into pBuf.
24326** Return the number of bytes actually read.  Update the offset.
24327**
24328** To avoid stomping the errno value on a failed write the lastErrno value
24329** is set before returning.
24330*/
24331static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
24332  int got;
24333  i64 newOffset;
24334  TIMER_START;
24335#if defined(USE_PREAD)
24336  got = pwrite(id->h, pBuf, cnt, offset);
24337#elif defined(USE_PREAD64)
24338  got = pwrite64(id->h, pBuf, cnt, offset);
24339#else
24340  newOffset = lseek(id->h, offset, SEEK_SET);
24341  if( newOffset!=offset ){
24342    if( newOffset == -1 ){
24343      ((unixFile*)id)->lastErrno = errno;
24344    }else{
24345      ((unixFile*)id)->lastErrno = 0;
24346    }
24347    return -1;
24348  }
24349  got = write(id->h, pBuf, cnt);
24350#endif
24351  TIMER_END;
24352  if( got<0 ){
24353    ((unixFile*)id)->lastErrno = errno;
24354  }
24355
24356  OSTRACE5("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
24357  return got;
24358}
24359
24360
24361/*
24362** Write data from a buffer into a file.  Return SQLITE_OK on success
24363** or some other error code on failure.
24364*/
24365static int unixWrite(
24366  sqlite3_file *id,
24367  const void *pBuf,
24368  int amt,
24369  sqlite3_int64 offset
24370){
24371  unixFile *pFile = (unixFile*)id;
24372  int wrote = 0;
24373  assert( id );
24374  assert( amt>0 );
24375
24376  /* If this is a database file (not a journal, master-journal or temp
24377  ** file), the bytes in the locking range should never be read or written. */
24378  assert( pFile->pUnused==0
24379       || offset>=PENDING_BYTE+512
24380       || offset+amt<=PENDING_BYTE
24381  );
24382
24383#ifndef NDEBUG
24384  /* If we are doing a normal write to a database file (as opposed to
24385  ** doing a hot-journal rollback or a write to some file other than a
24386  ** normal database file) then record the fact that the database
24387  ** has changed.  If the transaction counter is modified, record that
24388  ** fact too.
24389  */
24390  if( pFile->inNormalWrite ){
24391    pFile->dbUpdate = 1;  /* The database has been modified */
24392    if( offset<=24 && offset+amt>=27 ){
24393      int rc;
24394      char oldCntr[4];
24395      SimulateIOErrorBenign(1);
24396      rc = seekAndRead(pFile, 24, oldCntr, 4);
24397      SimulateIOErrorBenign(0);
24398      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
24399        pFile->transCntrChng = 1;  /* The transaction counter has changed */
24400      }
24401    }
24402  }
24403#endif
24404
24405  while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
24406    amt -= wrote;
24407    offset += wrote;
24408    pBuf = &((char*)pBuf)[wrote];
24409  }
24410  SimulateIOError(( wrote=(-1), amt=1 ));
24411  SimulateDiskfullError(( wrote=0, amt=1 ));
24412  if( amt>0 ){
24413    if( wrote<0 ){
24414      /* lastErrno set by seekAndWrite */
24415      return SQLITE_IOERR_WRITE;
24416    }else{
24417      pFile->lastErrno = 0; /* not a system error */
24418      return SQLITE_FULL;
24419    }
24420  }
24421  return SQLITE_OK;
24422}
24423
24424#ifdef SQLITE_TEST
24425/*
24426** Count the number of fullsyncs and normal syncs.  This is used to test
24427** that syncs and fullsyncs are occurring at the right times.
24428*/
24429SQLITE_API int sqlite3_sync_count = 0;
24430SQLITE_API int sqlite3_fullsync_count = 0;
24431#endif
24432
24433/*
24434** We do not trust systems to provide a working fdatasync().  Some do.
24435** Others do no.  To be safe, we will stick with the (slower) fsync().
24436** If you know that your system does support fdatasync() correctly,
24437** then simply compile with -Dfdatasync=fdatasync
24438*/
24439#if !defined(fdatasync) && !defined(__linux__)
24440# define fdatasync fsync
24441#endif
24442
24443/*
24444** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
24445** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
24446** only available on Mac OS X.  But that could change.
24447*/
24448#ifdef F_FULLFSYNC
24449# define HAVE_FULLFSYNC 1
24450#else
24451# define HAVE_FULLFSYNC 0
24452#endif
24453
24454
24455/*
24456** The fsync() system call does not work as advertised on many
24457** unix systems.  The following procedure is an attempt to make
24458** it work better.
24459**
24460** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
24461** for testing when we want to run through the test suite quickly.
24462** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
24463** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
24464** or power failure will likely corrupt the database file.
24465**
24466** SQLite sets the dataOnly flag if the size of the file is unchanged.
24467** The idea behind dataOnly is that it should only write the file content
24468** to disk, not the inode.  We only set dataOnly if the file size is
24469** unchanged since the file size is part of the inode.  However,
24470** Ted Ts'o tells us that fdatasync() will also write the inode if the
24471** file size has changed.  The only real difference between fdatasync()
24472** and fsync(), Ted tells us, is that fdatasync() will not flush the
24473** inode if the mtime or owner or other inode attributes have changed.
24474** We only care about the file size, not the other file attributes, so
24475** as far as SQLite is concerned, an fdatasync() is always adequate.
24476** So, we always use fdatasync() if it is available, regardless of
24477** the value of the dataOnly flag.
24478*/
24479static int full_fsync(int fd, int fullSync, int dataOnly){
24480  int rc;
24481
24482  /* The following "ifdef/elif/else/" block has the same structure as
24483  ** the one below. It is replicated here solely to avoid cluttering
24484  ** up the real code with the UNUSED_PARAMETER() macros.
24485  */
24486#ifdef SQLITE_NO_SYNC
24487  UNUSED_PARAMETER(fd);
24488  UNUSED_PARAMETER(fullSync);
24489  UNUSED_PARAMETER(dataOnly);
24490#elif HAVE_FULLFSYNC
24491  UNUSED_PARAMETER(dataOnly);
24492#else
24493  UNUSED_PARAMETER(fullSync);
24494  UNUSED_PARAMETER(dataOnly);
24495#endif
24496
24497  /* Record the number of times that we do a normal fsync() and
24498  ** FULLSYNC.  This is used during testing to verify that this procedure
24499  ** gets called with the correct arguments.
24500  */
24501#ifdef SQLITE_TEST
24502  if( fullSync ) sqlite3_fullsync_count++;
24503  sqlite3_sync_count++;
24504#endif
24505
24506  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
24507  ** no-op
24508  */
24509#ifdef SQLITE_NO_SYNC
24510  rc = SQLITE_OK;
24511#elif HAVE_FULLFSYNC
24512  if( fullSync ){
24513    rc = fcntl(fd, F_FULLFSYNC, 0);
24514  }else{
24515    rc = 1;
24516  }
24517  /* If the FULLFSYNC failed, fall back to attempting an fsync().
24518  ** It shouldn't be possible for fullfsync to fail on the local
24519  ** file system (on OSX), so failure indicates that FULLFSYNC
24520  ** isn't supported for this file system. So, attempt an fsync
24521  ** and (for now) ignore the overhead of a superfluous fcntl call.
24522  ** It'd be better to detect fullfsync support once and avoid
24523  ** the fcntl call every time sync is called.
24524  */
24525  if( rc ) rc = fsync(fd);
24526
24527#else
24528  rc = fdatasync(fd);
24529#if OS_VXWORKS
24530  if( rc==-1 && errno==ENOTSUP ){
24531    rc = fsync(fd);
24532  }
24533#endif /* OS_VXWORKS */
24534#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
24535
24536  if( OS_VXWORKS && rc!= -1 ){
24537    rc = 0;
24538  }
24539  return rc;
24540}
24541
24542/*
24543** Make sure all writes to a particular file are committed to disk.
24544**
24545** If dataOnly==0 then both the file itself and its metadata (file
24546** size, access time, etc) are synced.  If dataOnly!=0 then only the
24547** file data is synced.
24548**
24549** Under Unix, also make sure that the directory entry for the file
24550** has been created by fsync-ing the directory that contains the file.
24551** If we do not do this and we encounter a power failure, the directory
24552** entry for the journal might not exist after we reboot.  The next
24553** SQLite to access the file will not know that the journal exists (because
24554** the directory entry for the journal was never created) and the transaction
24555** will not roll back - possibly leading to database corruption.
24556*/
24557static int unixSync(sqlite3_file *id, int flags){
24558  int rc;
24559  unixFile *pFile = (unixFile*)id;
24560
24561  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
24562  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
24563
24564  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
24565  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
24566      || (flags&0x0F)==SQLITE_SYNC_FULL
24567  );
24568
24569  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
24570  ** line is to test that doing so does not cause any problems.
24571  */
24572  SimulateDiskfullError( return SQLITE_FULL );
24573
24574  assert( pFile );
24575  OSTRACE2("SYNC    %-3d\n", pFile->h);
24576  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
24577  SimulateIOError( rc=1 );
24578  if( rc ){
24579    pFile->lastErrno = errno;
24580    return SQLITE_IOERR_FSYNC;
24581  }
24582  if( pFile->dirfd>=0 ){
24583    int err;
24584    OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
24585            HAVE_FULLFSYNC, isFullsync);
24586#ifndef SQLITE_DISABLE_DIRSYNC
24587    /* The directory sync is only attempted if full_fsync is
24588    ** turned off or unavailable.  If a full_fsync occurred above,
24589    ** then the directory sync is superfluous.
24590    */
24591    if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
24592       /*
24593       ** We have received multiple reports of fsync() returning
24594       ** errors when applied to directories on certain file systems.
24595       ** A failed directory sync is not a big deal.  So it seems
24596       ** better to ignore the error.  Ticket #1657
24597       */
24598       /* pFile->lastErrno = errno; */
24599       /* return SQLITE_IOERR; */
24600    }
24601#endif
24602    err = close(pFile->dirfd); /* Only need to sync once, so close the */
24603    if( err==0 ){              /* directory when we are done */
24604      pFile->dirfd = -1;
24605    }else{
24606      pFile->lastErrno = errno;
24607      rc = SQLITE_IOERR_DIR_CLOSE;
24608    }
24609  }
24610  return rc;
24611}
24612
24613/*
24614** Truncate an open file to a specified size
24615*/
24616static int unixTruncate(sqlite3_file *id, i64 nByte){
24617  int rc;
24618  assert( id );
24619  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
24620  rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
24621  if( rc ){
24622    ((unixFile*)id)->lastErrno = errno;
24623    return SQLITE_IOERR_TRUNCATE;
24624  }else{
24625#ifndef NDEBUG
24626    /* If we are doing a normal write to a database file (as opposed to
24627    ** doing a hot-journal rollback or a write to some file other than a
24628    ** normal database file) and we truncate the file to zero length,
24629    ** that effectively updates the change counter.  This might happen
24630    ** when restoring a database using the backup API from a zero-length
24631    ** source.
24632    */
24633    if( ((unixFile*)id)->inNormalWrite && nByte==0 ){
24634      ((unixFile*)id)->transCntrChng = 1;
24635    }
24636#endif
24637
24638    return SQLITE_OK;
24639  }
24640}
24641
24642/*
24643** Determine the current size of a file in bytes
24644*/
24645static int unixFileSize(sqlite3_file *id, i64 *pSize){
24646  int rc;
24647  struct stat buf;
24648  assert( id );
24649  rc = fstat(((unixFile*)id)->h, &buf);
24650  SimulateIOError( rc=1 );
24651  if( rc!=0 ){
24652    ((unixFile*)id)->lastErrno = errno;
24653    return SQLITE_IOERR_FSTAT;
24654  }
24655  *pSize = buf.st_size;
24656
24657  /* When opening a zero-size database, the findLockInfo() procedure
24658  ** writes a single byte into that file in order to work around a bug
24659  ** in the OS-X msdos filesystem.  In order to avoid problems with upper
24660  ** layers, we need to report this file size as zero even though it is
24661  ** really 1.   Ticket #3260.
24662  */
24663  if( *pSize==1 ) *pSize = 0;
24664
24665
24666  return SQLITE_OK;
24667}
24668
24669#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
24670/*
24671** Handler for proxy-locking file-control verbs.  Defined below in the
24672** proxying locking division.
24673*/
24674static int proxyFileControl(sqlite3_file*,int,void*);
24675#endif
24676
24677
24678/*
24679** Information and control of an open file handle.
24680*/
24681static int unixFileControl(sqlite3_file *id, int op, void *pArg){
24682  switch( op ){
24683    case SQLITE_FCNTL_LOCKSTATE: {
24684      *(int*)pArg = ((unixFile*)id)->locktype;
24685      return SQLITE_OK;
24686    }
24687    case SQLITE_LAST_ERRNO: {
24688      *(int*)pArg = ((unixFile*)id)->lastErrno;
24689      return SQLITE_OK;
24690    }
24691#ifndef NDEBUG
24692    /* The pager calls this method to signal that it has done
24693    ** a rollback and that the database is therefore unchanged and
24694    ** it hence it is OK for the transaction change counter to be
24695    ** unchanged.
24696    */
24697    case SQLITE_FCNTL_DB_UNCHANGED: {
24698      ((unixFile*)id)->dbUpdate = 0;
24699      return SQLITE_OK;
24700    }
24701#endif
24702#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
24703    case SQLITE_SET_LOCKPROXYFILE:
24704    case SQLITE_GET_LOCKPROXYFILE: {
24705      return proxyFileControl(id,op,pArg);
24706    }
24707#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
24708  }
24709  return SQLITE_ERROR;
24710}
24711
24712/*
24713** Return the sector size in bytes of the underlying block device for
24714** the specified file. This is almost always 512 bytes, but may be
24715** larger for some devices.
24716**
24717** SQLite code assumes this function cannot fail. It also assumes that
24718** if two files are created in the same file-system directory (i.e.
24719** a database and its journal file) that the sector size will be the
24720** same for both.
24721*/
24722static int unixSectorSize(sqlite3_file *NotUsed){
24723  UNUSED_PARAMETER(NotUsed);
24724  return SQLITE_DEFAULT_SECTOR_SIZE;
24725}
24726
24727/*
24728** Return the device characteristics for the file. This is always 0 for unix.
24729*/
24730static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
24731  UNUSED_PARAMETER(NotUsed);
24732  return 0;
24733}
24734
24735/*
24736** Here ends the implementation of all sqlite3_file methods.
24737**
24738********************** End sqlite3_file Methods *******************************
24739******************************************************************************/
24740
24741/*
24742** This division contains definitions of sqlite3_io_methods objects that
24743** implement various file locking strategies.  It also contains definitions
24744** of "finder" functions.  A finder-function is used to locate the appropriate
24745** sqlite3_io_methods object for a particular database file.  The pAppData
24746** field of the sqlite3_vfs VFS objects are initialized to be pointers to
24747** the correct finder-function for that VFS.
24748**
24749** Most finder functions return a pointer to a fixed sqlite3_io_methods
24750** object.  The only interesting finder-function is autolockIoFinder, which
24751** looks at the filesystem type and tries to guess the best locking
24752** strategy from that.
24753**
24754** For finder-funtion F, two objects are created:
24755**
24756**    (1) The real finder-function named "FImpt()".
24757**
24758**    (2) A constant pointer to this function named just "F".
24759**
24760**
24761** A pointer to the F pointer is used as the pAppData value for VFS
24762** objects.  We have to do this instead of letting pAppData point
24763** directly at the finder-function since C90 rules prevent a void*
24764** from be cast into a function pointer.
24765**
24766**
24767** Each instance of this macro generates two objects:
24768**
24769**   *  A constant sqlite3_io_methods object call METHOD that has locking
24770**      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
24771**
24772**   *  An I/O method finder function called FINDER that returns a pointer
24773**      to the METHOD object in the previous bullet.
24774*/
24775#define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK)               \
24776static const sqlite3_io_methods METHOD = {                                   \
24777   1,                          /* iVersion */                                \
24778   CLOSE,                      /* xClose */                                  \
24779   unixRead,                   /* xRead */                                   \
24780   unixWrite,                  /* xWrite */                                  \
24781   unixTruncate,               /* xTruncate */                               \
24782   unixSync,                   /* xSync */                                   \
24783   unixFileSize,               /* xFileSize */                               \
24784   LOCK,                       /* xLock */                                   \
24785   UNLOCK,                     /* xUnlock */                                 \
24786   CKLOCK,                     /* xCheckReservedLock */                      \
24787   unixFileControl,            /* xFileControl */                            \
24788   unixSectorSize,             /* xSectorSize */                             \
24789   unixDeviceCharacteristics   /* xDeviceCapabilities */                     \
24790};                                                                           \
24791static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
24792  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
24793  return &METHOD;                                                            \
24794}                                                                            \
24795static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
24796    = FINDER##Impl;
24797
24798/*
24799** Here are all of the sqlite3_io_methods objects for each of the
24800** locking strategies.  Functions that return pointers to these methods
24801** are also created.
24802*/
24803IOMETHODS(
24804  posixIoFinder,            /* Finder function name */
24805  posixIoMethods,           /* sqlite3_io_methods object name */
24806  unixClose,                /* xClose method */
24807  unixLock,                 /* xLock method */
24808  unixUnlock,               /* xUnlock method */
24809  unixCheckReservedLock     /* xCheckReservedLock method */
24810)
24811IOMETHODS(
24812  nolockIoFinder,           /* Finder function name */
24813  nolockIoMethods,          /* sqlite3_io_methods object name */
24814  nolockClose,              /* xClose method */
24815  nolockLock,               /* xLock method */
24816  nolockUnlock,             /* xUnlock method */
24817  nolockCheckReservedLock   /* xCheckReservedLock method */
24818)
24819IOMETHODS(
24820  dotlockIoFinder,          /* Finder function name */
24821  dotlockIoMethods,         /* sqlite3_io_methods object name */
24822  dotlockClose,             /* xClose method */
24823  dotlockLock,              /* xLock method */
24824  dotlockUnlock,            /* xUnlock method */
24825  dotlockCheckReservedLock  /* xCheckReservedLock method */
24826)
24827
24828#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
24829IOMETHODS(
24830  flockIoFinder,            /* Finder function name */
24831  flockIoMethods,           /* sqlite3_io_methods object name */
24832  flockClose,               /* xClose method */
24833  flockLock,                /* xLock method */
24834  flockUnlock,              /* xUnlock method */
24835  flockCheckReservedLock    /* xCheckReservedLock method */
24836)
24837#endif
24838
24839#if OS_VXWORKS
24840IOMETHODS(
24841  semIoFinder,              /* Finder function name */
24842  semIoMethods,             /* sqlite3_io_methods object name */
24843  semClose,                 /* xClose method */
24844  semLock,                  /* xLock method */
24845  semUnlock,                /* xUnlock method */
24846  semCheckReservedLock      /* xCheckReservedLock method */
24847)
24848#endif
24849
24850#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24851IOMETHODS(
24852  afpIoFinder,              /* Finder function name */
24853  afpIoMethods,             /* sqlite3_io_methods object name */
24854  afpClose,                 /* xClose method */
24855  afpLock,                  /* xLock method */
24856  afpUnlock,                /* xUnlock method */
24857  afpCheckReservedLock      /* xCheckReservedLock method */
24858)
24859#endif
24860
24861/*
24862** The "Whole File Locking" finder returns the same set of methods as
24863** the posix locking finder.  But it also sets the SQLITE_WHOLE_FILE_LOCKING
24864** flag to force the posix advisory locks to cover the whole file instead
24865** of just a small span of bytes near the 1GiB boundary.  Whole File Locking
24866** is useful on NFS-mounted files since it helps NFS to maintain cache
24867** coherency.  But it is a detriment to other filesystems since it runs
24868** slower.
24869*/
24870static const sqlite3_io_methods *posixWflIoFinderImpl(const char*z, unixFile*p){
24871  UNUSED_PARAMETER(z);
24872  p->fileFlags = SQLITE_WHOLE_FILE_LOCKING;
24873  return &posixIoMethods;
24874}
24875static const sqlite3_io_methods
24876  *(*const posixWflIoFinder)(const char*,unixFile *p) = posixWflIoFinderImpl;
24877
24878/*
24879** The proxy locking method is a "super-method" in the sense that it
24880** opens secondary file descriptors for the conch and lock files and
24881** it uses proxy, dot-file, AFP, and flock() locking methods on those
24882** secondary files.  For this reason, the division that implements
24883** proxy locking is located much further down in the file.  But we need
24884** to go ahead and define the sqlite3_io_methods and finder function
24885** for proxy locking here.  So we forward declare the I/O methods.
24886*/
24887#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24888static int proxyClose(sqlite3_file*);
24889static int proxyLock(sqlite3_file*, int);
24890static int proxyUnlock(sqlite3_file*, int);
24891static int proxyCheckReservedLock(sqlite3_file*, int*);
24892IOMETHODS(
24893  proxyIoFinder,            /* Finder function name */
24894  proxyIoMethods,           /* sqlite3_io_methods object name */
24895  proxyClose,               /* xClose method */
24896  proxyLock,                /* xLock method */
24897  proxyUnlock,              /* xUnlock method */
24898  proxyCheckReservedLock    /* xCheckReservedLock method */
24899)
24900#endif
24901
24902
24903#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24904/*
24905** This "finder" function attempts to determine the best locking strategy
24906** for the database file "filePath".  It then returns the sqlite3_io_methods
24907** object that implements that strategy.
24908**
24909** This is for MacOSX only.
24910*/
24911static const sqlite3_io_methods *autolockIoFinderImpl(
24912  const char *filePath,    /* name of the database file */
24913  unixFile *pNew           /* open file object for the database file */
24914){
24915  static const struct Mapping {
24916    const char *zFilesystem;              /* Filesystem type name */
24917    const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
24918  } aMap[] = {
24919    { "hfs",    &posixIoMethods },
24920    { "ufs",    &posixIoMethods },
24921    { "afpfs",  &afpIoMethods },
24922#ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
24923    { "smbfs",  &afpIoMethods },
24924#else
24925    { "smbfs",  &flockIoMethods },
24926#endif
24927    { "webdav", &nolockIoMethods },
24928    { 0, 0 }
24929  };
24930  int i;
24931  struct statfs fsInfo;
24932  struct flock lockInfo;
24933
24934  if( !filePath ){
24935    /* If filePath==NULL that means we are dealing with a transient file
24936    ** that does not need to be locked. */
24937    return &nolockIoMethods;
24938  }
24939  if( statfs(filePath, &fsInfo) != -1 ){
24940    if( fsInfo.f_flags & MNT_RDONLY ){
24941      return &nolockIoMethods;
24942    }
24943    for(i=0; aMap[i].zFilesystem; i++){
24944      if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
24945        return aMap[i].pMethods;
24946      }
24947    }
24948  }
24949
24950  /* Default case. Handles, amongst others, "nfs".
24951  ** Test byte-range lock using fcntl(). If the call succeeds,
24952  ** assume that the file-system supports POSIX style locks.
24953  */
24954  lockInfo.l_len = 1;
24955  lockInfo.l_start = 0;
24956  lockInfo.l_whence = SEEK_SET;
24957  lockInfo.l_type = F_RDLCK;
24958  if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
24959    pNew->fileFlags = SQLITE_WHOLE_FILE_LOCKING;
24960    return &posixIoMethods;
24961  }else{
24962    return &dotlockIoMethods;
24963  }
24964}
24965static const sqlite3_io_methods
24966  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
24967
24968#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24969
24970#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
24971/*
24972** This "finder" function attempts to determine the best locking strategy
24973** for the database file "filePath".  It then returns the sqlite3_io_methods
24974** object that implements that strategy.
24975**
24976** This is for VXWorks only.
24977*/
24978static const sqlite3_io_methods *autolockIoFinderImpl(
24979  const char *filePath,    /* name of the database file */
24980  unixFile *pNew           /* the open file object */
24981){
24982  struct flock lockInfo;
24983
24984  if( !filePath ){
24985    /* If filePath==NULL that means we are dealing with a transient file
24986    ** that does not need to be locked. */
24987    return &nolockIoMethods;
24988  }
24989
24990  /* Test if fcntl() is supported and use POSIX style locks.
24991  ** Otherwise fall back to the named semaphore method.
24992  */
24993  lockInfo.l_len = 1;
24994  lockInfo.l_start = 0;
24995  lockInfo.l_whence = SEEK_SET;
24996  lockInfo.l_type = F_RDLCK;
24997  if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
24998    return &posixIoMethods;
24999  }else{
25000    return &semIoMethods;
25001  }
25002}
25003static const sqlite3_io_methods
25004  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
25005
25006#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
25007
25008/*
25009** An abstract type for a pointer to a IO method finder function:
25010*/
25011typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
25012
25013
25014/****************************************************************************
25015**************************** sqlite3_vfs methods ****************************
25016**
25017** This division contains the implementation of methods on the
25018** sqlite3_vfs object.
25019*/
25020
25021/*
25022** Initialize the contents of the unixFile structure pointed to by pId.
25023*/
25024static int fillInUnixFile(
25025  sqlite3_vfs *pVfs,      /* Pointer to vfs object */
25026  int h,                  /* Open file descriptor of file being opened */
25027  int dirfd,              /* Directory file descriptor */
25028  sqlite3_file *pId,      /* Write to the unixFile structure here */
25029  const char *zFilename,  /* Name of the file being opened */
25030  int noLock,             /* Omit locking if true */
25031  int isDelete            /* Delete on close if true */
25032){
25033  const sqlite3_io_methods *pLockingStyle;
25034  unixFile *pNew = (unixFile *)pId;
25035  int rc = SQLITE_OK;
25036
25037  assert( pNew->pLock==NULL );
25038  assert( pNew->pOpen==NULL );
25039
25040  /* Parameter isDelete is only used on vxworks. Express this explicitly
25041  ** here to prevent compiler warnings about unused parameters.
25042  */
25043  UNUSED_PARAMETER(isDelete);
25044
25045  OSTRACE3("OPEN    %-3d %s\n", h, zFilename);
25046  pNew->h = h;
25047  pNew->dirfd = dirfd;
25048  SET_THREADID(pNew);
25049  pNew->fileFlags = 0;
25050
25051#if OS_VXWORKS
25052  pNew->pId = vxworksFindFileId(zFilename);
25053  if( pNew->pId==0 ){
25054    noLock = 1;
25055    rc = SQLITE_NOMEM;
25056  }
25057#endif
25058
25059  if( noLock ){
25060    pLockingStyle = &nolockIoMethods;
25061  }else{
25062    pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
25063#if SQLITE_ENABLE_LOCKING_STYLE
25064    /* Cache zFilename in the locking context (AFP and dotlock override) for
25065    ** proxyLock activation is possible (remote proxy is based on db name)
25066    ** zFilename remains valid until file is closed, to support */
25067    pNew->lockingContext = (void*)zFilename;
25068#endif
25069  }
25070
25071  if( pLockingStyle == &posixIoMethods ){
25072    unixEnterMutex();
25073    rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
25074    if( rc!=SQLITE_OK ){
25075      /* If an error occured in findLockInfo(), close the file descriptor
25076      ** immediately, before releasing the mutex. findLockInfo() may fail
25077      ** in two scenarios:
25078      **
25079      **   (a) A call to fstat() failed.
25080      **   (b) A malloc failed.
25081      **
25082      ** Scenario (b) may only occur if the process is holding no other
25083      ** file descriptors open on the same file. If there were other file
25084      ** descriptors on this file, then no malloc would be required by
25085      ** findLockInfo(). If this is the case, it is quite safe to close
25086      ** handle h - as it is guaranteed that no posix locks will be released
25087      ** by doing so.
25088      **
25089      ** If scenario (a) caused the error then things are not so safe. The
25090      ** implicit assumption here is that if fstat() fails, things are in
25091      ** such bad shape that dropping a lock or two doesn't matter much.
25092      */
25093      close(h);
25094      h = -1;
25095    }
25096    unixLeaveMutex();
25097  }
25098
25099#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25100  else if( pLockingStyle == &afpIoMethods ){
25101    /* AFP locking uses the file path so it needs to be included in
25102    ** the afpLockingContext.
25103    */
25104    afpLockingContext *pCtx;
25105    pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
25106    if( pCtx==0 ){
25107      rc = SQLITE_NOMEM;
25108    }else{
25109      /* NB: zFilename exists and remains valid until the file is closed
25110      ** according to requirement F11141.  So we do not need to make a
25111      ** copy of the filename. */
25112      pCtx->dbPath = zFilename;
25113      srandomdev();
25114      unixEnterMutex();
25115      rc = findLockInfo(pNew, NULL, &pNew->pOpen);
25116      unixLeaveMutex();
25117    }
25118  }
25119#endif
25120
25121  else if( pLockingStyle == &dotlockIoMethods ){
25122    /* Dotfile locking uses the file path so it needs to be included in
25123    ** the dotlockLockingContext
25124    */
25125    char *zLockFile;
25126    int nFilename;
25127    nFilename = (int)strlen(zFilename) + 6;
25128    zLockFile = (char *)sqlite3_malloc(nFilename);
25129    if( zLockFile==0 ){
25130      rc = SQLITE_NOMEM;
25131    }else{
25132      sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
25133    }
25134    pNew->lockingContext = zLockFile;
25135  }
25136
25137#if OS_VXWORKS
25138  else if( pLockingStyle == &semIoMethods ){
25139    /* Named semaphore locking uses the file path so it needs to be
25140    ** included in the semLockingContext
25141    */
25142    unixEnterMutex();
25143    rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
25144    if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
25145      char *zSemName = pNew->pOpen->aSemName;
25146      int n;
25147      sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
25148                       pNew->pId->zCanonicalName);
25149      for( n=1; zSemName[n]; n++ )
25150        if( zSemName[n]=='/' ) zSemName[n] = '_';
25151      pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
25152      if( pNew->pOpen->pSem == SEM_FAILED ){
25153        rc = SQLITE_NOMEM;
25154        pNew->pOpen->aSemName[0] = '\0';
25155      }
25156    }
25157    unixLeaveMutex();
25158  }
25159#endif
25160
25161  pNew->lastErrno = 0;
25162#if OS_VXWORKS
25163  if( rc!=SQLITE_OK ){
25164    unlink(zFilename);
25165    isDelete = 0;
25166  }
25167  pNew->isDelete = isDelete;
25168#endif
25169  if( rc!=SQLITE_OK ){
25170    if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
25171    if( h>=0 ) close(h);
25172  }else{
25173    pNew->pMethod = pLockingStyle;
25174    OpenCounter(+1);
25175  }
25176  return rc;
25177}
25178
25179/*
25180** Open a file descriptor to the directory containing file zFilename.
25181** If successful, *pFd is set to the opened file descriptor and
25182** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
25183** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
25184** value.
25185**
25186** If SQLITE_OK is returned, the caller is responsible for closing
25187** the file descriptor *pFd using close().
25188*/
25189static int openDirectory(const char *zFilename, int *pFd){
25190  int ii;
25191  int fd = -1;
25192  char zDirname[MAX_PATHNAME+1];
25193
25194  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
25195  for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
25196  if( ii>0 ){
25197    zDirname[ii] = '\0';
25198    fd = open(zDirname, O_RDONLY|O_BINARY, 0);
25199    if( fd>=0 ){
25200#ifdef FD_CLOEXEC
25201      fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
25202#endif
25203      OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
25204    }
25205  }
25206  *pFd = fd;
25207  return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
25208}
25209
25210/*
25211** Create a temporary file name in zBuf.  zBuf must be allocated
25212** by the calling process and must be big enough to hold at least
25213** pVfs->mxPathname bytes.
25214*/
25215static int getTempname(int nBuf, char *zBuf){
25216  static const char *azDirs[] = {
25217     0,
25218     0,
25219     "/var/tmp",
25220     "/usr/tmp",
25221     "/tmp",
25222     ".",
25223  };
25224  static const unsigned char zChars[] =
25225    "abcdefghijklmnopqrstuvwxyz"
25226    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
25227    "0123456789";
25228  unsigned int i, j;
25229  struct stat buf;
25230  const char *zDir = ".";
25231
25232  /* It's odd to simulate an io-error here, but really this is just
25233  ** using the io-error infrastructure to test that SQLite handles this
25234  ** function failing.
25235  */
25236  SimulateIOError( return SQLITE_IOERR );
25237
25238  azDirs[0] = sqlite3_temp_directory;
25239  if (NULL == azDirs[1]) {
25240    azDirs[1] = getenv("TMPDIR");
25241  }
25242
25243  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
25244    if( azDirs[i]==0 ) continue;
25245    if( stat(azDirs[i], &buf) ) continue;
25246    if( !S_ISDIR(buf.st_mode) ) continue;
25247    if( access(azDirs[i], 07) ) continue;
25248    zDir = azDirs[i];
25249    break;
25250  }
25251
25252  /* Check that the output buffer is large enough for the temporary file
25253  ** name. If it is not, return SQLITE_ERROR.
25254  */
25255  if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
25256    return SQLITE_ERROR;
25257  }
25258
25259  do{
25260    sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
25261    j = (int)strlen(zBuf);
25262    sqlite3_randomness(15, &zBuf[j]);
25263    for(i=0; i<15; i++, j++){
25264      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
25265    }
25266    zBuf[j] = 0;
25267  }while( access(zBuf,0)==0 );
25268  return SQLITE_OK;
25269}
25270
25271#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25272/*
25273** Routine to transform a unixFile into a proxy-locking unixFile.
25274** Implementation in the proxy-lock division, but used by unixOpen()
25275** if SQLITE_PREFER_PROXY_LOCKING is defined.
25276*/
25277static int proxyTransformUnixFile(unixFile*, const char*);
25278#endif
25279
25280/*
25281** Search for an unused file descriptor that was opened on the database
25282** file (not a journal or master-journal file) identified by pathname
25283** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
25284** argument to this function.
25285**
25286** Such a file descriptor may exist if a database connection was closed
25287** but the associated file descriptor could not be closed because some
25288** other file descriptor open on the same file is holding a file-lock.
25289** Refer to comments in the unixClose() function and the lengthy comment
25290** describing "Posix Advisory Locking" at the start of this file for
25291** further details. Also, ticket #4018.
25292**
25293** If a suitable file descriptor is found, then it is returned. If no
25294** such file descriptor is located, -1 is returned.
25295*/
25296static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
25297  UnixUnusedFd *pUnused = 0;
25298
25299  /* Do not search for an unused file descriptor on vxworks. Not because
25300  ** vxworks would not benefit from the change (it might, we're not sure),
25301  ** but because no way to test it is currently available. It is better
25302  ** not to risk breaking vxworks support for the sake of such an obscure
25303  ** feature.  */
25304#if !OS_VXWORKS
25305  struct stat sStat;                   /* Results of stat() call */
25306
25307  /* A stat() call may fail for various reasons. If this happens, it is
25308  ** almost certain that an open() call on the same path will also fail.
25309  ** For this reason, if an error occurs in the stat() call here, it is
25310  ** ignored and -1 is returned. The caller will try to open a new file
25311  ** descriptor on the same path, fail, and return an error to SQLite.
25312  **
25313  ** Even if a subsequent open() call does succeed, the consequences of
25314  ** not searching for a resusable file descriptor are not dire.  */
25315  if( 0==stat(zPath, &sStat) ){
25316    struct unixOpenCnt *pOpen;
25317
25318    unixEnterMutex();
25319    pOpen = openList;
25320    while( pOpen && (pOpen->fileId.dev!=sStat.st_dev
25321                     || pOpen->fileId.ino!=sStat.st_ino) ){
25322       pOpen = pOpen->pNext;
25323    }
25324    if( pOpen ){
25325      UnixUnusedFd **pp;
25326      for(pp=&pOpen->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
25327      pUnused = *pp;
25328      if( pUnused ){
25329        *pp = pUnused->pNext;
25330      }
25331    }
25332    unixLeaveMutex();
25333  }
25334#endif    /* if !OS_VXWORKS */
25335  return pUnused;
25336}
25337
25338/*
25339** Open the file zPath.
25340**
25341** Previously, the SQLite OS layer used three functions in place of this
25342** one:
25343**
25344**     sqlite3OsOpenReadWrite();
25345**     sqlite3OsOpenReadOnly();
25346**     sqlite3OsOpenExclusive();
25347**
25348** These calls correspond to the following combinations of flags:
25349**
25350**     ReadWrite() ->     (READWRITE | CREATE)
25351**     ReadOnly()  ->     (READONLY)
25352**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
25353**
25354** The old OpenExclusive() accepted a boolean argument - "delFlag". If
25355** true, the file was configured to be automatically deleted when the
25356** file handle closed. To achieve the same effect using this new
25357** interface, add the DELETEONCLOSE flag to those specified above for
25358** OpenExclusive().
25359*/
25360static int unixOpen(
25361  sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
25362  const char *zPath,           /* Pathname of file to be opened */
25363  sqlite3_file *pFile,         /* The file descriptor to be filled in */
25364  int flags,                   /* Input flags to control the opening */
25365  int *pOutFlags               /* Output flags returned to SQLite core */
25366){
25367  unixFile *p = (unixFile *)pFile;
25368  int fd = -1;                   /* File descriptor returned by open() */
25369  int dirfd = -1;                /* Directory file descriptor */
25370  int openFlags = 0;             /* Flags to pass to open() */
25371  int eType = flags&0xFFFFFF00;  /* Type of file to open */
25372  int noLock;                    /* True to omit locking primitives */
25373  int rc = SQLITE_OK;            /* Function Return Code */
25374
25375  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
25376  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
25377  int isCreate     = (flags & SQLITE_OPEN_CREATE);
25378  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
25379  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
25380
25381  /* If creating a master or main-file journal, this function will open
25382  ** a file-descriptor on the directory too. The first time unixSync()
25383  ** is called the directory file descriptor will be fsync()ed and close()d.
25384  */
25385  int isOpenDirectory = (isCreate &&
25386      (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
25387  );
25388
25389  /* If argument zPath is a NULL pointer, this function is required to open
25390  ** a temporary file. Use this buffer to store the file name in.
25391  */
25392  char zTmpname[MAX_PATHNAME+1];
25393  const char *zName = zPath;
25394
25395  /* Check the following statements are true:
25396  **
25397  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
25398  **   (b) if CREATE is set, then READWRITE must also be set, and
25399  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
25400  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
25401  */
25402  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
25403  assert(isCreate==0 || isReadWrite);
25404  assert(isExclusive==0 || isCreate);
25405  assert(isDelete==0 || isCreate);
25406
25407  /* The main DB, main journal, and master journal are never automatically
25408  ** deleted. Nor are they ever temporary files.  */
25409  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
25410  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
25411  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
25412
25413  /* Assert that the upper layer has set one of the "file-type" flags. */
25414  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
25415       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
25416       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
25417       || eType==SQLITE_OPEN_TRANSIENT_DB
25418  );
25419
25420  memset(p, 0, sizeof(unixFile));
25421
25422  if( eType==SQLITE_OPEN_MAIN_DB ){
25423    UnixUnusedFd *pUnused;
25424    pUnused = findReusableFd(zName, flags);
25425    if( pUnused ){
25426      fd = pUnused->fd;
25427    }else{
25428      pUnused = sqlite3_malloc(sizeof(*pUnused));
25429      if( !pUnused ){
25430        return SQLITE_NOMEM;
25431      }
25432    }
25433    p->pUnused = pUnused;
25434  }else if( !zName ){
25435    /* If zName is NULL, the upper layer is requesting a temp file. */
25436    assert(isDelete && !isOpenDirectory);
25437    rc = getTempname(MAX_PATHNAME+1, zTmpname);
25438    if( rc!=SQLITE_OK ){
25439      return rc;
25440    }
25441    zName = zTmpname;
25442  }
25443
25444  /* Determine the value of the flags parameter passed to POSIX function
25445  ** open(). These must be calculated even if open() is not called, as
25446  ** they may be stored as part of the file handle and used by the
25447  ** 'conch file' locking functions later on.  */
25448  if( isReadonly )  openFlags |= O_RDONLY;
25449  if( isReadWrite ) openFlags |= O_RDWR;
25450  if( isCreate )    openFlags |= O_CREAT;
25451  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
25452  openFlags |= (O_LARGEFILE|O_BINARY);
25453
25454  if( fd<0 ){
25455    mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
25456    fd = open(zName, openFlags, openMode);
25457    OSTRACE4("OPENX   %-3d %s 0%o\n", fd, zName, openFlags);
25458    if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
25459      /* Failed to open the file for read/write access. Try read-only. */
25460      flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
25461      openFlags &= ~(O_RDWR|O_CREAT);
25462      flags |= SQLITE_OPEN_READONLY;
25463      openFlags |= O_RDONLY;
25464      fd = open(zName, openFlags, openMode);
25465    }
25466    if( fd<0 ){
25467      rc = SQLITE_CANTOPEN_BKPT;
25468      goto open_finished;
25469    }
25470  }
25471  assert( fd>=0 );
25472  if( pOutFlags ){
25473    *pOutFlags = flags;
25474  }
25475
25476  if( p->pUnused ){
25477    p->pUnused->fd = fd;
25478    p->pUnused->flags = flags;
25479  }
25480
25481  if( isDelete ){
25482#if OS_VXWORKS
25483    zPath = zName;
25484#else
25485    unlink(zName);
25486#endif
25487  }
25488#if SQLITE_ENABLE_LOCKING_STYLE
25489  else{
25490    p->openFlags = openFlags;
25491  }
25492#endif
25493
25494  if( isOpenDirectory ){
25495    rc = openDirectory(zPath, &dirfd);
25496    if( rc!=SQLITE_OK ){
25497      /* It is safe to close fd at this point, because it is guaranteed not
25498      ** to be open on a database file. If it were open on a database file,
25499      ** it would not be safe to close as this would release any locks held
25500      ** on the file by this process.  */
25501      assert( eType!=SQLITE_OPEN_MAIN_DB );
25502      close(fd);             /* silently leak if fail, already in error */
25503      goto open_finished;
25504    }
25505  }
25506
25507#ifdef FD_CLOEXEC
25508  fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
25509#endif
25510
25511  noLock = eType!=SQLITE_OPEN_MAIN_DB;
25512
25513#if SQLITE_PREFER_PROXY_LOCKING
25514  if( zPath!=NULL && !noLock && pVfs->xOpen ){
25515    char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
25516    int useProxy = 0;
25517
25518    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
25519    ** never use proxy, NULL means use proxy for non-local files only.  */
25520    if( envforce!=NULL ){
25521      useProxy = atoi(envforce)>0;
25522    }else{
25523      struct statfs fsInfo;
25524      if( statfs(zPath, &fsInfo) == -1 ){
25525        /* In theory, the close(fd) call is sub-optimal. If the file opened
25526        ** with fd is a database file, and there are other connections open
25527        ** on that file that are currently holding advisory locks on it,
25528        ** then the call to close() will cancel those locks. In practice,
25529        ** we're assuming that statfs() doesn't fail very often. At least
25530        ** not while other file descriptors opened by the same process on
25531        ** the same file are working.  */
25532        p->lastErrno = errno;
25533        if( dirfd>=0 ){
25534          close(dirfd); /* silently leak if fail, in error */
25535        }
25536        close(fd); /* silently leak if fail, in error */
25537        rc = SQLITE_IOERR_ACCESS;
25538        goto open_finished;
25539      }
25540      useProxy = !(fsInfo.f_flags&MNT_LOCAL);
25541    }
25542    if( useProxy ){
25543      rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
25544      if( rc==SQLITE_OK ){
25545        rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
25546      }
25547      goto open_finished;
25548    }
25549  }
25550#endif
25551
25552  rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
25553open_finished:
25554  if( rc!=SQLITE_OK ){
25555    sqlite3_free(p->pUnused);
25556  }
25557  return rc;
25558}
25559
25560
25561/*
25562** Delete the file at zPath. If the dirSync argument is true, fsync()
25563** the directory after deleting the file.
25564*/
25565static int unixDelete(
25566  sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
25567  const char *zPath,        /* Name of file to be deleted */
25568  int dirSync               /* If true, fsync() directory after deleting file */
25569){
25570  int rc = SQLITE_OK;
25571  UNUSED_PARAMETER(NotUsed);
25572  SimulateIOError(return SQLITE_IOERR_DELETE);
25573  unlink(zPath);
25574#ifndef SQLITE_DISABLE_DIRSYNC
25575  if( dirSync ){
25576    int fd;
25577    rc = openDirectory(zPath, &fd);
25578    if( rc==SQLITE_OK ){
25579#if OS_VXWORKS
25580      if( fsync(fd)==-1 )
25581#else
25582      if( fsync(fd) )
25583#endif
25584      {
25585        rc = SQLITE_IOERR_DIR_FSYNC;
25586      }
25587      if( close(fd)&&!rc ){
25588        rc = SQLITE_IOERR_DIR_CLOSE;
25589      }
25590    }
25591  }
25592#endif
25593  return rc;
25594}
25595
25596/*
25597** Test the existance of or access permissions of file zPath. The
25598** test performed depends on the value of flags:
25599**
25600**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
25601**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
25602**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
25603**
25604** Otherwise return 0.
25605*/
25606static int unixAccess(
25607  sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
25608  const char *zPath,      /* Path of the file to examine */
25609  int flags,              /* What do we want to learn about the zPath file? */
25610  int *pResOut            /* Write result boolean here */
25611){
25612  int amode = 0;
25613  UNUSED_PARAMETER(NotUsed);
25614  SimulateIOError( return SQLITE_IOERR_ACCESS; );
25615  switch( flags ){
25616    case SQLITE_ACCESS_EXISTS:
25617      amode = F_OK;
25618      break;
25619    case SQLITE_ACCESS_READWRITE:
25620      amode = W_OK|R_OK;
25621      break;
25622    case SQLITE_ACCESS_READ:
25623      amode = R_OK;
25624      break;
25625
25626    default:
25627      assert(!"Invalid flags argument");
25628  }
25629  *pResOut = (access(zPath, amode)==0);
25630  return SQLITE_OK;
25631}
25632
25633
25634/*
25635** Turn a relative pathname into a full pathname. The relative path
25636** is stored as a nul-terminated string in the buffer pointed to by
25637** zPath.
25638**
25639** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
25640** (in this case, MAX_PATHNAME bytes). The full-path is written to
25641** this buffer before returning.
25642*/
25643static int unixFullPathname(
25644  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
25645  const char *zPath,            /* Possibly relative input path */
25646  int nOut,                     /* Size of output buffer in bytes */
25647  char *zOut                    /* Output buffer */
25648){
25649
25650  /* It's odd to simulate an io-error here, but really this is just
25651  ** using the io-error infrastructure to test that SQLite handles this
25652  ** function failing. This function could fail if, for example, the
25653  ** current working directory has been unlinked.
25654  */
25655  SimulateIOError( return SQLITE_ERROR );
25656
25657  assert( pVfs->mxPathname==MAX_PATHNAME );
25658  UNUSED_PARAMETER(pVfs);
25659
25660  zOut[nOut-1] = '\0';
25661  if( zPath[0]=='/' ){
25662    sqlite3_snprintf(nOut, zOut, "%s", zPath);
25663  }else{
25664    int nCwd;
25665    if( getcwd(zOut, nOut-1)==0 ){
25666      return SQLITE_CANTOPEN_BKPT;
25667    }
25668    nCwd = (int)strlen(zOut);
25669    sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
25670  }
25671  return SQLITE_OK;
25672}
25673
25674
25675#ifndef SQLITE_OMIT_LOAD_EXTENSION
25676/*
25677** Interfaces for opening a shared library, finding entry points
25678** within the shared library, and closing the shared library.
25679*/
25680#include <dlfcn.h>
25681static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
25682  UNUSED_PARAMETER(NotUsed);
25683  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
25684}
25685
25686/*
25687** SQLite calls this function immediately after a call to unixDlSym() or
25688** unixDlOpen() fails (returns a null pointer). If a more detailed error
25689** message is available, it is written to zBufOut. If no error message
25690** is available, zBufOut is left unmodified and SQLite uses a default
25691** error message.
25692*/
25693static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
25694  char *zErr;
25695  UNUSED_PARAMETER(NotUsed);
25696  unixEnterMutex();
25697  zErr = dlerror();
25698  if( zErr ){
25699    sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
25700  }
25701  unixLeaveMutex();
25702}
25703static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
25704  /*
25705  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
25706  ** cast into a pointer to a function.  And yet the library dlsym() routine
25707  ** returns a void* which is really a pointer to a function.  So how do we
25708  ** use dlsym() with -pedantic-errors?
25709  **
25710  ** Variable x below is defined to be a pointer to a function taking
25711  ** parameters void* and const char* and returning a pointer to a function.
25712  ** We initialize x by assigning it a pointer to the dlsym() function.
25713  ** (That assignment requires a cast.)  Then we call the function that
25714  ** x points to.
25715  **
25716  ** This work-around is unlikely to work correctly on any system where
25717  ** you really cannot cast a function pointer into void*.  But then, on the
25718  ** other hand, dlsym() will not work on such a system either, so we have
25719  ** not really lost anything.
25720  */
25721  void (*(*x)(void*,const char*))(void);
25722  UNUSED_PARAMETER(NotUsed);
25723  x = (void(*(*)(void*,const char*))(void))dlsym;
25724  return (*x)(p, zSym);
25725}
25726static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
25727  UNUSED_PARAMETER(NotUsed);
25728  dlclose(pHandle);
25729}
25730#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
25731  #define unixDlOpen  0
25732  #define unixDlError 0
25733  #define unixDlSym   0
25734  #define unixDlClose 0
25735#endif
25736
25737/*
25738** Write nBuf bytes of random data to the supplied buffer zBuf.
25739*/
25740static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
25741  UNUSED_PARAMETER(NotUsed);
25742  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
25743
25744  /* We have to initialize zBuf to prevent valgrind from reporting
25745  ** errors.  The reports issued by valgrind are incorrect - we would
25746  ** prefer that the randomness be increased by making use of the
25747  ** uninitialized space in zBuf - but valgrind errors tend to worry
25748  ** some users.  Rather than argue, it seems easier just to initialize
25749  ** the whole array and silence valgrind, even if that means less randomness
25750  ** in the random seed.
25751  **
25752  ** When testing, initializing zBuf[] to zero is all we do.  That means
25753  ** that we always use the same random number sequence.  This makes the
25754  ** tests repeatable.
25755  */
25756  memset(zBuf, 0, nBuf);
25757#if !defined(SQLITE_TEST)
25758  {
25759    int pid, fd;
25760    fd = open("/dev/urandom", O_RDONLY);
25761    if( fd<0 ){
25762      time_t t;
25763      time(&t);
25764      memcpy(zBuf, &t, sizeof(t));
25765      pid = getpid();
25766      memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
25767      assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
25768      nBuf = sizeof(t) + sizeof(pid);
25769    }else{
25770      nBuf = read(fd, zBuf, nBuf);
25771      close(fd);
25772    }
25773  }
25774#endif
25775  return nBuf;
25776}
25777
25778
25779/*
25780** Sleep for a little while.  Return the amount of time slept.
25781** The argument is the number of microseconds we want to sleep.
25782** The return value is the number of microseconds of sleep actually
25783** requested from the underlying operating system, a number which
25784** might be greater than or equal to the argument, but not less
25785** than the argument.
25786*/
25787static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
25788#if OS_VXWORKS
25789  struct timespec sp;
25790
25791  sp.tv_sec = microseconds / 1000000;
25792  sp.tv_nsec = (microseconds % 1000000) * 1000;
25793  nanosleep(&sp, NULL);
25794  UNUSED_PARAMETER(NotUsed);
25795  return microseconds;
25796#elif defined(HAVE_USLEEP) && HAVE_USLEEP
25797  usleep(microseconds);
25798  UNUSED_PARAMETER(NotUsed);
25799  return microseconds;
25800#else
25801  int seconds = (microseconds+999999)/1000000;
25802  sleep(seconds);
25803  UNUSED_PARAMETER(NotUsed);
25804  return seconds*1000000;
25805#endif
25806}
25807
25808/*
25809** The following variable, if set to a non-zero value, is interpreted as
25810** the number of seconds since 1970 and is used to set the result of
25811** sqlite3OsCurrentTime() during testing.
25812*/
25813#ifdef SQLITE_TEST
25814SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
25815#endif
25816
25817/*
25818** Find the current time (in Universal Coordinated Time).  Write the
25819** current time and date as a Julian Day number into *prNow and
25820** return 0.  Return 1 if the time and date cannot be found.
25821*/
25822static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
25823#if defined(SQLITE_OMIT_FLOATING_POINT)
25824  time_t t;
25825  time(&t);
25826  *prNow = (((sqlite3_int64)t)/8640 + 24405875)/10;
25827#elif defined(NO_GETTOD)
25828  time_t t;
25829  time(&t);
25830  *prNow = t/86400.0 + 2440587.5;
25831#elif OS_VXWORKS
25832  struct timespec sNow;
25833  clock_gettime(CLOCK_REALTIME, &sNow);
25834  *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
25835#else
25836  struct timeval sNow;
25837  gettimeofday(&sNow, 0);
25838  *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
25839#endif
25840
25841#ifdef SQLITE_TEST
25842  if( sqlite3_current_time ){
25843    *prNow = sqlite3_current_time/86400.0 + 2440587.5;
25844  }
25845#endif
25846  UNUSED_PARAMETER(NotUsed);
25847  return 0;
25848}
25849
25850/*
25851** We added the xGetLastError() method with the intention of providing
25852** better low-level error messages when operating-system problems come up
25853** during SQLite operation.  But so far, none of that has been implemented
25854** in the core.  So this routine is never called.  For now, it is merely
25855** a place-holder.
25856*/
25857static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
25858  UNUSED_PARAMETER(NotUsed);
25859  UNUSED_PARAMETER(NotUsed2);
25860  UNUSED_PARAMETER(NotUsed3);
25861  return 0;
25862}
25863
25864/*
25865************************ End of sqlite3_vfs methods ***************************
25866******************************************************************************/
25867
25868/******************************************************************************
25869************************** Begin Proxy Locking ********************************
25870**
25871** Proxy locking is a "uber-locking-method" in this sense:  It uses the
25872** other locking methods on secondary lock files.  Proxy locking is a
25873** meta-layer over top of the primitive locking implemented above.  For
25874** this reason, the division that implements of proxy locking is deferred
25875** until late in the file (here) after all of the other I/O methods have
25876** been defined - so that the primitive locking methods are available
25877** as services to help with the implementation of proxy locking.
25878**
25879****
25880**
25881** The default locking schemes in SQLite use byte-range locks on the
25882** database file to coordinate safe, concurrent access by multiple readers
25883** and writers [http://sqlite.org/lockingv3.html].  The five file locking
25884** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
25885** as POSIX read & write locks over fixed set of locations (via fsctl),
25886** on AFP and SMB only exclusive byte-range locks are available via fsctl
25887** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
25888** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
25889** address in the shared range is taken for a SHARED lock, the entire
25890** shared range is taken for an EXCLUSIVE lock):
25891**
25892**      PENDING_BYTE        0x40000000
25893**      RESERVED_BYTE       0x40000001
25894**      SHARED_RANGE        0x40000002 -> 0x40000200
25895**
25896** This works well on the local file system, but shows a nearly 100x
25897** slowdown in read performance on AFP because the AFP client disables
25898** the read cache when byte-range locks are present.  Enabling the read
25899** cache exposes a cache coherency problem that is present on all OS X
25900** supported network file systems.  NFS and AFP both observe the
25901** close-to-open semantics for ensuring cache coherency
25902** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
25903** address the requirements for concurrent database access by multiple
25904** readers and writers
25905** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
25906**
25907** To address the performance and cache coherency issues, proxy file locking
25908** changes the way database access is controlled by limiting access to a
25909** single host at a time and moving file locks off of the database file
25910** and onto a proxy file on the local file system.
25911**
25912**
25913** Using proxy locks
25914** -----------------
25915**
25916** C APIs
25917**
25918**  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
25919**                       <proxy_path> | ":auto:");
25920**  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
25921**
25922**
25923** SQL pragmas
25924**
25925**  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
25926**  PRAGMA [database.]lock_proxy_file
25927**
25928** Specifying ":auto:" means that if there is a conch file with a matching
25929** host ID in it, the proxy path in the conch file will be used, otherwise
25930** a proxy path based on the user's temp dir
25931** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
25932** actual proxy file name is generated from the name and path of the
25933** database file.  For example:
25934**
25935**       For database path "/Users/me/foo.db"
25936**       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
25937**
25938** Once a lock proxy is configured for a database connection, it can not
25939** be removed, however it may be switched to a different proxy path via
25940** the above APIs (assuming the conch file is not being held by another
25941** connection or process).
25942**
25943**
25944** How proxy locking works
25945** -----------------------
25946**
25947** Proxy file locking relies primarily on two new supporting files:
25948**
25949**   *  conch file to limit access to the database file to a single host
25950**      at a time
25951**
25952**   *  proxy file to act as a proxy for the advisory locks normally
25953**      taken on the database
25954**
25955** The conch file - to use a proxy file, sqlite must first "hold the conch"
25956** by taking an sqlite-style shared lock on the conch file, reading the
25957** contents and comparing the host's unique host ID (see below) and lock
25958** proxy path against the values stored in the conch.  The conch file is
25959** stored in the same directory as the database file and the file name
25960** is patterned after the database file name as ".<databasename>-conch".
25961** If the conch file does not exist, or it's contents do not match the
25962** host ID and/or proxy path, then the lock is escalated to an exclusive
25963** lock and the conch file contents is updated with the host ID and proxy
25964** path and the lock is downgraded to a shared lock again.  If the conch
25965** is held by another process (with a shared lock), the exclusive lock
25966** will fail and SQLITE_BUSY is returned.
25967**
25968** The proxy file - a single-byte file used for all advisory file locks
25969** normally taken on the database file.   This allows for safe sharing
25970** of the database file for multiple readers and writers on the same
25971** host (the conch ensures that they all use the same local lock file).
25972**
25973** There is a third file - the host ID file - used as a persistent record
25974** of a unique identifier for the host, a 128-byte unique host id file
25975** in the path defined by the HOSTIDPATH macro (default value is
25976** /Library/Caches/.com.apple.sqliteConchHostId).
25977**
25978** Requesting the lock proxy does not immediately take the conch, it is
25979** only taken when the first request to lock database file is made.
25980** This matches the semantics of the traditional locking behavior, where
25981** opening a connection to a database file does not take a lock on it.
25982** The shared lock and an open file descriptor are maintained until
25983** the connection to the database is closed.
25984**
25985** The proxy file and the lock file are never deleted so they only need
25986** to be created the first time they are used.
25987**
25988** Configuration options
25989** ---------------------
25990**
25991**  SQLITE_PREFER_PROXY_LOCKING
25992**
25993**       Database files accessed on non-local file systems are
25994**       automatically configured for proxy locking, lock files are
25995**       named automatically using the same logic as
25996**       PRAGMA lock_proxy_file=":auto:"
25997**
25998**  SQLITE_PROXY_DEBUG
25999**
26000**       Enables the logging of error messages during host id file
26001**       retrieval and creation
26002**
26003**  HOSTIDPATH
26004**
26005**       Overrides the default host ID file path location
26006**
26007**  LOCKPROXYDIR
26008**
26009**       Overrides the default directory used for lock proxy files that
26010**       are named automatically via the ":auto:" setting
26011**
26012**  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
26013**
26014**       Permissions to use when creating a directory for storing the
26015**       lock proxy files, only used when LOCKPROXYDIR is not set.
26016**
26017**
26018** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
26019** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
26020** force proxy locking to be used for every database file opened, and 0
26021** will force automatic proxy locking to be disabled for all database
26022** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
26023** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
26024*/
26025
26026/*
26027** Proxy locking is only available on MacOSX
26028*/
26029#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26030
26031#ifdef SQLITE_TEST
26032/* simulate multiple hosts by creating unique hostid file paths */
26033SQLITE_API int sqlite3_hostid_num = 0;
26034#endif
26035
26036/*
26037** The proxyLockingContext has the path and file structures for the remote
26038** and local proxy files in it
26039*/
26040typedef struct proxyLockingContext proxyLockingContext;
26041struct proxyLockingContext {
26042  unixFile *conchFile;         /* Open conch file */
26043  char *conchFilePath;         /* Name of the conch file */
26044  unixFile *lockProxy;         /* Open proxy lock file */
26045  char *lockProxyPath;         /* Name of the proxy lock file */
26046  char *dbPath;                /* Name of the open file */
26047  int conchHeld;               /* True if the conch is currently held */
26048  void *oldLockingContext;     /* Original lockingcontext to restore on close */
26049  sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
26050};
26051
26052/* HOSTIDLEN and CONCHLEN both include space for the string
26053** terminating nul
26054*/
26055#define HOSTIDLEN         128
26056#define CONCHLEN          (MAXPATHLEN+HOSTIDLEN+1)
26057#ifndef HOSTIDPATH
26058# define HOSTIDPATH       "/Library/Caches/.com.apple.sqliteConchHostId"
26059#endif
26060
26061/* basically a copy of unixRandomness with different
26062** test behavior built in */
26063static int proxyGenerateHostID(char *pHostID){
26064  int pid, fd, len;
26065  unsigned char *key = (unsigned char *)pHostID;
26066
26067  memset(key, 0, HOSTIDLEN);
26068  len = 0;
26069  fd = open("/dev/urandom", O_RDONLY);
26070  if( fd>=0 ){
26071    len = read(fd, key, HOSTIDLEN);
26072    close(fd); /* silently leak the fd if it fails */
26073  }
26074  if( len < HOSTIDLEN ){
26075    time_t t;
26076    time(&t);
26077    memcpy(key, &t, sizeof(t));
26078    pid = getpid();
26079    memcpy(&key[sizeof(t)], &pid, sizeof(pid));
26080  }
26081
26082#ifdef MAKE_PRETTY_HOSTID
26083  {
26084    int i;
26085    /* filter the bytes into printable ascii characters and NUL terminate */
26086    key[(HOSTIDLEN-1)] = 0x00;
26087    for( i=0; i<(HOSTIDLEN-1); i++ ){
26088      unsigned char pa = key[i]&0x7F;
26089      if( pa<0x20 ){
26090        key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
26091      }else if( pa==0x7F ){
26092        key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
26093      }
26094    }
26095  }
26096#endif
26097  return SQLITE_OK;
26098}
26099
26100/* writes the host id path to path, path should be an pre-allocated buffer
26101** with enough space for a path
26102*/
26103static void proxyGetHostIDPath(char *path, size_t len){
26104  strlcpy(path, HOSTIDPATH, len);
26105#ifdef SQLITE_TEST
26106  if( sqlite3_hostid_num>0 ){
26107    char suffix[2] = "1";
26108    suffix[0] = suffix[0] + sqlite3_hostid_num;
26109    strlcat(path, suffix, len);
26110  }
26111#endif
26112  OSTRACE3("GETHOSTIDPATH  %s pid=%d\n", path, getpid());
26113}
26114
26115/* get the host ID from a sqlite hostid file stored in the
26116** user-specific tmp directory, create the ID if it's not there already
26117*/
26118static int proxyGetHostID(char *pHostID, int *pError){
26119  int fd;
26120  char path[MAXPATHLEN];
26121  size_t len;
26122  int rc=SQLITE_OK;
26123
26124  proxyGetHostIDPath(path, MAXPATHLEN);
26125  /* try to create the host ID file, if it already exists read the contents */
26126  fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
26127  if( fd<0 ){
26128    int err=errno;
26129
26130    if( err!=EEXIST ){
26131#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
26132      fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
26133              path, strerror(err));
26134#endif
26135      return SQLITE_PERM;
26136    }
26137    /* couldn't create the file, read it instead */
26138    fd = open(path, O_RDONLY|O_EXCL);
26139    if( fd<0 ){
26140#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
26141      int err = errno;
26142      fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
26143              path, strerror(err));
26144#endif
26145      return SQLITE_PERM;
26146    }
26147    len = pread(fd, pHostID, HOSTIDLEN, 0);
26148    if( len<0 ){
26149      *pError = errno;
26150      rc = SQLITE_IOERR_READ;
26151    }else if( len<HOSTIDLEN ){
26152      *pError = 0;
26153      rc = SQLITE_IOERR_SHORT_READ;
26154    }
26155    close(fd); /* silently leak the fd if it fails */
26156    OSTRACE3("GETHOSTID  read %s pid=%d\n", pHostID, getpid());
26157    return rc;
26158  }else{
26159    /* we're creating the host ID file (use a random string of bytes) */
26160    proxyGenerateHostID(pHostID);
26161    len = pwrite(fd, pHostID, HOSTIDLEN, 0);
26162    if( len<0 ){
26163      *pError = errno;
26164      rc = SQLITE_IOERR_WRITE;
26165    }else if( len<HOSTIDLEN ){
26166      *pError = 0;
26167      rc = SQLITE_IOERR_WRITE;
26168    }
26169    close(fd); /* silently leak the fd if it fails */
26170    OSTRACE3("GETHOSTID  wrote %s pid=%d\n", pHostID, getpid());
26171    return rc;
26172  }
26173}
26174
26175static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
26176  int len;
26177  int dbLen;
26178  int i;
26179
26180#ifdef LOCKPROXYDIR
26181  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
26182#else
26183# ifdef _CS_DARWIN_USER_TEMP_DIR
26184  {
26185    confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen);
26186    len = strlcat(lPath, "sqliteplocks", maxLen);
26187    if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
26188      /* if mkdir fails, handle as lock file creation failure */
26189#  ifdef SQLITE_DEBUG
26190      int err = errno;
26191      if( err!=EEXIST ){
26192        fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
26193                SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
26194      }
26195#  endif
26196    }else{
26197      OSTRACE3("GETLOCKPATH  mkdir %s pid=%d\n", lPath, getpid());
26198    }
26199
26200  }
26201# else
26202  len = strlcpy(lPath, "/tmp/", maxLen);
26203# endif
26204#endif
26205
26206  if( lPath[len-1]!='/' ){
26207    len = strlcat(lPath, "/", maxLen);
26208  }
26209
26210  /* transform the db path to a unique cache name */
26211  dbLen = (int)strlen(dbPath);
26212  for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
26213    char c = dbPath[i];
26214    lPath[i+len] = (c=='/')?'_':c;
26215  }
26216  lPath[i+len]='\0';
26217  strlcat(lPath, ":auto:", maxLen);
26218  return SQLITE_OK;
26219}
26220
26221/*
26222** Create a new VFS file descriptor (stored in memory obtained from
26223** sqlite3_malloc) and open the file named "path" in the file descriptor.
26224**
26225** The caller is responsible not only for closing the file descriptor
26226** but also for freeing the memory associated with the file descriptor.
26227*/
26228static int proxyCreateUnixFile(const char *path, unixFile **ppFile) {
26229  unixFile *pNew;
26230  int flags = SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
26231  int rc = SQLITE_OK;
26232  sqlite3_vfs dummyVfs;
26233
26234  pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile));
26235  if( !pNew ){
26236    return SQLITE_NOMEM;
26237  }
26238  memset(pNew, 0, sizeof(unixFile));
26239
26240  /* Call unixOpen() to open the proxy file. The flags passed to unixOpen()
26241  ** suggest that the file being opened is a "main database". This is
26242  ** necessary as other file types do not necessarily support locking. It
26243  ** is better to use unixOpen() instead of opening the file directly with
26244  ** open(), as unixOpen() sets up the various mechanisms required to
26245  ** make sure a call to close() does not cause the system to discard
26246  ** POSIX locks prematurely.
26247  **
26248  ** It is important that the xOpen member of the VFS object passed to
26249  ** unixOpen() is NULL. This tells unixOpen() may try to open a proxy-file
26250  ** for the proxy-file (creating a potential infinite loop).
26251  */
26252  pUnused = findReusableFd(path, openFlags);
26253  if( pUnused ){
26254    fd = pUnused->fd;
26255  }else{
26256    pUnused = sqlite3_malloc(sizeof(*pUnused));
26257    if( !pUnused ){
26258      return SQLITE_NOMEM;
26259    }
26260  }
26261  if( fd<0 ){
26262    fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
26263    terrno = errno;
26264    if( fd<0 && errno==ENOENT && islockfile ){
26265      if( proxyCreateLockPath(path) == SQLITE_OK ){
26266        fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
26267      }
26268    }
26269  }
26270  if( fd<0 ){
26271    openFlags = O_RDONLY;
26272    fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
26273    terrno = errno;
26274  }
26275  if( fd<0 ){
26276    if( islockfile ){
26277      return SQLITE_BUSY;
26278    }
26279    switch (terrno) {
26280      case EACCES:
26281        return SQLITE_PERM;
26282      case EIO:
26283        return SQLITE_IOERR_LOCK; /* even though it is the conch */
26284      default:
26285        return SQLITE_CANTOPEN_BKPT;
26286    }
26287  }
26288
26289  pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
26290  if( pNew==NULL ){
26291    rc = SQLITE_NOMEM;
26292    goto end_create_proxy;
26293  }
26294  memset(pNew, 0, sizeof(unixFile));
26295  pNew->openFlags = openFlags;
26296  dummyVfs.pAppData = (void*)&autolockIoFinder;
26297  dummyVfs.xOpen = 0;
26298  rc = unixOpen(&dummyVfs, path, (sqlite3_file *)pNew, flags, &flags);
26299  if( rc==SQLITE_OK && (flags&SQLITE_OPEN_READONLY) ){
26300    pNew->pMethod->xClose((sqlite3_file *)pNew);
26301    rc = SQLITE_CANTOPEN;
26302  }
26303
26304  if( rc!=SQLITE_OK ){
26305    sqlite3_free(pNew);
26306    pNew = 0;
26307  }
26308
26309  *ppFile = pNew;
26310  return rc;
26311}
26312
26313/* takes the conch by taking a shared lock and read the contents conch, if
26314** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
26315** lockPath means that the lockPath in the conch file will be used if the
26316** host IDs match, or a new lock path will be generated automatically
26317** and written to the conch file.
26318*/
26319static int proxyTakeConch(unixFile *pFile){
26320  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26321
26322  if( pCtx->conchHeld>0 ){
26323    return SQLITE_OK;
26324  }else{
26325    unixFile *conchFile = pCtx->conchFile;
26326    char testValue[CONCHLEN];
26327    char conchValue[CONCHLEN];
26328    char lockPath[MAXPATHLEN];
26329    char *tLockPath = NULL;
26330    int rc = SQLITE_OK;
26331    int readRc = SQLITE_OK;
26332    int syncPerms = 0;
26333
26334    OSTRACE4("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
26335             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
26336
26337    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
26338    if( rc==SQLITE_OK ){
26339      int pError = 0;
26340      memset(testValue, 0, CONCHLEN); /* conch is fixed size */
26341      rc = proxyGetHostID(testValue, &pError);
26342      if( (rc&0xff)==SQLITE_IOERR ){
26343        pFile->lastErrno = pError;
26344      }
26345      if( pCtx->lockProxyPath ){
26346        strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
26347      }
26348    }
26349    if( rc!=SQLITE_OK ){
26350      goto end_takeconch;
26351    }
26352
26353    readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0);
26354    if( readRc!=SQLITE_IOERR_SHORT_READ ){
26355      if( readRc!=SQLITE_OK ){
26356        if( (rc&0xff)==SQLITE_IOERR ){
26357          pFile->lastErrno = conchFile->lastErrno;
26358        }
26359        rc = readRc;
26360        goto end_takeconch;
26361      }
26362      /* if the conch has data compare the contents */
26363      if( !pCtx->lockProxyPath ){
26364        /* for auto-named local lock file, just check the host ID and we'll
26365         ** use the local lock file path that's already in there */
26366        if( !memcmp(testValue, conchValue, HOSTIDLEN) ){
26367          tLockPath = (char *)&conchValue[HOSTIDLEN];
26368          goto end_takeconch;
26369        }
26370      }else{
26371        /* we've got the conch if conchValue matches our path and host ID */
26372        if( !memcmp(testValue, conchValue, CONCHLEN) ){
26373          goto end_takeconch;
26374        }
26375      }
26376    }else{
26377      /* a short read means we're "creating" the conch (even though it could
26378      ** have been user-intervention), if we acquire the exclusive lock,
26379      ** we'll try to match the current on-disk permissions of the database
26380      */
26381      syncPerms = 1;
26382    }
26383
26384    /* either conch was emtpy or didn't match */
26385    if( !pCtx->lockProxyPath ){
26386      proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
26387      tLockPath = lockPath;
26388      strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN);
26389    }
26390
26391    /* update conch with host and path (this will fail if other process
26392     ** has a shared lock already) */
26393    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
26394    if( rc==SQLITE_OK ){
26395      rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0);
26396      if( rc==SQLITE_OK && syncPerms ){
26397        struct stat buf;
26398        int err = fstat(pFile->h, &buf);
26399        if( err==0 ){
26400          /* try to match the database file permissions, ignore failure */
26401#ifndef SQLITE_PROXY_DEBUG
26402          fchmod(conchFile->h, buf.st_mode);
26403#else
26404          if( fchmod(conchFile->h, buf.st_mode)!=0 ){
26405            int code = errno;
26406            fprintf(stderr, "fchmod %o FAILED with %d %s\n",
26407                             buf.st_mode, code, strerror(code));
26408          } else {
26409            fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode);
26410          }
26411        }else{
26412          int code = errno;
26413          fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
26414                          err, code, strerror(code));
26415#endif
26416        }
26417      }
26418    }
26419    conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
26420
26421end_takeconch:
26422    OSTRACE2("TRANSPROXY: CLOSE  %d\n", pFile->h);
26423    if( rc==SQLITE_OK && pFile->openFlags ){
26424      if( pFile->h>=0 ){
26425#ifdef STRICT_CLOSE_ERROR
26426        if( close(pFile->h) ){
26427          pFile->lastErrno = errno;
26428          return SQLITE_IOERR_CLOSE;
26429        }
26430#else
26431        close(pFile->h); /* silently leak fd if fail */
26432#endif
26433      }
26434      pFile->h = -1;
26435      int fd = open(pCtx->dbPath, pFile->openFlags,
26436                    SQLITE_DEFAULT_FILE_PERMISSIONS);
26437      OSTRACE2("TRANSPROXY: OPEN  %d\n", fd);
26438      if( fd>=0 ){
26439        pFile->h = fd;
26440      }else{
26441        rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called
26442                               during locking */
26443      }
26444    }
26445    if( rc==SQLITE_OK && !pCtx->lockProxy ){
26446      char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
26447      /* ACS: Need to make a copy of path sometimes */
26448      rc = proxyCreateUnixFile(path, &pCtx->lockProxy);
26449    }
26450    if( rc==SQLITE_OK ){
26451      pCtx->conchHeld = 1;
26452
26453      if( tLockPath ){
26454        pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
26455        if( pCtx->lockProxy->pMethod == &afpIoMethods ){
26456          ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath =
26457                     pCtx->lockProxyPath;
26458        }
26459      }
26460>>>>>>> BEGIN MERGE CONFLICT
26461
26462      /* if the conch isn't writable and doesn't match, we can't take it */
26463      if( (conchFile->openFlags&O_RDWR) == 0 ){
26464        rc = SQLITE_BUSY;
26465        goto end_takeconch;
26466      }
26467
26468      /* either the conch didn't match or we need to create a new one */
26469      if( !pCtx->lockProxyPath ){
26470        proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
26471        tempLockPath = lockPath;
26472        /* create a copy of the lock path _only_ if the conch is taken */
26473      }
26474
26475      /* update conch with host and path (this will fail if other process
26476      ** has a shared lock already), if the host id matches, use the big
26477      ** stick.
26478      */
26479      futimes(conchFile->h, NULL);
26480      if( hostIdMatch && !createConch ){
26481        if( conchFile->pLock && conchFile->pLock->cnt>1 ){
26482          /* We are trying for an exclusive lock but another thread in this
26483           ** same process is still holding a shared lock. */
26484          rc = SQLITE_BUSY;
26485        } else {
26486          rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
26487        }
26488      }else{
26489        rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
26490      }
26491      if( rc==SQLITE_OK ){
26492        char writeBuffer[PROXY_MAXCONCHLEN];
26493        int writeSize = 0;
26494
26495        writeBuffer[0] = (char)PROXY_CONCHVERSION;
26496        memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
26497        if( pCtx->lockProxyPath!=NULL ){
26498          strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
26499        }else{
26500          strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
26501        }
26502        writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
26503        ftruncate(conchFile->h, writeSize);
26504        rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
26505        fsync(conchFile->h);
26506        /* If we created a new conch file (not just updated the contents of a
26507         ** valid conch file), try to match the permissions of the database
26508         */
26509        if( rc==SQLITE_OK && createConch ){
26510          struct stat buf;
26511          int err = fstat(pFile->h, &buf);
26512          if( err==0 ){
26513            mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
26514                                        S_IROTH|S_IWOTH);
26515            /* try to match the database file R/W permissions, ignore failure */
26516#ifndef SQLITE_PROXY_DEBUG
26517            fchmod(conchFile->h, cmode);
26518#else
26519            if( fchmod(conchFile->h, cmode)!=0 ){
26520              int code = errno;
26521              fprintf(stderr, "fchmod %o FAILED with %d %s\n",
26522                      cmode, code, strerror(code));
26523            } else {
26524              fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
26525            }
26526          }else{
26527            int code = errno;
26528            fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
26529                    err, code, strerror(code));
26530#endif
26531          }
26532        }
26533      }
26534      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
26535
26536    end_takeconch:
26537      OSTRACE2("TRANSPROXY: CLOSE  %d\n", pFile->h);
26538      if( rc==SQLITE_OK && pFile->openFlags ){
26539        if( pFile->h>=0 ){
26540#ifdef STRICT_CLOSE_ERROR
26541          if( close(pFile->h) ){
26542            pFile->lastErrno = errno;
26543            return SQLITE_IOERR_CLOSE;
26544          }
26545#else
26546          close(pFile->h); /* silently leak fd if fail */
26547#endif
26548        }
26549        pFile->h = -1;
26550        int fd = open(pCtx->dbPath, pFile->openFlags,
26551                      SQLITE_DEFAULT_FILE_PERMISSIONS);
26552        OSTRACE2("TRANSPROXY: OPEN  %d\n", fd);
26553        if( fd>=0 ){
26554          pFile->h = fd;
26555        }else{
26556          rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
26557           during locking */
26558        }
26559      }
26560      if( rc==SQLITE_OK && !pCtx->lockProxy ){
26561        char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
26562        rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
26563        if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
26564          /* we couldn't create the proxy lock file with the old lock file path
26565           ** so try again via auto-naming
26566           */
26567          forceNewLockPath = 1;
26568          tryOldLockPath = 0;
26569          continue; /* go back to the do {} while start point, try again */
26570        }
26571      }
26572      if( rc==SQLITE_OK ){
26573        /* Need to make a copy of path if we extracted the value
26574         ** from the conch file or the path was allocated on the stack
26575         */
26576        if( tempLockPath ){
26577          pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
26578          if( !pCtx->lockProxyPath ){
26579            rc = SQLITE_NOMEM;
26580          }
26581        }
26582      }
26583      if( rc==SQLITE_OK ){
26584        pCtx->conchHeld = 1;
26585
26586        if( pCtx->lockProxy->pMethod == &afpIoMethods ){
26587          afpLockingContext *afpCtx;
26588          afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
26589          afpCtx->dbPath = pCtx->lockProxyPath;
26590        }
26591      } else {
26592        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
26593      }
26594      OSTRACE3("TAKECONCH  %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
26595      return rc;
26596    } while (1); /* in case we need to retry the :auto: lock file - we should never get here except via the 'continue' call. */
26597============================
26598    } else {
26599      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
26600    }
26601    OSTRACE3("TAKECONCH  %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
26602    return rc;
26603<<<<<<< END MERGE CONFLICT
26604  }
26605}
26606
26607/*
26608** If pFile holds a lock on a conch file, then release that lock.
26609*/
26610static int proxyReleaseConch(unixFile *pFile){
26611  int rc;                     /* Subroutine return code */
26612  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
26613  unixFile *conchFile;        /* Name of the conch file */
26614
26615  pCtx = (proxyLockingContext *)pFile->lockingContext;
26616  conchFile = pCtx->conchFile;
26617  OSTRACE4("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
26618           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
26619           getpid());
26620  pCtx->conchHeld = 0;
26621  rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
26622  OSTRACE3("RELEASECONCH  %d %s\n", conchFile->h,
26623           (rc==SQLITE_OK ? "ok" : "failed"));
26624  return rc;
26625}
26626
26627/*
26628** Given the name of a database file, compute the name of its conch file.
26629** Store the conch filename in memory obtained from sqlite3_malloc().
26630** Make *pConchPath point to the new name.  Return SQLITE_OK on success
26631** or SQLITE_NOMEM if unable to obtain memory.
26632**
26633** The caller is responsible for ensuring that the allocated memory
26634** space is eventually freed.
26635**
26636** *pConchPath is set to NULL if a memory allocation error occurs.
26637*/
26638static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
26639  int i;                        /* Loop counter */
26640  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
26641  char *conchPath;              /* buffer in which to construct conch name */
26642
26643  /* Allocate space for the conch filename and initialize the name to
26644  ** the name of the original database file. */
26645  *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
26646  if( conchPath==0 ){
26647    return SQLITE_NOMEM;
26648  }
26649  memcpy(conchPath, dbPath, len+1);
26650
26651  /* now insert a "." before the last / character */
26652  for( i=(len-1); i>=0; i-- ){
26653    if( conchPath[i]=='/' ){
26654      i++;
26655      break;
26656    }
26657  }
26658  conchPath[i]='.';
26659  while ( i<len ){
26660    conchPath[i+1]=dbPath[i];
26661    i++;
26662  }
26663
26664  /* append the "-conch" suffix to the file */
26665  memcpy(&conchPath[i+1], "-conch", 7);
26666  assert( (int)strlen(conchPath) == len+7 );
26667
26668  return SQLITE_OK;
26669}
26670
26671
26672/* Takes a fully configured proxy locking-style unix file and switches
26673** the local lock file path
26674*/
26675static int switchLockProxyPath(unixFile *pFile, const char *path) {
26676  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
26677  char *oldPath = pCtx->lockProxyPath;
26678  int rc = SQLITE_OK;
26679
26680  if( pFile->locktype!=NO_LOCK ){
26681    return SQLITE_BUSY;
26682  }
26683
26684  /* nothing to do if the path is NULL, :auto: or matches the existing path */
26685  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
26686    (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
26687    return SQLITE_OK;
26688  }else{
26689    unixFile *lockProxy = pCtx->lockProxy;
26690    pCtx->lockProxy=NULL;
26691    pCtx->conchHeld = 0;
26692    if( lockProxy!=NULL ){
26693      rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
26694      if( rc ) return rc;
26695      sqlite3_free(lockProxy);
26696    }
26697    sqlite3_free(oldPath);
26698    pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
26699  }
26700
26701  return rc;
26702}
26703
26704/*
26705** pFile is a file that has been opened by a prior xOpen call.  dbPath
26706** is a string buffer at least MAXPATHLEN+1 characters in size.
26707**
26708** This routine find the filename associated with pFile and writes it
26709** int dbPath.
26710*/
26711static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
26712#if defined(__APPLE__)
26713  if( pFile->pMethod == &afpIoMethods ){
26714    /* afp style keeps a reference to the db path in the filePath field
26715    ** of the struct */
26716    assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
26717    strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath);
26718  }else
26719#endif
26720  if( pFile->pMethod == &dotlockIoMethods ){
26721    /* dot lock style uses the locking context to store the dot lock
26722    ** file path */
26723    int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
26724    memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
26725  }else{
26726    /* all other styles use the locking context to store the db file path */
26727    assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
26728    strcpy(dbPath, (char *)pFile->lockingContext);
26729  }
26730  return SQLITE_OK;
26731}
26732
26733/*
26734** Takes an already filled in unix file and alters it so all file locking
26735** will be performed on the local proxy lock file.  The following fields
26736** are preserved in the locking context so that they can be restored and
26737** the unix structure properly cleaned up at close time:
26738**  ->lockingContext
26739**  ->pMethod
26740*/
26741static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
26742  proxyLockingContext *pCtx;
26743  char dbPath[MAXPATHLEN+1];       /* Name of the database file */
26744  char *lockPath=NULL;
26745  int rc = SQLITE_OK;
26746
26747  if( pFile->locktype!=NO_LOCK ){
26748    return SQLITE_BUSY;
26749  }
26750  proxyGetDbPathForUnixFile(pFile, dbPath);
26751  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
26752    lockPath=NULL;
26753  }else{
26754    lockPath=(char *)path;
26755  }
26756
26757  OSTRACE4("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
26758           (lockPath ? lockPath : ":auto:"), getpid());
26759
26760  pCtx = sqlite3_malloc( sizeof(*pCtx) );
26761  if( pCtx==0 ){
26762    return SQLITE_NOMEM;
26763  }
26764  memset(pCtx, 0, sizeof(*pCtx));
26765
26766  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
26767  if( rc==SQLITE_OK ){
26768    rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile);
26769  }
26770  if( rc==SQLITE_OK && lockPath ){
26771    pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
26772  }
26773
26774  if( rc==SQLITE_OK ){
26775    /* all memory is allocated, proxys are created and assigned,
26776    ** switch the locking context and pMethod then return.
26777    */
26778    pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
26779    pCtx->oldLockingContext = pFile->lockingContext;
26780    pFile->lockingContext = pCtx;
26781    pCtx->pOldMethod = pFile->pMethod;
26782    pFile->pMethod = &proxyIoMethods;
26783  }else{
26784    if( pCtx->conchFile ){
26785      rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
26786      if( rc ) return rc;
26787      sqlite3_free(pCtx->conchFile);
26788    }
26789    sqlite3_free(pCtx->conchFilePath);
26790    sqlite3_free(pCtx);
26791  }
26792  OSTRACE3("TRANSPROXY  %d %s\n", pFile->h,
26793           (rc==SQLITE_OK ? "ok" : "failed"));
26794  return rc;
26795}
26796
26797
26798/*
26799** This routine handles sqlite3_file_control() calls that are specific
26800** to proxy locking.
26801*/
26802static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
26803  switch( op ){
26804    case SQLITE_GET_LOCKPROXYFILE: {
26805      unixFile *pFile = (unixFile*)id;
26806      if( pFile->pMethod == &proxyIoMethods ){
26807        proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
26808        proxyTakeConch(pFile);
26809        if( pCtx->lockProxyPath ){
26810          *(const char **)pArg = pCtx->lockProxyPath;
26811        }else{
26812          *(const char **)pArg = ":auto: (not held)";
26813        }
26814      } else {
26815        *(const char **)pArg = NULL;
26816      }
26817      return SQLITE_OK;
26818    }
26819    case SQLITE_SET_LOCKPROXYFILE: {
26820      unixFile *pFile = (unixFile*)id;
26821      int rc = SQLITE_OK;
26822      int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
26823      if( pArg==NULL || (const char *)pArg==0 ){
26824        if( isProxyStyle ){
26825          /* turn off proxy locking - not supported */
26826          rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
26827        }else{
26828          /* turn off proxy locking - already off - NOOP */
26829          rc = SQLITE_OK;
26830        }
26831      }else{
26832        const char *proxyPath = (const char *)pArg;
26833        if( isProxyStyle ){
26834          proxyLockingContext *pCtx =
26835            (proxyLockingContext*)pFile->lockingContext;
26836          if( !strcmp(pArg, ":auto:")
26837           || (pCtx->lockProxyPath &&
26838               !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
26839          ){
26840            rc = SQLITE_OK;
26841          }else{
26842            rc = switchLockProxyPath(pFile, proxyPath);
26843          }
26844        }else{
26845          /* turn on proxy file locking */
26846          rc = proxyTransformUnixFile(pFile, proxyPath);
26847        }
26848      }
26849      return rc;
26850    }
26851    default: {
26852      assert( 0 );  /* The call assures that only valid opcodes are sent */
26853    }
26854  }
26855  /*NOTREACHED*/
26856  return SQLITE_ERROR;
26857}
26858
26859/*
26860** Within this division (the proxying locking implementation) the procedures
26861** above this point are all utilities.  The lock-related methods of the
26862** proxy-locking sqlite3_io_method object follow.
26863*/
26864
26865
26866/*
26867** This routine checks if there is a RESERVED lock held on the specified
26868** file by this or any other process. If such a lock is held, set *pResOut
26869** to a non-zero value otherwise *pResOut is set to zero.  The return value
26870** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26871*/
26872static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
26873  unixFile *pFile = (unixFile*)id;
26874  int rc = proxyTakeConch(pFile);
26875  if( rc==SQLITE_OK ){
26876    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26877    unixFile *proxy = pCtx->lockProxy;
26878    return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
26879  }
26880  return rc;
26881}
26882
26883/*
26884** Lock the file with the lock specified by parameter locktype - one
26885** of the following:
26886**
26887**     (1) SHARED_LOCK
26888**     (2) RESERVED_LOCK
26889**     (3) PENDING_LOCK
26890**     (4) EXCLUSIVE_LOCK
26891**
26892** Sometimes when requesting one lock state, additional lock states
26893** are inserted in between.  The locking might fail on one of the later
26894** transitions leaving the lock state different from what it started but
26895** still short of its goal.  The following chart shows the allowed
26896** transitions and the inserted intermediate states:
26897**
26898**    UNLOCKED -> SHARED
26899**    SHARED -> RESERVED
26900**    SHARED -> (PENDING) -> EXCLUSIVE
26901**    RESERVED -> (PENDING) -> EXCLUSIVE
26902**    PENDING -> EXCLUSIVE
26903**
26904** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26905** routine to lower a locking level.
26906*/
26907static int proxyLock(sqlite3_file *id, int locktype) {
26908  unixFile *pFile = (unixFile*)id;
26909  int rc = proxyTakeConch(pFile);
26910  if( rc==SQLITE_OK ){
26911    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26912    unixFile *proxy = pCtx->lockProxy;
26913    rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
26914    pFile->locktype = proxy->locktype;
26915  }
26916  return rc;
26917}
26918
26919
26920/*
26921** Lower the locking level on file descriptor pFile to locktype.  locktype
26922** must be either NO_LOCK or SHARED_LOCK.
26923**
26924** If the locking level of the file descriptor is already at or below
26925** the requested locking level, this routine is a no-op.
26926*/
26927static int proxyUnlock(sqlite3_file *id, int locktype) {
26928  unixFile *pFile = (unixFile*)id;
26929  int rc = proxyTakeConch(pFile);
26930  if( rc==SQLITE_OK ){
26931    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26932    unixFile *proxy = pCtx->lockProxy;
26933    rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
26934    pFile->locktype = proxy->locktype;
26935  }
26936  return rc;
26937}
26938
26939/*
26940** Close a file that uses proxy locks.
26941*/
26942static int proxyClose(sqlite3_file *id) {
26943  if( id ){
26944    unixFile *pFile = (unixFile*)id;
26945    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26946    unixFile *lockProxy = pCtx->lockProxy;
26947    unixFile *conchFile = pCtx->conchFile;
26948    int rc = SQLITE_OK;
26949
26950    if( lockProxy ){
26951      rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
26952      if( rc ) return rc;
26953      rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
26954      if( rc ) return rc;
26955      sqlite3_free(lockProxy);
26956      pCtx->lockProxy = 0;
26957    }
26958    if( conchFile ){
26959      if( pCtx->conchHeld ){
26960        rc = proxyReleaseConch(pFile);
26961        if( rc ) return rc;
26962      }
26963      rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
26964      if( rc ) return rc;
26965      sqlite3_free(conchFile);
26966    }
26967    sqlite3_free(pCtx->lockProxyPath);
26968    sqlite3_free(pCtx->conchFilePath);
26969    sqlite3_free(pCtx->dbPath);
26970    /* restore the original locking context and pMethod then close it */
26971    pFile->lockingContext = pCtx->oldLockingContext;
26972    pFile->pMethod = pCtx->pOldMethod;
26973    sqlite3_free(pCtx);
26974    return pFile->pMethod->xClose(id);
26975  }
26976  return SQLITE_OK;
26977}
26978
26979
26980
26981#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26982/*
26983** The proxy locking style is intended for use with AFP filesystems.
26984** And since AFP is only supported on MacOSX, the proxy locking is also
26985** restricted to MacOSX.
26986**
26987**
26988******************* End of the proxy lock implementation **********************
26989******************************************************************************/
26990
26991/*
26992** Initialize the operating system interface.
26993**
26994** This routine registers all VFS implementations for unix-like operating
26995** systems.  This routine, and the sqlite3_os_end() routine that follows,
26996** should be the only routines in this file that are visible from other
26997** files.
26998**
26999** This routine is called once during SQLite initialization and by a
27000** single thread.  The memory allocation and mutex subsystems have not
27001** necessarily been initialized when this routine is called, and so they
27002** should not be used.
27003*/
27004SQLITE_API int sqlite3_os_init(void){
27005  /*
27006  ** The following macro defines an initializer for an sqlite3_vfs object.
27007  ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
27008  ** to the "finder" function.  (pAppData is a pointer to a pointer because
27009  ** silly C90 rules prohibit a void* from being cast to a function pointer
27010  ** and so we have to go through the intermediate pointer to avoid problems
27011  ** when compiling with -pedantic-errors on GCC.)
27012  **
27013  ** The FINDER parameter to this macro is the name of the pointer to the
27014  ** finder-function.  The finder-function returns a pointer to the
27015  ** sqlite_io_methods object that implements the desired locking
27016  ** behaviors.  See the division above that contains the IOMETHODS
27017  ** macro for addition information on finder-functions.
27018  **
27019  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
27020  ** object.  But the "autolockIoFinder" available on MacOSX does a little
27021  ** more than that; it looks at the filesystem type that hosts the
27022  ** database file and tries to choose an locking method appropriate for
27023  ** that filesystem time.
27024  */
27025  #define UNIXVFS(VFSNAME, FINDER) {                        \
27026    1,                    /* iVersion */                    \
27027    sizeof(unixFile),     /* szOsFile */                    \
27028    MAX_PATHNAME,         /* mxPathname */                  \
27029    0,                    /* pNext */                       \
27030    VFSNAME,              /* zName */                       \
27031    (void*)&FINDER,       /* pAppData */                    \
27032    unixOpen,             /* xOpen */                       \
27033    unixDelete,           /* xDelete */                     \
27034    unixAccess,           /* xAccess */                     \
27035    unixFullPathname,     /* xFullPathname */               \
27036    unixDlOpen,           /* xDlOpen */                     \
27037    unixDlError,          /* xDlError */                    \
27038    unixDlSym,            /* xDlSym */                      \
27039    unixDlClose,          /* xDlClose */                    \
27040    unixRandomness,       /* xRandomness */                 \
27041    unixSleep,            /* xSleep */                      \
27042    unixCurrentTime,      /* xCurrentTime */                \
27043    unixGetLastError      /* xGetLastError */               \
27044  }
27045
27046  /*
27047  ** All default VFSes for unix are contained in the following array.
27048  **
27049  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
27050  ** by the SQLite core when the VFS is registered.  So the following
27051  ** array cannot be const.
27052  */
27053  static sqlite3_vfs aVfs[] = {
27054#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
27055    UNIXVFS("unix",          autolockIoFinder ),
27056#else
27057    UNIXVFS("unix",          posixIoFinder ),
27058#endif
27059    UNIXVFS("unix-none",     nolockIoFinder ),
27060    UNIXVFS("unix-dotfile",  dotlockIoFinder ),
27061    UNIXVFS("unix-wfl",      posixWflIoFinder ),
27062#if OS_VXWORKS
27063    UNIXVFS("unix-namedsem", semIoFinder ),
27064#endif
27065#if SQLITE_ENABLE_LOCKING_STYLE
27066    UNIXVFS("unix-posix",    posixIoFinder ),
27067#if !OS_VXWORKS
27068    UNIXVFS("unix-flock",    flockIoFinder ),
27069#endif
27070#endif
27071#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27072    UNIXVFS("unix-afp",      afpIoFinder ),
27073    UNIXVFS("unix-proxy",    proxyIoFinder ),
27074#endif
27075  };
27076  unsigned int i;          /* Loop counter */
27077
27078  /* Register all VFSes defined in the aVfs[] array */
27079  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
27080    sqlite3_vfs_register(&aVfs[i], i==0);
27081  }
27082  return SQLITE_OK;
27083}
27084
27085/*
27086** Shutdown the operating system interface.
27087**
27088** Some operating systems might need to do some cleanup in this routine,
27089** to release dynamically allocated objects.  But not on unix.
27090** This routine is a no-op for unix.
27091*/
27092SQLITE_API int sqlite3_os_end(void){
27093  return SQLITE_OK;
27094}
27095
27096#endif /* SQLITE_OS_UNIX */
27097
27098/************** End of os_unix.c *********************************************/
27099/************** Begin file os_win.c ******************************************/
27100/*
27101** 2004 May 22
27102**
27103** The author disclaims copyright to this source code.  In place of
27104** a legal notice, here is a blessing:
27105**
27106**    May you do good and not evil.
27107**    May you find forgiveness for yourself and forgive others.
27108**    May you share freely, never taking more than you give.
27109**
27110******************************************************************************
27111**
27112** This file contains code that is specific to windows.
27113*/
27114#if SQLITE_OS_WIN               /* This file is used for windows only */
27115
27116
27117/*
27118** A Note About Memory Allocation:
27119**
27120** This driver uses malloc()/free() directly rather than going through
27121** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
27122** are designed for use on embedded systems where memory is scarce and
27123** malloc failures happen frequently.  Win32 does not typically run on
27124** embedded systems, and when it does the developers normally have bigger
27125** problems to worry about than running out of memory.  So there is not
27126** a compelling need to use the wrappers.
27127**
27128** But there is a good reason to not use the wrappers.  If we use the
27129** wrappers then we will get simulated malloc() failures within this
27130** driver.  And that causes all kinds of problems for our tests.  We
27131** could enhance SQLite to deal with simulated malloc failures within
27132** the OS driver, but the code to deal with those failure would not
27133** be exercised on Linux (which does not need to malloc() in the driver)
27134** and so we would have difficulty writing coverage tests for that
27135** code.  Better to leave the code out, we think.
27136**
27137** The point of this discussion is as follows:  When creating a new
27138** OS layer for an embedded system, if you use this file as an example,
27139** avoid the use of malloc()/free().  Those routines work ok on windows
27140** desktops but not so well in embedded systems.
27141*/
27142
27143#include <winbase.h>
27144
27145#ifdef __CYGWIN__
27146# include <sys/cygwin.h>
27147#endif
27148
27149/*
27150** Macros used to determine whether or not to use threads.
27151*/
27152#if defined(THREADSAFE) && THREADSAFE
27153# define SQLITE_W32_THREADS 1
27154#endif
27155
27156/*
27157** Include code that is common to all os_*.c files
27158*/
27159/************** Include os_common.h in the middle of os_win.c ****************/
27160/************** Begin file os_common.h ***************************************/
27161/*
27162** 2004 May 22
27163**
27164** The author disclaims copyright to this source code.  In place of
27165** a legal notice, here is a blessing:
27166**
27167**    May you do good and not evil.
27168**    May you find forgiveness for yourself and forgive others.
27169**    May you share freely, never taking more than you give.
27170**
27171******************************************************************************
27172**
27173** This file contains macros and a little bit of code that is common to
27174** all of the platform-specific files (os_*.c) and is #included into those
27175** files.
27176**
27177** This file should be #included by the os_*.c files only.  It is not a
27178** general purpose header file.
27179*/
27180#ifndef _OS_COMMON_H_
27181#define _OS_COMMON_H_
27182
27183/*
27184** At least two bugs have slipped in because we changed the MEMORY_DEBUG
27185** macro to SQLITE_DEBUG and some older makefiles have not yet made the
27186** switch.  The following code should catch this problem at compile-time.
27187*/
27188#ifdef MEMORY_DEBUG
27189# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
27190#endif
27191
27192#ifdef SQLITE_DEBUG
27193SQLITE_PRIVATE int sqlite3OSTrace = 0;
27194#define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
27195#define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
27196#define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
27197#define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
27198#define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
27199#define OSTRACE6(X,Y,Z,A,B,C) \
27200    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
27201#define OSTRACE7(X,Y,Z,A,B,C,D) \
27202    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
27203#else
27204#define OSTRACE1(X)
27205#define OSTRACE2(X,Y)
27206#define OSTRACE3(X,Y,Z)
27207#define OSTRACE4(X,Y,Z,A)
27208#define OSTRACE5(X,Y,Z,A,B)
27209#define OSTRACE6(X,Y,Z,A,B,C)
27210#define OSTRACE7(X,Y,Z,A,B,C,D)
27211#endif
27212
27213/*
27214** Macros for performance tracing.  Normally turned off.  Only works
27215** on i486 hardware.
27216*/
27217#ifdef SQLITE_PERFORMANCE_TRACE
27218
27219/*
27220** hwtime.h contains inline assembler code for implementing
27221** high-performance timing routines.
27222*/
27223/************** Include hwtime.h in the middle of os_common.h ****************/
27224/************** Begin file hwtime.h ******************************************/
27225/*
27226** 2008 May 27
27227**
27228** The author disclaims copyright to this source code.  In place of
27229** a legal notice, here is a blessing:
27230**
27231**    May you do good and not evil.
27232**    May you find forgiveness for yourself and forgive others.
27233**    May you share freely, never taking more than you give.
27234**
27235******************************************************************************
27236**
27237** This file contains inline asm code for retrieving "high-performance"
27238** counters for x86 class CPUs.
27239*/
27240#ifndef _HWTIME_H_
27241#define _HWTIME_H_
27242
27243/*
27244** The following routine only works on pentium-class (or newer) processors.
27245** It uses the RDTSC opcode to read the cycle count value out of the
27246** processor and returns that value.  This can be used for high-res
27247** profiling.
27248*/
27249#if (defined(__GNUC__) || defined(_MSC_VER)) && \
27250      (defined(i386) || defined(__i386__) || defined(_M_IX86))
27251
27252  #if defined(__GNUC__)
27253
27254  __inline__ sqlite_uint64 sqlite3Hwtime(void){
27255     unsigned int lo, hi;
27256     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
27257     return (sqlite_uint64)hi << 32 | lo;
27258  }
27259
27260  #elif defined(_MSC_VER)
27261
27262  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
27263     __asm {
27264        rdtsc
27265        ret       ; return value at EDX:EAX
27266     }
27267  }
27268
27269  #endif
27270
27271#elif (defined(__GNUC__) && defined(__x86_64__))
27272
27273  __inline__ sqlite_uint64 sqlite3Hwtime(void){
27274      unsigned long val;
27275      __asm__ __volatile__ ("rdtsc" : "=A" (val));
27276      return val;
27277  }
27278
27279#elif (defined(__GNUC__) && defined(__ppc__))
27280
27281  __inline__ sqlite_uint64 sqlite3Hwtime(void){
27282      unsigned long long retval;
27283      unsigned long junk;
27284      __asm__ __volatile__ ("\n\
27285          1:      mftbu   %1\n\
27286                  mftb    %L0\n\
27287                  mftbu   %0\n\
27288                  cmpw    %0,%1\n\
27289                  bne     1b"
27290                  : "=r" (retval), "=r" (junk));
27291      return retval;
27292  }
27293
27294#else
27295
27296  #error Need implementation of sqlite3Hwtime() for your platform.
27297
27298  /*
27299  ** To compile without implementing sqlite3Hwtime() for your platform,
27300  ** you can remove the above #error and use the following
27301  ** stub function.  You will lose timing support for many
27302  ** of the debugging and testing utilities, but it should at
27303  ** least compile and run.
27304  */
27305SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
27306
27307#endif
27308
27309#endif /* !defined(_HWTIME_H_) */
27310
27311/************** End of hwtime.h **********************************************/
27312/************** Continuing where we left off in os_common.h ******************/
27313
27314static sqlite_uint64 g_start;
27315static sqlite_uint64 g_elapsed;
27316#define TIMER_START       g_start=sqlite3Hwtime()
27317#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
27318#define TIMER_ELAPSED     g_elapsed
27319#else
27320#define TIMER_START
27321#define TIMER_END
27322#define TIMER_ELAPSED     ((sqlite_uint64)0)
27323#endif
27324
27325/*
27326** If we compile with the SQLITE_TEST macro set, then the following block
27327** of code will give us the ability to simulate a disk I/O error.  This
27328** is used for testing the I/O recovery logic.
27329*/
27330#ifdef SQLITE_TEST
27331SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
27332SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
27333SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
27334SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
27335SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
27336SQLITE_API int sqlite3_diskfull_pending = 0;
27337SQLITE_API int sqlite3_diskfull = 0;
27338#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
27339#define SimulateIOError(CODE)  \
27340  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
27341       || sqlite3_io_error_pending-- == 1 )  \
27342              { local_ioerr(); CODE; }
27343static void local_ioerr(){
27344  IOTRACE(("IOERR\n"));
27345  sqlite3_io_error_hit++;
27346  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
27347}
27348#define SimulateDiskfullError(CODE) \
27349   if( sqlite3_diskfull_pending ){ \
27350     if( sqlite3_diskfull_pending == 1 ){ \
27351       local_ioerr(); \
27352       sqlite3_diskfull = 1; \
27353       sqlite3_io_error_hit = 1; \
27354       CODE; \
27355     }else{ \
27356       sqlite3_diskfull_pending--; \
27357     } \
27358   }
27359#else
27360#define SimulateIOErrorBenign(X)
27361#define SimulateIOError(A)
27362#define SimulateDiskfullError(A)
27363#endif
27364
27365/*
27366** When testing, keep a count of the number of open files.
27367*/
27368#ifdef SQLITE_TEST
27369SQLITE_API int sqlite3_open_file_count = 0;
27370#define OpenCounter(X)  sqlite3_open_file_count+=(X)
27371#else
27372#define OpenCounter(X)
27373#endif
27374
27375#endif /* !defined(_OS_COMMON_H_) */
27376
27377/************** End of os_common.h *******************************************/
27378/************** Continuing where we left off in os_win.c *********************/
27379
27380/*
27381** Some microsoft compilers lack this definition.
27382*/
27383#ifndef INVALID_FILE_ATTRIBUTES
27384# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
27385#endif
27386
27387/*
27388** Determine if we are dealing with WindowsCE - which has a much
27389** reduced API.
27390*/
27391#if SQLITE_OS_WINCE
27392# define AreFileApisANSI() 1
27393# define FormatMessageW(a,b,c,d,e,f,g) 0
27394#endif
27395
27396/*
27397** WinCE lacks native support for file locking so we have to fake it
27398** with some code of our own.
27399*/
27400#if SQLITE_OS_WINCE
27401typedef struct winceLock {
27402  int nReaders;       /* Number of reader locks obtained */
27403  BOOL bPending;      /* Indicates a pending lock has been obtained */
27404  BOOL bReserved;     /* Indicates a reserved lock has been obtained */
27405  BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
27406} winceLock;
27407#endif
27408
27409/*
27410** The winFile structure is a subclass of sqlite3_file* specific to the win32
27411** portability layer.
27412*/
27413typedef struct winFile winFile;
27414struct winFile {
27415  const sqlite3_io_methods *pMethod;/* Must be first */
27416  HANDLE h;               /* Handle for accessing the file */
27417  unsigned char locktype; /* Type of lock currently held on this file */
27418  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
27419  DWORD lastErrno;        /* The Windows errno from the last I/O error */
27420  DWORD sectorSize;       /* Sector size of the device file is on */
27421#if SQLITE_OS_WINCE
27422  WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
27423  HANDLE hMutex;          /* Mutex used to control access to shared lock */
27424  HANDLE hShared;         /* Shared memory segment used for locking */
27425  winceLock local;        /* Locks obtained by this instance of winFile */
27426  winceLock *shared;      /* Global shared lock memory for the file  */
27427#endif
27428};
27429
27430/*
27431** Forward prototypes.
27432*/
27433static int getSectorSize(
27434    sqlite3_vfs *pVfs,
27435    const char *zRelative     /* UTF-8 file name */
27436);
27437
27438/*
27439** The following variable is (normally) set once and never changes
27440** thereafter.  It records whether the operating system is Win95
27441** or WinNT.
27442**
27443** 0:   Operating system unknown.
27444** 1:   Operating system is Win95.
27445** 2:   Operating system is WinNT.
27446**
27447** In order to facilitate testing on a WinNT system, the test fixture
27448** can manually set this value to 1 to emulate Win98 behavior.
27449*/
27450#ifdef SQLITE_TEST
27451SQLITE_API int sqlite3_os_type = 0;
27452#else
27453static int sqlite3_os_type = 0;
27454#endif
27455
27456/*
27457** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
27458** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
27459**
27460** Here is an interesting observation:  Win95, Win98, and WinME lack
27461** the LockFileEx() API.  But we can still statically link against that
27462** API as long as we don't call it when running Win95/98/ME.  A call to
27463** this routine is used to determine if the host is Win95/98/ME or
27464** WinNT/2K/XP so that we will know whether or not we can safely call
27465** the LockFileEx() API.
27466*/
27467#if SQLITE_OS_WINCE
27468# define isNT()  (1)
27469#else
27470  static int isNT(void){
27471    if( sqlite3_os_type==0 ){
27472      OSVERSIONINFO sInfo;
27473      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
27474      GetVersionEx(&sInfo);
27475      sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
27476    }
27477    return sqlite3_os_type==2;
27478  }
27479#endif /* SQLITE_OS_WINCE */
27480
27481/*
27482** Convert a UTF-8 string to microsoft unicode (UTF-16?).
27483**
27484** Space to hold the returned string is obtained from malloc.
27485*/
27486static WCHAR *utf8ToUnicode(const char *zFilename){
27487  int nChar;
27488  WCHAR *zWideFilename;
27489
27490  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
27491  zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
27492  if( zWideFilename==0 ){
27493    return 0;
27494  }
27495  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
27496  if( nChar==0 ){
27497    free(zWideFilename);
27498    zWideFilename = 0;
27499  }
27500  return zWideFilename;
27501}
27502
27503/*
27504** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
27505** obtained from malloc().
27506*/
27507static char *unicodeToUtf8(const WCHAR *zWideFilename){
27508  int nByte;
27509  char *zFilename;
27510
27511  nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
27512  zFilename = malloc( nByte );
27513  if( zFilename==0 ){
27514    return 0;
27515  }
27516  nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
27517                              0, 0);
27518  if( nByte == 0 ){
27519    free(zFilename);
27520    zFilename = 0;
27521  }
27522  return zFilename;
27523}
27524
27525/*
27526** Convert an ansi string to microsoft unicode, based on the
27527** current codepage settings for file apis.
27528**
27529** Space to hold the returned string is obtained
27530** from malloc.
27531*/
27532static WCHAR *mbcsToUnicode(const char *zFilename){
27533  int nByte;
27534  WCHAR *zMbcsFilename;
27535  int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
27536
27537  nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
27538  zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
27539  if( zMbcsFilename==0 ){
27540    return 0;
27541  }
27542  nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
27543  if( nByte==0 ){
27544    free(zMbcsFilename);
27545    zMbcsFilename = 0;
27546  }
27547  return zMbcsFilename;
27548}
27549
27550/*
27551** Convert microsoft unicode to multibyte character string, based on the
27552** user's Ansi codepage.
27553**
27554** Space to hold the returned string is obtained from
27555** malloc().
27556*/
27557static char *unicodeToMbcs(const WCHAR *zWideFilename){
27558  int nByte;
27559  char *zFilename;
27560  int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
27561
27562  nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
27563  zFilename = malloc( nByte );
27564  if( zFilename==0 ){
27565    return 0;
27566  }
27567  nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
27568                              0, 0);
27569  if( nByte == 0 ){
27570    free(zFilename);
27571    zFilename = 0;
27572  }
27573  return zFilename;
27574}
27575
27576/*
27577** Convert multibyte character string to UTF-8.  Space to hold the
27578** returned string is obtained from malloc().
27579*/
27580SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
27581  char *zFilenameUtf8;
27582  WCHAR *zTmpWide;
27583
27584  zTmpWide = mbcsToUnicode(zFilename);
27585  if( zTmpWide==0 ){
27586    return 0;
27587  }
27588  zFilenameUtf8 = unicodeToUtf8(zTmpWide);
27589  free(zTmpWide);
27590  return zFilenameUtf8;
27591}
27592
27593/*
27594** Convert UTF-8 to multibyte character string.  Space to hold the
27595** returned string is obtained from malloc().
27596*/
27597static char *utf8ToMbcs(const char *zFilename){
27598  char *zFilenameMbcs;
27599  WCHAR *zTmpWide;
27600
27601  zTmpWide = utf8ToUnicode(zFilename);
27602  if( zTmpWide==0 ){
27603    return 0;
27604  }
27605  zFilenameMbcs = unicodeToMbcs(zTmpWide);
27606  free(zTmpWide);
27607  return zFilenameMbcs;
27608}
27609
27610#if SQLITE_OS_WINCE
27611/*************************************************************************
27612** This section contains code for WinCE only.
27613*/
27614/*
27615** WindowsCE does not have a localtime() function.  So create a
27616** substitute.
27617*/
27618struct tm *__cdecl localtime(const time_t *t)
27619{
27620  static struct tm y;
27621  FILETIME uTm, lTm;
27622  SYSTEMTIME pTm;
27623  sqlite3_int64 t64;
27624  t64 = *t;
27625  t64 = (t64 + 11644473600)*10000000;
27626  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
27627  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
27628  FileTimeToLocalFileTime(&uTm,&lTm);
27629  FileTimeToSystemTime(&lTm,&pTm);
27630  y.tm_year = pTm.wYear - 1900;
27631  y.tm_mon = pTm.wMonth - 1;
27632  y.tm_wday = pTm.wDayOfWeek;
27633  y.tm_mday = pTm.wDay;
27634  y.tm_hour = pTm.wHour;
27635  y.tm_min = pTm.wMinute;
27636  y.tm_sec = pTm.wSecond;
27637  return &y;
27638}
27639
27640/* This will never be called, but defined to make the code compile */
27641#define GetTempPathA(a,b)
27642
27643#define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
27644#define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
27645#define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
27646
27647#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
27648
27649/*
27650** Acquire a lock on the handle h
27651*/
27652static void winceMutexAcquire(HANDLE h){
27653   DWORD dwErr;
27654   do {
27655     dwErr = WaitForSingleObject(h, INFINITE);
27656   } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
27657}
27658/*
27659** Release a lock acquired by winceMutexAcquire()
27660*/
27661#define winceMutexRelease(h) ReleaseMutex(h)
27662
27663/*
27664** Create the mutex and shared memory used for locking in the file
27665** descriptor pFile
27666*/
27667static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
27668  WCHAR *zTok;
27669  WCHAR *zName = utf8ToUnicode(zFilename);
27670  BOOL bInit = TRUE;
27671
27672  /* Initialize the local lockdata */
27673  ZeroMemory(&pFile->local, sizeof(pFile->local));
27674
27675  /* Replace the backslashes from the filename and lowercase it
27676  ** to derive a mutex name. */
27677  zTok = CharLowerW(zName);
27678  for (;*zTok;zTok++){
27679    if (*zTok == '\\') *zTok = '_';
27680  }
27681
27682  /* Create/open the named mutex */
27683  pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
27684  if (!pFile->hMutex){
27685    pFile->lastErrno = GetLastError();
27686    free(zName);
27687    return FALSE;
27688  }
27689
27690  /* Acquire the mutex before continuing */
27691  winceMutexAcquire(pFile->hMutex);
27692
27693  /* Since the names of named mutexes, semaphores, file mappings etc are
27694  ** case-sensitive, take advantage of that by uppercasing the mutex name
27695  ** and using that as the shared filemapping name.
27696  */
27697  CharUpperW(zName);
27698  pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
27699                                       PAGE_READWRITE, 0, sizeof(winceLock),
27700                                       zName);
27701
27702  /* Set a flag that indicates we're the first to create the memory so it
27703  ** must be zero-initialized */
27704  if (GetLastError() == ERROR_ALREADY_EXISTS){
27705    bInit = FALSE;
27706  }
27707
27708  free(zName);
27709
27710  /* If we succeeded in making the shared memory handle, map it. */
27711  if (pFile->hShared){
27712    pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
27713             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
27714    /* If mapping failed, close the shared memory handle and erase it */
27715    if (!pFile->shared){
27716      pFile->lastErrno = GetLastError();
27717      CloseHandle(pFile->hShared);
27718      pFile->hShared = NULL;
27719    }
27720  }
27721
27722  /* If shared memory could not be created, then close the mutex and fail */
27723  if (pFile->hShared == NULL){
27724    winceMutexRelease(pFile->hMutex);
27725    CloseHandle(pFile->hMutex);
27726    pFile->hMutex = NULL;
27727    return FALSE;
27728  }
27729
27730  /* Initialize the shared memory if we're supposed to */
27731  if (bInit) {
27732    ZeroMemory(pFile->shared, sizeof(winceLock));
27733  }
27734
27735  winceMutexRelease(pFile->hMutex);
27736  return TRUE;
27737}
27738
27739/*
27740** Destroy the part of winFile that deals with wince locks
27741*/
27742static void winceDestroyLock(winFile *pFile){
27743  if (pFile->hMutex){
27744    /* Acquire the mutex */
27745    winceMutexAcquire(pFile->hMutex);
27746
27747    /* The following blocks should probably assert in debug mode, but they
27748       are to cleanup in case any locks remained open */
27749    if (pFile->local.nReaders){
27750      pFile->shared->nReaders --;
27751    }
27752    if (pFile->local.bReserved){
27753      pFile->shared->bReserved = FALSE;
27754    }
27755    if (pFile->local.bPending){
27756      pFile->shared->bPending = FALSE;
27757    }
27758    if (pFile->local.bExclusive){
27759      pFile->shared->bExclusive = FALSE;
27760    }
27761
27762    /* De-reference and close our copy of the shared memory handle */
27763    UnmapViewOfFile(pFile->shared);
27764    CloseHandle(pFile->hShared);
27765
27766    /* Done with the mutex */
27767    winceMutexRelease(pFile->hMutex);
27768    CloseHandle(pFile->hMutex);
27769    pFile->hMutex = NULL;
27770  }
27771}
27772
27773/*
27774** An implementation of the LockFile() API of windows for wince
27775*/
27776static BOOL winceLockFile(
27777  HANDLE *phFile,
27778  DWORD dwFileOffsetLow,
27779  DWORD dwFileOffsetHigh,
27780  DWORD nNumberOfBytesToLockLow,
27781  DWORD nNumberOfBytesToLockHigh
27782){
27783  winFile *pFile = HANDLE_TO_WINFILE(phFile);
27784  BOOL bReturn = FALSE;
27785
27786  UNUSED_PARAMETER(dwFileOffsetHigh);
27787  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
27788
27789  if (!pFile->hMutex) return TRUE;
27790  winceMutexAcquire(pFile->hMutex);
27791
27792  /* Wanting an exclusive lock? */
27793  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
27794       && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
27795    if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
27796       pFile->shared->bExclusive = TRUE;
27797       pFile->local.bExclusive = TRUE;
27798       bReturn = TRUE;
27799    }
27800  }
27801
27802  /* Want a read-only lock? */
27803  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
27804           nNumberOfBytesToLockLow == 1){
27805    if (pFile->shared->bExclusive == 0){
27806      pFile->local.nReaders ++;
27807      if (pFile->local.nReaders == 1){
27808        pFile->shared->nReaders ++;
27809      }
27810      bReturn = TRUE;
27811    }
27812  }
27813
27814  /* Want a pending lock? */
27815  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
27816    /* If no pending lock has been acquired, then acquire it */
27817    if (pFile->shared->bPending == 0) {
27818      pFile->shared->bPending = TRUE;
27819      pFile->local.bPending = TRUE;
27820      bReturn = TRUE;
27821    }
27822  }
27823
27824  /* Want a reserved lock? */
27825  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
27826    if (pFile->shared->bReserved == 0) {
27827      pFile->shared->bReserved = TRUE;
27828      pFile->local.bReserved = TRUE;
27829      bReturn = TRUE;
27830    }
27831  }
27832
27833  winceMutexRelease(pFile->hMutex);
27834  return bReturn;
27835}
27836
27837/*
27838** An implementation of the UnlockFile API of windows for wince
27839*/
27840static BOOL winceUnlockFile(
27841  HANDLE *phFile,
27842  DWORD dwFileOffsetLow,
27843  DWORD dwFileOffsetHigh,
27844  DWORD nNumberOfBytesToUnlockLow,
27845  DWORD nNumberOfBytesToUnlockHigh
27846){
27847  winFile *pFile = HANDLE_TO_WINFILE(phFile);
27848  BOOL bReturn = FALSE;
27849
27850  UNUSED_PARAMETER(dwFileOffsetHigh);
27851  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
27852
27853  if (!pFile->hMutex) return TRUE;
27854  winceMutexAcquire(pFile->hMutex);
27855
27856  /* Releasing a reader lock or an exclusive lock */
27857  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
27858    /* Did we have an exclusive lock? */
27859    if (pFile->local.bExclusive){
27860      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
27861      pFile->local.bExclusive = FALSE;
27862      pFile->shared->bExclusive = FALSE;
27863      bReturn = TRUE;
27864    }
27865
27866    /* Did we just have a reader lock? */
27867    else if (pFile->local.nReaders){
27868      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
27869      pFile->local.nReaders --;
27870      if (pFile->local.nReaders == 0)
27871      {
27872        pFile->shared->nReaders --;
27873      }
27874      bReturn = TRUE;
27875    }
27876  }
27877
27878  /* Releasing a pending lock */
27879  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
27880    if (pFile->local.bPending){
27881      pFile->local.bPending = FALSE;
27882      pFile->shared->bPending = FALSE;
27883      bReturn = TRUE;
27884    }
27885  }
27886  /* Releasing a reserved lock */
27887  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
27888    if (pFile->local.bReserved) {
27889      pFile->local.bReserved = FALSE;
27890      pFile->shared->bReserved = FALSE;
27891      bReturn = TRUE;
27892    }
27893  }
27894
27895  winceMutexRelease(pFile->hMutex);
27896  return bReturn;
27897}
27898
27899/*
27900** An implementation of the LockFileEx() API of windows for wince
27901*/
27902static BOOL winceLockFileEx(
27903  HANDLE *phFile,
27904  DWORD dwFlags,
27905  DWORD dwReserved,
27906  DWORD nNumberOfBytesToLockLow,
27907  DWORD nNumberOfBytesToLockHigh,
27908  LPOVERLAPPED lpOverlapped
27909){
27910  UNUSED_PARAMETER(dwReserved);
27911  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
27912
27913  /* If the caller wants a shared read lock, forward this call
27914  ** to winceLockFile */
27915  if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
27916      dwFlags == 1 &&
27917      nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
27918    return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
27919  }
27920  return FALSE;
27921}
27922/*
27923** End of the special code for wince
27924*****************************************************************************/
27925#endif /* SQLITE_OS_WINCE */
27926
27927/*****************************************************************************
27928** The next group of routines implement the I/O methods specified
27929** by the sqlite3_io_methods object.
27930******************************************************************************/
27931
27932/*
27933** Close a file.
27934**
27935** It is reported that an attempt to close a handle might sometimes
27936** fail.  This is a very unreasonable result, but windows is notorious
27937** for being unreasonable so I do not doubt that it might happen.  If
27938** the close fails, we pause for 100 milliseconds and try again.  As
27939** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
27940** giving up and returning an error.
27941*/
27942#define MX_CLOSE_ATTEMPT 3
27943static int winClose(sqlite3_file *id){
27944  int rc, cnt = 0;
27945  winFile *pFile = (winFile*)id;
27946
27947  assert( id!=0 );
27948  OSTRACE2("CLOSE %d\n", pFile->h);
27949  do{
27950    rc = CloseHandle(pFile->h);
27951  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
27952#if SQLITE_OS_WINCE
27953#define WINCE_DELETION_ATTEMPTS 3
27954  winceDestroyLock(pFile);
27955  if( pFile->zDeleteOnClose ){
27956    int cnt = 0;
27957    while(
27958           DeleteFileW(pFile->zDeleteOnClose)==0
27959        && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
27960        && cnt++ < WINCE_DELETION_ATTEMPTS
27961    ){
27962       Sleep(100);  /* Wait a little before trying again */
27963    }
27964    free(pFile->zDeleteOnClose);
27965  }
27966#endif
27967  OpenCounter(-1);
27968  return rc ? SQLITE_OK : SQLITE_IOERR;
27969}
27970
27971/*
27972** Some microsoft compilers lack this definition.
27973*/
27974#ifndef INVALID_SET_FILE_POINTER
27975# define INVALID_SET_FILE_POINTER ((DWORD)-1)
27976#endif
27977
27978/*
27979** Read data from a file into a buffer.  Return SQLITE_OK if all
27980** bytes were read successfully and SQLITE_IOERR if anything goes
27981** wrong.
27982*/
27983static int winRead(
27984  sqlite3_file *id,          /* File to read from */
27985  void *pBuf,                /* Write content into this buffer */
27986  int amt,                   /* Number of bytes to read */
27987  sqlite3_int64 offset       /* Begin reading at this offset */
27988){
27989  LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
27990  LONG lowerBits = (LONG)(offset & 0xffffffff);
27991  DWORD rc;
27992  winFile *pFile = (winFile*)id;
27993  DWORD error;
27994  DWORD got;
27995
27996  assert( id!=0 );
27997  SimulateIOError(return SQLITE_IOERR_READ);
27998  OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
27999  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
28000  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
28001    pFile->lastErrno = error;
28002    return SQLITE_FULL;
28003  }
28004  if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
28005    pFile->lastErrno = GetLastError();
28006    return SQLITE_IOERR_READ;
28007  }
28008  if( got==(DWORD)amt ){
28009    return SQLITE_OK;
28010  }else{
28011    /* Unread parts of the buffer must be zero-filled */
28012    memset(&((char*)pBuf)[got], 0, amt-got);
28013    return SQLITE_IOERR_SHORT_READ;
28014  }
28015}
28016
28017/*
28018** Write data from a buffer into a file.  Return SQLITE_OK on success
28019** or some other error code on failure.
28020*/
28021static int winWrite(
28022  sqlite3_file *id,         /* File to write into */
28023  const void *pBuf,         /* The bytes to be written */
28024  int amt,                  /* Number of bytes to write */
28025  sqlite3_int64 offset      /* Offset into the file to begin writing at */
28026){
28027  LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
28028  LONG lowerBits = (LONG)(offset & 0xffffffff);
28029  DWORD rc;
28030  winFile *pFile = (winFile*)id;
28031  DWORD error;
28032  DWORD wrote = 0;
28033
28034  assert( id!=0 );
28035  SimulateIOError(return SQLITE_IOERR_WRITE);
28036  SimulateDiskfullError(return SQLITE_FULL);
28037  OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
28038  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
28039  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
28040    pFile->lastErrno = error;
28041    return SQLITE_FULL;
28042  }
28043  assert( amt>0 );
28044  while(
28045     amt>0
28046     && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
28047     && wrote>0
28048  ){
28049    amt -= wrote;
28050    pBuf = &((char*)pBuf)[wrote];
28051  }
28052  if( !rc || amt>(int)wrote ){
28053    pFile->lastErrno = GetLastError();
28054    return SQLITE_FULL;
28055  }
28056  return SQLITE_OK;
28057}
28058
28059/*
28060** Truncate an open file to a specified size
28061*/
28062static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
28063  LONG upperBits = (LONG)((nByte>>32) & 0x7fffffff);
28064  LONG lowerBits = (LONG)(nByte & 0xffffffff);
28065  DWORD rc;
28066  winFile *pFile = (winFile*)id;
28067  DWORD error;
28068
28069  assert( id!=0 );
28070  OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
28071  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
28072  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
28073  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
28074    pFile->lastErrno = error;
28075    return SQLITE_IOERR_TRUNCATE;
28076  }
28077  /* SetEndOfFile will fail if nByte is negative */
28078  if( !SetEndOfFile(pFile->h) ){
28079    pFile->lastErrno = GetLastError();
28080    return SQLITE_IOERR_TRUNCATE;
28081  }
28082  return SQLITE_OK;
28083}
28084
28085#ifdef SQLITE_TEST
28086/*
28087** Count the number of fullsyncs and normal syncs.  This is used to test
28088** that syncs and fullsyncs are occuring at the right times.
28089*/
28090SQLITE_API int sqlite3_sync_count = 0;
28091SQLITE_API int sqlite3_fullsync_count = 0;
28092#endif
28093
28094/*
28095** Make sure all writes to a particular file are committed to disk.
28096*/
28097static int winSync(sqlite3_file *id, int flags){
28098#ifndef SQLITE_NO_SYNC
28099  winFile *pFile = (winFile*)id;
28100
28101  assert( id!=0 );
28102  OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
28103#else
28104  UNUSED_PARAMETER(id);
28105#endif
28106#ifndef SQLITE_TEST
28107  UNUSED_PARAMETER(flags);
28108#else
28109  if( flags & SQLITE_SYNC_FULL ){
28110    sqlite3_fullsync_count++;
28111  }
28112  sqlite3_sync_count++;
28113#endif
28114  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
28115  ** no-op
28116  */
28117#ifdef SQLITE_NO_SYNC
28118    return SQLITE_OK;
28119#else
28120  if( FlushFileBuffers(pFile->h) ){
28121    return SQLITE_OK;
28122  }else{
28123    pFile->lastErrno = GetLastError();
28124    return SQLITE_IOERR;
28125  }
28126#endif
28127}
28128
28129/*
28130** Determine the current size of a file in bytes
28131*/
28132static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
28133  DWORD upperBits;
28134  DWORD lowerBits;
28135  winFile *pFile = (winFile*)id;
28136  DWORD error;
28137
28138  assert( id!=0 );
28139  SimulateIOError(return SQLITE_IOERR_FSTAT);
28140  lowerBits = GetFileSize(pFile->h, &upperBits);
28141  if(   (lowerBits == INVALID_FILE_SIZE)
28142     && ((error = GetLastError()) != NO_ERROR) )
28143  {
28144    pFile->lastErrno = error;
28145    return SQLITE_IOERR_FSTAT;
28146  }
28147  *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
28148  return SQLITE_OK;
28149}
28150
28151/*
28152** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
28153*/
28154#ifndef LOCKFILE_FAIL_IMMEDIATELY
28155# define LOCKFILE_FAIL_IMMEDIATELY 1
28156#endif
28157
28158/*
28159** Acquire a reader lock.
28160** Different API routines are called depending on whether or not this
28161** is Win95 or WinNT.
28162*/
28163static int getReadLock(winFile *pFile){
28164  int res;
28165  if( isNT() ){
28166    OVERLAPPED ovlp;
28167    ovlp.Offset = SHARED_FIRST;
28168    ovlp.OffsetHigh = 0;
28169    ovlp.hEvent = 0;
28170    res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
28171                     0, SHARED_SIZE, 0, &ovlp);
28172/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28173*/
28174#if SQLITE_OS_WINCE==0
28175  }else{
28176    int lk;
28177    sqlite3_randomness(sizeof(lk), &lk);
28178    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
28179    res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
28180#endif
28181  }
28182  if( res == 0 ){
28183    pFile->lastErrno = GetLastError();
28184  }
28185  return res;
28186}
28187
28188/*
28189** Undo a readlock
28190*/
28191static int unlockReadLock(winFile *pFile){
28192  int res;
28193  if( isNT() ){
28194    res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
28195/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28196*/
28197#if SQLITE_OS_WINCE==0
28198  }else{
28199    res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
28200#endif
28201  }
28202  if( res == 0 ){
28203    pFile->lastErrno = GetLastError();
28204  }
28205  return res;
28206}
28207
28208/*
28209** Lock the file with the lock specified by parameter locktype - one
28210** of the following:
28211**
28212**     (1) SHARED_LOCK
28213**     (2) RESERVED_LOCK
28214**     (3) PENDING_LOCK
28215**     (4) EXCLUSIVE_LOCK
28216**
28217** Sometimes when requesting one lock state, additional lock states
28218** are inserted in between.  The locking might fail on one of the later
28219** transitions leaving the lock state different from what it started but
28220** still short of its goal.  The following chart shows the allowed
28221** transitions and the inserted intermediate states:
28222**
28223**    UNLOCKED -> SHARED
28224**    SHARED -> RESERVED
28225**    SHARED -> (PENDING) -> EXCLUSIVE
28226**    RESERVED -> (PENDING) -> EXCLUSIVE
28227**    PENDING -> EXCLUSIVE
28228**
28229** This routine will only increase a lock.  The winUnlock() routine
28230** erases all locks at once and returns us immediately to locking level 0.
28231** It is not possible to lower the locking level one step at a time.  You
28232** must go straight to locking level 0.
28233*/
28234static int winLock(sqlite3_file *id, int locktype){
28235  int rc = SQLITE_OK;    /* Return code from subroutines */
28236  int res = 1;           /* Result of a windows lock call */
28237  int newLocktype;       /* Set pFile->locktype to this value before exiting */
28238  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
28239  winFile *pFile = (winFile*)id;
28240  DWORD error = NO_ERROR;
28241
28242  assert( id!=0 );
28243  OSTRACE5("LOCK %d %d was %d(%d)\n",
28244          pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
28245
28246  /* If there is already a lock of this type or more restrictive on the
28247  ** OsFile, do nothing. Don't use the end_lock: exit path, as
28248  ** sqlite3OsEnterMutex() hasn't been called yet.
28249  */
28250  if( pFile->locktype>=locktype ){
28251    return SQLITE_OK;
28252  }
28253
28254  /* Make sure the locking sequence is correct
28255  */
28256  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
28257  assert( locktype!=PENDING_LOCK );
28258  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
28259
28260  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
28261  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
28262  ** the PENDING_LOCK byte is temporary.
28263  */
28264  newLocktype = pFile->locktype;
28265  if(   (pFile->locktype==NO_LOCK)
28266     || (   (locktype==EXCLUSIVE_LOCK)
28267         && (pFile->locktype==RESERVED_LOCK))
28268  ){
28269    int cnt = 3;
28270    while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
28271      /* Try 3 times to get the pending lock.  The pending lock might be
28272      ** held by another reader process who will release it momentarily.
28273      */
28274      OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
28275      Sleep(1);
28276    }
28277    gotPendingLock = res;
28278    if( !res ){
28279      error = GetLastError();
28280    }
28281  }
28282
28283  /* Acquire a shared lock
28284  */
28285  if( locktype==SHARED_LOCK && res ){
28286    assert( pFile->locktype==NO_LOCK );
28287    res = getReadLock(pFile);
28288    if( res ){
28289      newLocktype = SHARED_LOCK;
28290    }else{
28291      error = GetLastError();
28292    }
28293  }
28294
28295  /* Acquire a RESERVED lock
28296  */
28297  if( locktype==RESERVED_LOCK && res ){
28298    assert( pFile->locktype==SHARED_LOCK );
28299    res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28300    if( res ){
28301      newLocktype = RESERVED_LOCK;
28302    }else{
28303      error = GetLastError();
28304    }
28305  }
28306
28307  /* Acquire a PENDING lock
28308  */
28309  if( locktype==EXCLUSIVE_LOCK && res ){
28310    newLocktype = PENDING_LOCK;
28311    gotPendingLock = 0;
28312  }
28313
28314  /* Acquire an EXCLUSIVE lock
28315  */
28316  if( locktype==EXCLUSIVE_LOCK && res ){
28317    assert( pFile->locktype>=SHARED_LOCK );
28318    res = unlockReadLock(pFile);
28319    OSTRACE2("unreadlock = %d\n", res);
28320    res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
28321    if( res ){
28322      newLocktype = EXCLUSIVE_LOCK;
28323    }else{
28324      error = GetLastError();
28325      OSTRACE2("error-code = %d\n", error);
28326      getReadLock(pFile);
28327    }
28328  }
28329
28330  /* If we are holding a PENDING lock that ought to be released, then
28331  ** release it now.
28332  */
28333  if( gotPendingLock && locktype==SHARED_LOCK ){
28334    UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
28335  }
28336
28337  /* Update the state of the lock has held in the file descriptor then
28338  ** return the appropriate result code.
28339  */
28340  if( res ){
28341    rc = SQLITE_OK;
28342  }else{
28343    OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
28344           locktype, newLocktype);
28345    pFile->lastErrno = error;
28346    rc = SQLITE_BUSY;
28347  }
28348  pFile->locktype = (u8)newLocktype;
28349  return rc;
28350}
28351
28352/*
28353** This routine checks if there is a RESERVED lock held on the specified
28354** file by this or any other process. If such a lock is held, return
28355** non-zero, otherwise zero.
28356*/
28357static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
28358  int rc;
28359  winFile *pFile = (winFile*)id;
28360
28361  assert( id!=0 );
28362  if( pFile->locktype>=RESERVED_LOCK ){
28363    rc = 1;
28364    OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
28365  }else{
28366    rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28367    if( rc ){
28368      UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28369    }
28370    rc = !rc;
28371    OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
28372  }
28373  *pResOut = rc;
28374  return SQLITE_OK;
28375}
28376
28377/*
28378** Lower the locking level on file descriptor id to locktype.  locktype
28379** must be either NO_LOCK or SHARED_LOCK.
28380**
28381** If the locking level of the file descriptor is already at or below
28382** the requested locking level, this routine is a no-op.
28383**
28384** It is not possible for this routine to fail if the second argument
28385** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
28386** might return SQLITE_IOERR;
28387*/
28388static int winUnlock(sqlite3_file *id, int locktype){
28389  int type;
28390  winFile *pFile = (winFile*)id;
28391  int rc = SQLITE_OK;
28392  assert( pFile!=0 );
28393  assert( locktype<=SHARED_LOCK );
28394  OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
28395          pFile->locktype, pFile->sharedLockByte);
28396  type = pFile->locktype;
28397  if( type>=EXCLUSIVE_LOCK ){
28398    UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
28399    if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
28400      /* This should never happen.  We should always be able to
28401      ** reacquire the read lock */
28402      rc = SQLITE_IOERR_UNLOCK;
28403    }
28404  }
28405  if( type>=RESERVED_LOCK ){
28406    UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28407  }
28408  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
28409    unlockReadLock(pFile);
28410  }
28411  if( type>=PENDING_LOCK ){
28412    UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
28413  }
28414  pFile->locktype = (u8)locktype;
28415  return rc;
28416}
28417
28418/*
28419** Control and query of the open file handle.
28420*/
28421static int winFileControl(sqlite3_file *id, int op, void *pArg){
28422  switch( op ){
28423    case SQLITE_FCNTL_LOCKSTATE: {
28424      *(int*)pArg = ((winFile*)id)->locktype;
28425      return SQLITE_OK;
28426    }
28427    case SQLITE_LAST_ERRNO: {
28428      *(int*)pArg = (int)((winFile*)id)->lastErrno;
28429      return SQLITE_OK;
28430    }
28431  }
28432  return SQLITE_ERROR;
28433}
28434
28435/*
28436** Return the sector size in bytes of the underlying block device for
28437** the specified file. This is almost always 512 bytes, but may be
28438** larger for some devices.
28439**
28440** SQLite code assumes this function cannot fail. It also assumes that
28441** if two files are created in the same file-system directory (i.e.
28442** a database and its journal file) that the sector size will be the
28443** same for both.
28444*/
28445static int winSectorSize(sqlite3_file *id){
28446  assert( id!=0 );
28447  return (int)(((winFile*)id)->sectorSize);
28448}
28449
28450/*
28451** Return a vector of device characteristics.
28452*/
28453static int winDeviceCharacteristics(sqlite3_file *id){
28454  UNUSED_PARAMETER(id);
28455  return 0;
28456}
28457
28458/*
28459** This vector defines all the methods that can operate on an
28460** sqlite3_file for win32.
28461*/
28462static const sqlite3_io_methods winIoMethod = {
28463  1,                        /* iVersion */
28464  winClose,
28465  winRead,
28466  winWrite,
28467  winTruncate,
28468  winSync,
28469  winFileSize,
28470  winLock,
28471  winUnlock,
28472  winCheckReservedLock,
28473  winFileControl,
28474  winSectorSize,
28475  winDeviceCharacteristics
28476};
28477
28478/***************************************************************************
28479** Here ends the I/O methods that form the sqlite3_io_methods object.
28480**
28481** The next block of code implements the VFS methods.
28482****************************************************************************/
28483
28484/*
28485** Convert a UTF-8 filename into whatever form the underlying
28486** operating system wants filenames in.  Space to hold the result
28487** is obtained from malloc and must be freed by the calling
28488** function.
28489*/
28490static void *convertUtf8Filename(const char *zFilename){
28491  void *zConverted = 0;
28492  if( isNT() ){
28493    zConverted = utf8ToUnicode(zFilename);
28494/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28495*/
28496#if SQLITE_OS_WINCE==0
28497  }else{
28498    zConverted = utf8ToMbcs(zFilename);
28499#endif
28500  }
28501  /* caller will handle out of memory */
28502  return zConverted;
28503}
28504
28505/*
28506** Create a temporary file name in zBuf.  zBuf must be big enough to
28507** hold at pVfs->mxPathname characters.
28508*/
28509static int getTempname(int nBuf, char *zBuf){
28510  static char zChars[] =
28511    "abcdefghijklmnopqrstuvwxyz"
28512    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
28513    "0123456789";
28514  size_t i, j;
28515  char zTempPath[MAX_PATH+1];
28516  if( sqlite3_temp_directory ){
28517    sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
28518  }else if( isNT() ){
28519    char *zMulti;
28520    WCHAR zWidePath[MAX_PATH];
28521    GetTempPathW(MAX_PATH-30, zWidePath);
28522    zMulti = unicodeToUtf8(zWidePath);
28523    if( zMulti ){
28524      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
28525      free(zMulti);
28526    }else{
28527      return SQLITE_NOMEM;
28528    }
28529/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28530** Since the ASCII version of these Windows API do not exist for WINCE,
28531** it's important to not reference them for WINCE builds.
28532*/
28533#if SQLITE_OS_WINCE==0
28534  }else{
28535    char *zUtf8;
28536    char zMbcsPath[MAX_PATH];
28537    GetTempPathA(MAX_PATH-30, zMbcsPath);
28538    zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
28539    if( zUtf8 ){
28540      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
28541      free(zUtf8);
28542    }else{
28543      return SQLITE_NOMEM;
28544    }
28545#endif
28546  }
28547  for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
28548  zTempPath[i] = 0;
28549  sqlite3_snprintf(nBuf-30, zBuf,
28550                   "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
28551  j = sqlite3Strlen30(zBuf);
28552  sqlite3_randomness(20, &zBuf[j]);
28553  for(i=0; i<20; i++, j++){
28554    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
28555  }
28556  zBuf[j] = 0;
28557  OSTRACE2("TEMP FILENAME: %s\n", zBuf);
28558  return SQLITE_OK;
28559}
28560
28561/*
28562** The return value of getLastErrorMsg
28563** is zero if the error message fits in the buffer, or non-zero
28564** otherwise (if the message was truncated).
28565*/
28566static int getLastErrorMsg(int nBuf, char *zBuf){
28567  /* FormatMessage returns 0 on failure.  Otherwise it
28568  ** returns the number of TCHARs written to the output
28569  ** buffer, excluding the terminating null char.
28570  */
28571  DWORD error = GetLastError();
28572  DWORD dwLen = 0;
28573  char *zOut = 0;
28574
28575  if( isNT() ){
28576    WCHAR *zTempWide = NULL;
28577    dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
28578                           NULL,
28579                           error,
28580                           0,
28581                           (LPWSTR) &zTempWide,
28582                           0,
28583                           0);
28584    if( dwLen > 0 ){
28585      /* allocate a buffer and convert to UTF8 */
28586      zOut = unicodeToUtf8(zTempWide);
28587      /* free the system buffer allocated by FormatMessage */
28588      LocalFree(zTempWide);
28589    }
28590/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28591** Since the ASCII version of these Windows API do not exist for WINCE,
28592** it's important to not reference them for WINCE builds.
28593*/
28594#if SQLITE_OS_WINCE==0
28595  }else{
28596    char *zTemp = NULL;
28597    dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
28598                           NULL,
28599                           error,
28600                           0,
28601                           (LPSTR) &zTemp,
28602                           0,
28603                           0);
28604    if( dwLen > 0 ){
28605      /* allocate a buffer and convert to UTF8 */
28606      zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
28607      /* free the system buffer allocated by FormatMessage */
28608      LocalFree(zTemp);
28609    }
28610#endif
28611  }
28612  if( 0 == dwLen ){
28613    sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
28614  }else{
28615    /* copy a maximum of nBuf chars to output buffer */
28616    sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
28617    /* free the UTF8 buffer */
28618    free(zOut);
28619  }
28620  return 0;
28621}
28622
28623/*
28624** Open a file.
28625*/
28626static int winOpen(
28627  sqlite3_vfs *pVfs,        /* Not used */
28628  const char *zName,        /* Name of the file (UTF-8) */
28629  sqlite3_file *id,         /* Write the SQLite file handle here */
28630  int flags,                /* Open mode flags */
28631  int *pOutFlags            /* Status return flags */
28632){
28633  HANDLE h;
28634  DWORD dwDesiredAccess;
28635  DWORD dwShareMode;
28636  DWORD dwCreationDisposition;
28637  DWORD dwFlagsAndAttributes = 0;
28638#if SQLITE_OS_WINCE
28639  int isTemp = 0;
28640#endif
28641  winFile *pFile = (winFile*)id;
28642  void *zConverted;                 /* Filename in OS encoding */
28643  const char *zUtf8Name = zName;    /* Filename in UTF-8 encoding */
28644  char zTmpname[MAX_PATH+1];        /* Buffer used to create temp filename */
28645
28646  assert( id!=0 );
28647  UNUSED_PARAMETER(pVfs);
28648
28649  /* If the second argument to this function is NULL, generate a
28650  ** temporary file name to use
28651  */
28652  if( !zUtf8Name ){
28653    int rc = getTempname(MAX_PATH+1, zTmpname);
28654    if( rc!=SQLITE_OK ){
28655      return rc;
28656    }
28657    zUtf8Name = zTmpname;
28658  }
28659
28660  /* Convert the filename to the system encoding. */
28661  zConverted = convertUtf8Filename(zUtf8Name);
28662  if( zConverted==0 ){
28663    return SQLITE_NOMEM;
28664  }
28665
28666  if( flags & SQLITE_OPEN_READWRITE ){
28667    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
28668  }else{
28669    dwDesiredAccess = GENERIC_READ;
28670  }
28671  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
28672  ** created. SQLite doesn't use it to indicate "exclusive access"
28673  ** as it is usually understood.
28674  */
28675  assert(!(flags & SQLITE_OPEN_EXCLUSIVE) || (flags & SQLITE_OPEN_CREATE));
28676  if( flags & SQLITE_OPEN_EXCLUSIVE ){
28677    /* Creates a new file, only if it does not already exist. */
28678    /* If the file exists, it fails. */
28679    dwCreationDisposition = CREATE_NEW;
28680  }else if( flags & SQLITE_OPEN_CREATE ){
28681    /* Open existing file, or create if it doesn't exist */
28682    dwCreationDisposition = OPEN_ALWAYS;
28683  }else{
28684    /* Opens a file, only if it exists. */
28685    dwCreationDisposition = OPEN_EXISTING;
28686  }
28687  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
28688  if( flags & SQLITE_OPEN_DELETEONCLOSE ){
28689#if SQLITE_OS_WINCE
28690    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
28691    isTemp = 1;
28692#else
28693    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
28694                               | FILE_ATTRIBUTE_HIDDEN
28695                               | FILE_FLAG_DELETE_ON_CLOSE;
28696#endif
28697  }else{
28698    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
28699  }
28700  /* Reports from the internet are that performance is always
28701  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
28702#if SQLITE_OS_WINCE
28703  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
28704#endif
28705  if( isNT() ){
28706    h = CreateFileW((WCHAR*)zConverted,
28707       dwDesiredAccess,
28708       dwShareMode,
28709       NULL,
28710       dwCreationDisposition,
28711       dwFlagsAndAttributes,
28712       NULL
28713    );
28714/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28715** Since the ASCII version of these Windows API do not exist for WINCE,
28716** it's important to not reference them for WINCE builds.
28717*/
28718#if SQLITE_OS_WINCE==0
28719  }else{
28720    h = CreateFileA((char*)zConverted,
28721       dwDesiredAccess,
28722       dwShareMode,
28723       NULL,
28724       dwCreationDisposition,
28725       dwFlagsAndAttributes,
28726       NULL
28727    );
28728#endif
28729  }
28730  if( h==INVALID_HANDLE_VALUE ){
28731    free(zConverted);
28732    if( flags & SQLITE_OPEN_READWRITE ){
28733      return winOpen(pVfs, zName, id,
28734             ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
28735    }else{
28736      return SQLITE_CANTOPEN_BKPT;
28737    }
28738  }
28739  if( pOutFlags ){
28740    if( flags & SQLITE_OPEN_READWRITE ){
28741      *pOutFlags = SQLITE_OPEN_READWRITE;
28742    }else{
28743      *pOutFlags = SQLITE_OPEN_READONLY;
28744    }
28745  }
28746  memset(pFile, 0, sizeof(*pFile));
28747  pFile->pMethod = &winIoMethod;
28748  pFile->h = h;
28749  pFile->lastErrno = NO_ERROR;
28750  pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
28751#if SQLITE_OS_WINCE
28752  if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
28753               (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
28754       && !winceCreateLock(zName, pFile)
28755  ){
28756    CloseHandle(h);
28757    free(zConverted);
28758    return SQLITE_CANTOPEN_BKPT;
28759  }
28760  if( isTemp ){
28761    pFile->zDeleteOnClose = zConverted;
28762  }else
28763#endif
28764  {
28765    free(zConverted);
28766  }
28767  OpenCounter(+1);
28768  return SQLITE_OK;
28769}
28770
28771/*
28772** Delete the named file.
28773**
28774** Note that windows does not allow a file to be deleted if some other
28775** process has it open.  Sometimes a virus scanner or indexing program
28776** will open a journal file shortly after it is created in order to do
28777** whatever it does.  While this other process is holding the
28778** file open, we will be unable to delete it.  To work around this
28779** problem, we delay 100 milliseconds and try to delete again.  Up
28780** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
28781** up and returning an error.
28782*/
28783#define MX_DELETION_ATTEMPTS 5
28784static int winDelete(
28785  sqlite3_vfs *pVfs,          /* Not used on win32 */
28786  const char *zFilename,      /* Name of file to delete */
28787  int syncDir                 /* Not used on win32 */
28788){
28789  int cnt = 0;
28790  DWORD rc;
28791  DWORD error = 0;
28792  void *zConverted = convertUtf8Filename(zFilename);
28793  UNUSED_PARAMETER(pVfs);
28794  UNUSED_PARAMETER(syncDir);
28795  if( zConverted==0 ){
28796    return SQLITE_NOMEM;
28797  }
28798  SimulateIOError(return SQLITE_IOERR_DELETE);
28799  if( isNT() ){
28800    do{
28801      DeleteFileW(zConverted);
28802    }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
28803               || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
28804           && (++cnt < MX_DELETION_ATTEMPTS)
28805           && (Sleep(100), 1) );
28806/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28807** Since the ASCII version of these Windows API do not exist for WINCE,
28808** it's important to not reference them for WINCE builds.
28809*/
28810#if SQLITE_OS_WINCE==0
28811  }else{
28812    do{
28813      DeleteFileA(zConverted);
28814    }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
28815               || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
28816           && (++cnt < MX_DELETION_ATTEMPTS)
28817           && (Sleep(100), 1) );
28818#endif
28819  }
28820  free(zConverted);
28821  OSTRACE2("DELETE \"%s\"\n", zFilename);
28822  return (   (rc == INVALID_FILE_ATTRIBUTES)
28823          && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
28824}
28825
28826/*
28827** Check the existance and status of a file.
28828*/
28829static int winAccess(
28830  sqlite3_vfs *pVfs,         /* Not used on win32 */
28831  const char *zFilename,     /* Name of file to check */
28832  int flags,                 /* Type of test to make on this file */
28833  int *pResOut               /* OUT: Result */
28834){
28835  DWORD attr;
28836  int rc = 0;
28837  void *zConverted = convertUtf8Filename(zFilename);
28838  UNUSED_PARAMETER(pVfs);
28839  if( zConverted==0 ){
28840    return SQLITE_NOMEM;
28841  }
28842  if( isNT() ){
28843    attr = GetFileAttributesW((WCHAR*)zConverted);
28844/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28845** Since the ASCII version of these Windows API do not exist for WINCE,
28846** it's important to not reference them for WINCE builds.
28847*/
28848#if SQLITE_OS_WINCE==0
28849  }else{
28850    attr = GetFileAttributesA((char*)zConverted);
28851#endif
28852  }
28853  free(zConverted);
28854  switch( flags ){
28855    case SQLITE_ACCESS_READ:
28856    case SQLITE_ACCESS_EXISTS:
28857      rc = attr!=INVALID_FILE_ATTRIBUTES;
28858      break;
28859    case SQLITE_ACCESS_READWRITE:
28860      rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
28861      break;
28862    default:
28863      assert(!"Invalid flags argument");
28864  }
28865  *pResOut = rc;
28866  return SQLITE_OK;
28867}
28868
28869
28870/*
28871** Turn a relative pathname into a full pathname.  Write the full
28872** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
28873** bytes in size.
28874*/
28875static int winFullPathname(
28876  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
28877  const char *zRelative,        /* Possibly relative input path */
28878  int nFull,                    /* Size of output buffer in bytes */
28879  char *zFull                   /* Output buffer */
28880){
28881
28882#if defined(__CYGWIN__)
28883  UNUSED_PARAMETER(nFull);
28884  cygwin_conv_to_full_win32_path(zRelative, zFull);
28885  return SQLITE_OK;
28886#endif
28887
28888#if SQLITE_OS_WINCE
28889  UNUSED_PARAMETER(nFull);
28890  /* WinCE has no concept of a relative pathname, or so I am told. */
28891  sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
28892  return SQLITE_OK;
28893#endif
28894
28895#if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
28896  int nByte;
28897  void *zConverted;
28898  char *zOut;
28899  UNUSED_PARAMETER(nFull);
28900  zConverted = convertUtf8Filename(zRelative);
28901  if( isNT() ){
28902    WCHAR *zTemp;
28903    nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
28904    zTemp = malloc( nByte*sizeof(zTemp[0]) );
28905    if( zTemp==0 ){
28906      free(zConverted);
28907      return SQLITE_NOMEM;
28908    }
28909    GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
28910    free(zConverted);
28911    zOut = unicodeToUtf8(zTemp);
28912    free(zTemp);
28913/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28914** Since the ASCII version of these Windows API do not exist for WINCE,
28915** it's important to not reference them for WINCE builds.
28916*/
28917#if SQLITE_OS_WINCE==0
28918  }else{
28919    char *zTemp;
28920    nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
28921    zTemp = malloc( nByte*sizeof(zTemp[0]) );
28922    if( zTemp==0 ){
28923      free(zConverted);
28924      return SQLITE_NOMEM;
28925    }
28926    GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
28927    free(zConverted);
28928    zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
28929    free(zTemp);
28930#endif
28931  }
28932  if( zOut ){
28933    sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
28934    free(zOut);
28935    return SQLITE_OK;
28936  }else{
28937    return SQLITE_NOMEM;
28938  }
28939#endif
28940}
28941
28942/*
28943** Get the sector size of the device used to store
28944** file.
28945*/
28946static int getSectorSize(
28947    sqlite3_vfs *pVfs,
28948    const char *zRelative     /* UTF-8 file name */
28949){
28950  DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
28951  /* GetDiskFreeSpace is not supported under WINCE */
28952#if SQLITE_OS_WINCE
28953  UNUSED_PARAMETER(pVfs);
28954  UNUSED_PARAMETER(zRelative);
28955#else
28956  char zFullpath[MAX_PATH+1];
28957  int rc;
28958  DWORD dwRet = 0;
28959  DWORD dwDummy;
28960
28961  /*
28962  ** We need to get the full path name of the file
28963  ** to get the drive letter to look up the sector
28964  ** size.
28965  */
28966  rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
28967  if( rc == SQLITE_OK )
28968  {
28969    void *zConverted = convertUtf8Filename(zFullpath);
28970    if( zConverted ){
28971      if( isNT() ){
28972        /* trim path to just drive reference */
28973        WCHAR *p = zConverted;
28974        for(;*p;p++){
28975          if( *p == '\\' ){
28976            *p = '\0';
28977            break;
28978          }
28979        }
28980        dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
28981                                  &dwDummy,
28982                                  &bytesPerSector,
28983                                  &dwDummy,
28984                                  &dwDummy);
28985      }else{
28986        /* trim path to just drive reference */
28987        char *p = (char *)zConverted;
28988        for(;*p;p++){
28989          if( *p == '\\' ){
28990            *p = '\0';
28991            break;
28992          }
28993        }
28994        dwRet = GetDiskFreeSpaceA((char*)zConverted,
28995                                  &dwDummy,
28996                                  &bytesPerSector,
28997                                  &dwDummy,
28998                                  &dwDummy);
28999      }
29000      free(zConverted);
29001    }
29002    if( !dwRet ){
29003      bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
29004    }
29005  }
29006#endif
29007  return (int) bytesPerSector;
29008}
29009
29010#ifndef SQLITE_OMIT_LOAD_EXTENSION
29011/*
29012** Interfaces for opening a shared library, finding entry points
29013** within the shared library, and closing the shared library.
29014*/
29015/*
29016** Interfaces for opening a shared library, finding entry points
29017** within the shared library, and closing the shared library.
29018*/
29019static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
29020  HANDLE h;
29021  void *zConverted = convertUtf8Filename(zFilename);
29022  UNUSED_PARAMETER(pVfs);
29023  if( zConverted==0 ){
29024    return 0;
29025  }
29026  if( isNT() ){
29027    h = LoadLibraryW((WCHAR*)zConverted);
29028/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
29029** Since the ASCII version of these Windows API do not exist for WINCE,
29030** it's important to not reference them for WINCE builds.
29031*/
29032#if SQLITE_OS_WINCE==0
29033  }else{
29034    h = LoadLibraryA((char*)zConverted);
29035#endif
29036  }
29037  free(zConverted);
29038  return (void*)h;
29039}
29040static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
29041  UNUSED_PARAMETER(pVfs);
29042  getLastErrorMsg(nBuf, zBufOut);
29043}
29044void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
29045  UNUSED_PARAMETER(pVfs);
29046#if SQLITE_OS_WINCE
29047  /* The GetProcAddressA() routine is only available on wince. */
29048  return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
29049#else
29050  /* All other windows platforms expect GetProcAddress() to take
29051  ** an Ansi string regardless of the _UNICODE setting */
29052  return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
29053#endif
29054}
29055void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
29056  UNUSED_PARAMETER(pVfs);
29057  FreeLibrary((HANDLE)pHandle);
29058}
29059#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
29060  #define winDlOpen  0
29061  #define winDlError 0
29062  #define winDlSym   0
29063  #define winDlClose 0
29064#endif
29065
29066
29067/*
29068** Write up to nBuf bytes of randomness into zBuf.
29069*/
29070static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
29071  int n = 0;
29072  UNUSED_PARAMETER(pVfs);
29073#if defined(SQLITE_TEST)
29074  n = nBuf;
29075  memset(zBuf, 0, nBuf);
29076#else
29077  if( sizeof(SYSTEMTIME)<=nBuf-n ){
29078    SYSTEMTIME x;
29079    GetSystemTime(&x);
29080    memcpy(&zBuf[n], &x, sizeof(x));
29081    n += sizeof(x);
29082  }
29083  if( sizeof(DWORD)<=nBuf-n ){
29084    DWORD pid = GetCurrentProcessId();
29085    memcpy(&zBuf[n], &pid, sizeof(pid));
29086    n += sizeof(pid);
29087  }
29088  if( sizeof(DWORD)<=nBuf-n ){
29089    DWORD cnt = GetTickCount();
29090    memcpy(&zBuf[n], &cnt, sizeof(cnt));
29091    n += sizeof(cnt);
29092  }
29093  if( sizeof(LARGE_INTEGER)<=nBuf-n ){
29094    LARGE_INTEGER i;
29095    QueryPerformanceCounter(&i);
29096    memcpy(&zBuf[n], &i, sizeof(i));
29097    n += sizeof(i);
29098  }
29099#endif
29100  return n;
29101}
29102
29103
29104/*
29105** Sleep for a little while.  Return the amount of time slept.
29106*/
29107static int winSleep(sqlite3_vfs *pVfs, int microsec){
29108  Sleep((microsec+999)/1000);
29109  UNUSED_PARAMETER(pVfs);
29110  return ((microsec+999)/1000)*1000;
29111}
29112
29113/*
29114** The following variable, if set to a non-zero value, becomes the result
29115** returned from sqlite3OsCurrentTime().  This is used for testing.
29116*/
29117#ifdef SQLITE_TEST
29118SQLITE_API int sqlite3_current_time = 0;
29119#endif
29120
29121/*
29122** Find the current time (in Universal Coordinated Time).  Write the
29123** current time and date as a Julian Day number into *prNow and
29124** return 0.  Return 1 if the time and date cannot be found.
29125*/
29126int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
29127  FILETIME ft;
29128  /* FILETIME structure is a 64-bit value representing the number of
29129     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
29130  */
29131  sqlite3_int64 timeW;   /* Whole days */
29132  sqlite3_int64 timeF;   /* Fractional Days */
29133
29134  /* Number of 100-nanosecond intervals in a single day */
29135  static const sqlite3_int64 ntuPerDay =
29136      10000000*(sqlite3_int64)86400;
29137
29138  /* Number of 100-nanosecond intervals in half of a day */
29139  static const sqlite3_int64 ntuPerHalfDay =
29140      10000000*(sqlite3_int64)43200;
29141
29142  /* 2^32 - to avoid use of LL and warnings in gcc */
29143  static const sqlite3_int64 max32BitValue =
29144      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
29145
29146#if SQLITE_OS_WINCE
29147  SYSTEMTIME time;
29148  GetSystemTime(&time);
29149  /* if SystemTimeToFileTime() fails, it returns zero. */
29150  if (!SystemTimeToFileTime(&time,&ft)){
29151    return 1;
29152  }
29153#else
29154  GetSystemTimeAsFileTime( &ft );
29155#endif
29156  UNUSED_PARAMETER(pVfs);
29157  timeW = (((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + (sqlite3_int64)ft.dwLowDateTime;
29158  timeF = timeW % ntuPerDay;          /* fractional days (100-nanoseconds) */
29159  timeW = timeW / ntuPerDay;          /* whole days */
29160  timeW = timeW + 2305813;            /* add whole days (from 2305813.5) */
29161  timeF = timeF + ntuPerHalfDay;      /* add half a day (from 2305813.5) */
29162  timeW = timeW + (timeF/ntuPerDay);  /* add whole day if half day made one */
29163  timeF = timeF % ntuPerDay;          /* compute new fractional days */
29164  *prNow = (double)timeW + ((double)timeF / (double)ntuPerDay);
29165#ifdef SQLITE_TEST
29166  if( sqlite3_current_time ){
29167    *prNow = ((double)sqlite3_current_time + (double)43200) / (double)86400 + (double)2440587;
29168  }
29169#endif
29170  return 0;
29171}
29172
29173/*
29174** The idea is that this function works like a combination of
29175** GetLastError() and FormatMessage() on windows (or errno and
29176** strerror_r() on unix). After an error is returned by an OS
29177** function, SQLite calls this function with zBuf pointing to
29178** a buffer of nBuf bytes. The OS layer should populate the
29179** buffer with a nul-terminated UTF-8 encoded error message
29180** describing the last IO error to have occurred within the calling
29181** thread.
29182**
29183** If the error message is too large for the supplied buffer,
29184** it should be truncated. The return value of xGetLastError
29185** is zero if the error message fits in the buffer, or non-zero
29186** otherwise (if the message was truncated). If non-zero is returned,
29187** then it is not necessary to include the nul-terminator character
29188** in the output buffer.
29189**
29190** Not supplying an error message will have no adverse effect
29191** on SQLite. It is fine to have an implementation that never
29192** returns an error message:
29193**
29194**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
29195**     assert(zBuf[0]=='\0');
29196**     return 0;
29197**   }
29198**
29199** However if an error message is supplied, it will be incorporated
29200** by sqlite into the error message available to the user using
29201** sqlite3_errmsg(), possibly making IO errors easier to debug.
29202*/
29203static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
29204  UNUSED_PARAMETER(pVfs);
29205  return getLastErrorMsg(nBuf, zBuf);
29206}
29207
29208/*
29209** Initialize and deinitialize the operating system interface.
29210*/
29211SQLITE_API int sqlite3_os_init(void){
29212  static sqlite3_vfs winVfs = {
29213    1,                 /* iVersion */
29214    sizeof(winFile),   /* szOsFile */
29215    MAX_PATH,          /* mxPathname */
29216    0,                 /* pNext */
29217    "win32",           /* zName */
29218    0,                 /* pAppData */
29219
29220    winOpen,           /* xOpen */
29221    winDelete,         /* xDelete */
29222    winAccess,         /* xAccess */
29223    winFullPathname,   /* xFullPathname */
29224    winDlOpen,         /* xDlOpen */
29225    winDlError,        /* xDlError */
29226    winDlSym,          /* xDlSym */
29227    winDlClose,        /* xDlClose */
29228    winRandomness,     /* xRandomness */
29229    winSleep,          /* xSleep */
29230    winCurrentTime,    /* xCurrentTime */
29231    winGetLastError    /* xGetLastError */
29232  };
29233
29234  sqlite3_vfs_register(&winVfs, 1);
29235  return SQLITE_OK;
29236}
29237SQLITE_API int sqlite3_os_end(void){
29238  return SQLITE_OK;
29239}
29240
29241#endif /* SQLITE_OS_WIN */
29242
29243/************** End of os_win.c **********************************************/
29244/************** Begin file bitvec.c ******************************************/
29245/*
29246** 2008 February 16
29247**
29248** The author disclaims copyright to this source code.  In place of
29249** a legal notice, here is a blessing:
29250**
29251**    May you do good and not evil.
29252**    May you find forgiveness for yourself and forgive others.
29253**    May you share freely, never taking more than you give.
29254**
29255*************************************************************************
29256** This file implements an object that represents a fixed-length
29257** bitmap.  Bits are numbered starting with 1.
29258**
29259** A bitmap is used to record which pages of a database file have been
29260** journalled during a transaction, or which pages have the "dont-write"
29261** property.  Usually only a few pages are meet either condition.
29262** So the bitmap is usually sparse and has low cardinality.
29263** But sometimes (for example when during a DROP of a large table) most
29264** or all of the pages in a database can get journalled.  In those cases,
29265** the bitmap becomes dense with high cardinality.  The algorithm needs
29266** to handle both cases well.
29267**
29268** The size of the bitmap is fixed when the object is created.
29269**
29270** All bits are clear when the bitmap is created.  Individual bits
29271** may be set or cleared one at a time.
29272**
29273** Test operations are about 100 times more common that set operations.
29274** Clear operations are exceedingly rare.  There are usually between
29275** 5 and 500 set operations per Bitvec object, though the number of sets can
29276** sometimes grow into tens of thousands or larger.  The size of the
29277** Bitvec object is the number of pages in the database file at the
29278** start of a transaction, and is thus usually less than a few thousand,
29279** but can be as large as 2 billion for a really big database.
29280*/
29281
29282/* Size of the Bitvec structure in bytes. */
29283#define BITVEC_SZ        (sizeof(void*)*128)  /* 512 on 32bit.  1024 on 64bit */
29284
29285/* Round the union size down to the nearest pointer boundary, since that's how
29286** it will be aligned within the Bitvec struct. */
29287#define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
29288
29289/* Type of the array "element" for the bitmap representation.
29290** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
29291** Setting this to the "natural word" size of your CPU may improve
29292** performance. */
29293#define BITVEC_TELEM     u8
29294/* Size, in bits, of the bitmap element. */
29295#define BITVEC_SZELEM    8
29296/* Number of elements in a bitmap array. */
29297#define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
29298/* Number of bits in the bitmap array. */
29299#define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
29300
29301/* Number of u32 values in hash table. */
29302#define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
29303/* Maximum number of entries in hash table before
29304** sub-dividing and re-hashing. */
29305#define BITVEC_MXHASH    (BITVEC_NINT/2)
29306/* Hashing function for the aHash representation.
29307** Empirical testing showed that the *37 multiplier
29308** (an arbitrary prime)in the hash function provided
29309** no fewer collisions than the no-op *1. */
29310#define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
29311
29312#define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
29313
29314
29315/*
29316** A bitmap is an instance of the following structure.
29317**
29318** This bitmap records the existance of zero or more bits
29319** with values between 1 and iSize, inclusive.
29320**
29321** There are three possible representations of the bitmap.
29322** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
29323** bitmap.  The least significant bit is bit 1.
29324**
29325** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
29326** a hash table that will hold up to BITVEC_MXHASH distinct values.
29327**
29328** Otherwise, the value i is redirected into one of BITVEC_NPTR
29329** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
29330** handles up to iDivisor separate values of i.  apSub[0] holds
29331** values between 1 and iDivisor.  apSub[1] holds values between
29332** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
29333** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
29334** to hold deal with values between 1 and iDivisor.
29335*/
29336struct Bitvec {
29337  u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
29338  u32 nSet;       /* Number of bits that are set - only valid for aHash
29339                  ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
29340                  ** this would be 125. */
29341  u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
29342                  /* Should >=0 for apSub element. */
29343                  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
29344                  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
29345  union {
29346    BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
29347    u32 aHash[BITVEC_NINT];      /* Hash table representation */
29348    Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
29349  } u;
29350};
29351
29352/*
29353** Create a new bitmap object able to handle bits between 0 and iSize,
29354** inclusive.  Return a pointer to the new object.  Return NULL if
29355** malloc fails.
29356*/
29357SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
29358  Bitvec *p;
29359  assert( sizeof(*p)==BITVEC_SZ );
29360  p = sqlite3MallocZero( sizeof(*p) );
29361  if( p ){
29362    p->iSize = iSize;
29363  }
29364  return p;
29365}
29366
29367/*
29368** Check to see if the i-th bit is set.  Return true or false.
29369** If p is NULL (if the bitmap has not been created) or if
29370** i is out of range, then return false.
29371*/
29372SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
29373  if( p==0 ) return 0;
29374  if( i>p->iSize || i==0 ) return 0;
29375  i--;
29376  while( p->iDivisor ){
29377    u32 bin = i/p->iDivisor;
29378    i = i%p->iDivisor;
29379    p = p->u.apSub[bin];
29380    if (!p) {
29381      return 0;
29382    }
29383  }
29384  if( p->iSize<=BITVEC_NBIT ){
29385    return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
29386  } else{
29387    u32 h = BITVEC_HASH(i++);
29388    while( p->u.aHash[h] ){
29389      if( p->u.aHash[h]==i ) return 1;
29390      h = (h+1) % BITVEC_NINT;
29391    }
29392    return 0;
29393  }
29394}
29395
29396/*
29397** Set the i-th bit.  Return 0 on success and an error code if
29398** anything goes wrong.
29399**
29400** This routine might cause sub-bitmaps to be allocated.  Failing
29401** to get the memory needed to hold the sub-bitmap is the only
29402** that can go wrong with an insert, assuming p and i are valid.
29403**
29404** The calling function must ensure that p is a valid Bitvec object
29405** and that the value for "i" is within range of the Bitvec object.
29406** Otherwise the behavior is undefined.
29407*/
29408SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
29409  u32 h;
29410  if( p==0 ) return SQLITE_OK;
29411  assert( i>0 );
29412  assert( i<=p->iSize );
29413  i--;
29414  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
29415    u32 bin = i/p->iDivisor;
29416    i = i%p->iDivisor;
29417    if( p->u.apSub[bin]==0 ){
29418      p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
29419      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
29420    }
29421    p = p->u.apSub[bin];
29422  }
29423  if( p->iSize<=BITVEC_NBIT ){
29424    p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
29425    return SQLITE_OK;
29426  }
29427  h = BITVEC_HASH(i++);
29428  /* if there wasn't a hash collision, and this doesn't */
29429  /* completely fill the hash, then just add it without */
29430  /* worring about sub-dividing and re-hashing. */
29431  if( !p->u.aHash[h] ){
29432    if (p->nSet<(BITVEC_NINT-1)) {
29433      goto bitvec_set_end;
29434    } else {
29435      goto bitvec_set_rehash;
29436    }
29437  }
29438  /* there was a collision, check to see if it's already */
29439  /* in hash, if not, try to find a spot for it */
29440  do {
29441    if( p->u.aHash[h]==i ) return SQLITE_OK;
29442    h++;
29443    if( h>=BITVEC_NINT ) h = 0;
29444  } while( p->u.aHash[h] );
29445  /* we didn't find it in the hash.  h points to the first */
29446  /* available free spot. check to see if this is going to */
29447  /* make our hash too "full".  */
29448bitvec_set_rehash:
29449  if( p->nSet>=BITVEC_MXHASH ){
29450    unsigned int j;
29451    int rc;
29452    u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
29453    if( aiValues==0 ){
29454      return SQLITE_NOMEM;
29455    }else{
29456      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
29457      memset(p->u.apSub, 0, sizeof(p->u.apSub));
29458      p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
29459      rc = sqlite3BitvecSet(p, i);
29460      for(j=0; j<BITVEC_NINT; j++){
29461        if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
29462      }
29463      sqlite3StackFree(0, aiValues);
29464      return rc;
29465    }
29466  }
29467bitvec_set_end:
29468  p->nSet++;
29469  p->u.aHash[h] = i;
29470  return SQLITE_OK;
29471}
29472
29473/*
29474** Clear the i-th bit.
29475**
29476** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
29477** that BitvecClear can use to rebuilt its hash table.
29478*/
29479SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
29480  if( p==0 ) return;
29481  assert( i>0 );
29482  i--;
29483  while( p->iDivisor ){
29484    u32 bin = i/p->iDivisor;
29485    i = i%p->iDivisor;
29486    p = p->u.apSub[bin];
29487    if (!p) {
29488      return;
29489    }
29490  }
29491  if( p->iSize<=BITVEC_NBIT ){
29492    p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
29493  }else{
29494    unsigned int j;
29495    u32 *aiValues = pBuf;
29496    memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
29497    memset(p->u.aHash, 0, sizeof(p->u.aHash));
29498    p->nSet = 0;
29499    for(j=0; j<BITVEC_NINT; j++){
29500      if( aiValues[j] && aiValues[j]!=(i+1) ){
29501        u32 h = BITVEC_HASH(aiValues[j]-1);
29502        p->nSet++;
29503        while( p->u.aHash[h] ){
29504          h++;
29505          if( h>=BITVEC_NINT ) h = 0;
29506        }
29507        p->u.aHash[h] = aiValues[j];
29508      }
29509    }
29510  }
29511}
29512
29513/*
29514** Destroy a bitmap object.  Reclaim all memory used.
29515*/
29516SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
29517  if( p==0 ) return;
29518  if( p->iDivisor ){
29519    unsigned int i;
29520    for(i=0; i<BITVEC_NPTR; i++){
29521      sqlite3BitvecDestroy(p->u.apSub[i]);
29522    }
29523  }
29524  sqlite3_free(p);
29525}
29526
29527/*
29528** Return the value of the iSize parameter specified when Bitvec *p
29529** was created.
29530*/
29531SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
29532  return p->iSize;
29533}
29534
29535#ifndef SQLITE_OMIT_BUILTIN_TEST
29536/*
29537** Let V[] be an array of unsigned characters sufficient to hold
29538** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
29539** Then the following macros can be used to set, clear, or test
29540** individual bits within V.
29541*/
29542#define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
29543#define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
29544#define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
29545
29546/*
29547** This routine runs an extensive test of the Bitvec code.
29548**
29549** The input is an array of integers that acts as a program
29550** to test the Bitvec.  The integers are opcodes followed
29551** by 0, 1, or 3 operands, depending on the opcode.  Another
29552** opcode follows immediately after the last operand.
29553**
29554** There are 6 opcodes numbered from 0 through 5.  0 is the
29555** "halt" opcode and causes the test to end.
29556**
29557**    0          Halt and return the number of errors
29558**    1 N S X    Set N bits beginning with S and incrementing by X
29559**    2 N S X    Clear N bits beginning with S and incrementing by X
29560**    3 N        Set N randomly chosen bits
29561**    4 N        Clear N randomly chosen bits
29562**    5 N S X    Set N bits from S increment X in array only, not in bitvec
29563**
29564** The opcodes 1 through 4 perform set and clear operations are performed
29565** on both a Bitvec object and on a linear array of bits obtained from malloc.
29566** Opcode 5 works on the linear array only, not on the Bitvec.
29567** Opcode 5 is used to deliberately induce a fault in order to
29568** confirm that error detection works.
29569**
29570** At the conclusion of the test the linear array is compared
29571** against the Bitvec object.  If there are any differences,
29572** an error is returned.  If they are the same, zero is returned.
29573**
29574** If a memory allocation error occurs, return -1.
29575*/
29576SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
29577  Bitvec *pBitvec = 0;
29578  unsigned char *pV = 0;
29579  int rc = -1;
29580  int i, nx, pc, op;
29581  void *pTmpSpace;
29582
29583  /* Allocate the Bitvec to be tested and a linear array of
29584  ** bits to act as the reference */
29585  pBitvec = sqlite3BitvecCreate( sz );
29586  pV = sqlite3_malloc( (sz+7)/8 + 1 );
29587  pTmpSpace = sqlite3_malloc(BITVEC_SZ);
29588  if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
29589  memset(pV, 0, (sz+7)/8 + 1);
29590
29591  /* NULL pBitvec tests */
29592  sqlite3BitvecSet(0, 1);
29593  sqlite3BitvecClear(0, 1, pTmpSpace);
29594
29595  /* Run the program */
29596  pc = 0;
29597  while( (op = aOp[pc])!=0 ){
29598    switch( op ){
29599      case 1:
29600      case 2:
29601      case 5: {
29602        nx = 4;
29603        i = aOp[pc+2] - 1;
29604        aOp[pc+2] += aOp[pc+3];
29605        break;
29606      }
29607      case 3:
29608      case 4:
29609      default: {
29610        nx = 2;
29611        sqlite3_randomness(sizeof(i), &i);
29612        break;
29613      }
29614    }
29615    if( (--aOp[pc+1]) > 0 ) nx = 0;
29616    pc += nx;
29617    i = (i & 0x7fffffff)%sz;
29618    if( (op & 1)!=0 ){
29619      SETBIT(pV, (i+1));
29620      if( op!=5 ){
29621        if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
29622      }
29623    }else{
29624      CLEARBIT(pV, (i+1));
29625      sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
29626    }
29627  }
29628
29629  /* Test to make sure the linear array exactly matches the
29630  ** Bitvec object.  Start with the assumption that they do
29631  ** match (rc==0).  Change rc to non-zero if a discrepancy
29632  ** is found.
29633  */
29634  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
29635          + sqlite3BitvecTest(pBitvec, 0)
29636          + (sqlite3BitvecSize(pBitvec) - sz);
29637  for(i=1; i<=sz; i++){
29638    if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
29639      rc = i;
29640      break;
29641    }
29642  }
29643
29644  /* Free allocated structure */
29645bitvec_end:
29646  sqlite3_free(pTmpSpace);
29647  sqlite3_free(pV);
29648  sqlite3BitvecDestroy(pBitvec);
29649  return rc;
29650}
29651#endif /* SQLITE_OMIT_BUILTIN_TEST */
29652
29653/************** End of bitvec.c **********************************************/
29654/************** Begin file pcache.c ******************************************/
29655/*
29656** 2008 August 05
29657**
29658** The author disclaims copyright to this source code.  In place of
29659** a legal notice, here is a blessing:
29660**
29661**    May you do good and not evil.
29662**    May you find forgiveness for yourself and forgive others.
29663**    May you share freely, never taking more than you give.
29664**
29665*************************************************************************
29666** This file implements that page cache.
29667*/
29668
29669/*
29670** A complete page cache is an instance of this structure.
29671*/
29672struct PCache {
29673  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
29674  PgHdr *pSynced;                     /* Last synced page in dirty page list */
29675  int nRef;                           /* Number of referenced pages */
29676  int nMax;                           /* Configured cache size */
29677  int szPage;                         /* Size of every page in this cache */
29678  int szExtra;                        /* Size of extra space for each page */
29679  int bPurgeable;                     /* True if pages are on backing store */
29680  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
29681  void *pStress;                      /* Argument to xStress */
29682  sqlite3_pcache *pCache;             /* Pluggable cache module */
29683  PgHdr *pPage1;                      /* Reference to page 1 */
29684};
29685
29686/*
29687** Some of the assert() macros in this code are too expensive to run
29688** even during normal debugging.  Use them only rarely on long-running
29689** tests.  Enable the expensive asserts using the
29690** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
29691*/
29692#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
29693# define expensive_assert(X)  assert(X)
29694#else
29695# define expensive_assert(X)
29696#endif
29697
29698/********************************** Linked List Management ********************/
29699
29700#if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
29701/*
29702** Check that the pCache->pSynced variable is set correctly. If it
29703** is not, either fail an assert or return zero. Otherwise, return
29704** non-zero. This is only used in debugging builds, as follows:
29705**
29706**   expensive_assert( pcacheCheckSynced(pCache) );
29707*/
29708static int pcacheCheckSynced(PCache *pCache){
29709  PgHdr *p;
29710  for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
29711    assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
29712  }
29713  return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
29714}
29715#endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
29716
29717/*
29718** Remove page pPage from the list of dirty pages.
29719*/
29720static void pcacheRemoveFromDirtyList(PgHdr *pPage){
29721  PCache *p = pPage->pCache;
29722
29723  assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
29724  assert( pPage->pDirtyPrev || pPage==p->pDirty );
29725
29726  /* Update the PCache1.pSynced variable if necessary. */
29727  if( p->pSynced==pPage ){
29728    PgHdr *pSynced = pPage->pDirtyPrev;
29729    while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
29730      pSynced = pSynced->pDirtyPrev;
29731    }
29732    p->pSynced = pSynced;
29733  }
29734
29735  if( pPage->pDirtyNext ){
29736    pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
29737  }else{
29738    assert( pPage==p->pDirtyTail );
29739    p->pDirtyTail = pPage->pDirtyPrev;
29740  }
29741  if( pPage->pDirtyPrev ){
29742    pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
29743  }else{
29744    assert( pPage==p->pDirty );
29745    p->pDirty = pPage->pDirtyNext;
29746  }
29747  pPage->pDirtyNext = 0;
29748  pPage->pDirtyPrev = 0;
29749
29750  expensive_assert( pcacheCheckSynced(p) );
29751}
29752
29753/*
29754** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
29755** pPage).
29756*/
29757static void pcacheAddToDirtyList(PgHdr *pPage){
29758  PCache *p = pPage->pCache;
29759
29760  assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
29761
29762  pPage->pDirtyNext = p->pDirty;
29763  if( pPage->pDirtyNext ){
29764    assert( pPage->pDirtyNext->pDirtyPrev==0 );
29765    pPage->pDirtyNext->pDirtyPrev = pPage;
29766  }
29767  p->pDirty = pPage;
29768  if( !p->pDirtyTail ){
29769    p->pDirtyTail = pPage;
29770  }
29771  if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
29772    p->pSynced = pPage;
29773  }
29774  expensive_assert( pcacheCheckSynced(p) );
29775}
29776
29777/*
29778** Wrapper around the pluggable caches xUnpin method. If the cache is
29779** being used for an in-memory database, this function is a no-op.
29780*/
29781static void pcacheUnpin(PgHdr *p){
29782  PCache *pCache = p->pCache;
29783  if( pCache->bPurgeable ){
29784    if( p->pgno==1 ){
29785      pCache->pPage1 = 0;
29786    }
29787    sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
29788  }
29789}
29790
29791/*************************************************** General Interfaces ******
29792**
29793** Initialize and shutdown the page cache subsystem. Neither of these
29794** functions are threadsafe.
29795*/
29796SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
29797  if( sqlite3GlobalConfig.pcache.xInit==0 ){
29798    sqlite3PCacheSetDefault();
29799  }
29800  return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
29801}
29802SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
29803  if( sqlite3GlobalConfig.pcache.xShutdown ){
29804    sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
29805  }
29806}
29807
29808/*
29809** Return the size in bytes of a PCache object.
29810*/
29811SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
29812
29813/*
29814** Create a new PCache object. Storage space to hold the object
29815** has already been allocated and is passed in as the p pointer.
29816** The caller discovers how much space needs to be allocated by
29817** calling sqlite3PcacheSize().
29818*/
29819SQLITE_PRIVATE void sqlite3PcacheOpen(
29820  int szPage,                  /* Size of every page */
29821  int szExtra,                 /* Extra space associated with each page */
29822  int bPurgeable,              /* True if pages are on backing store */
29823  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
29824  void *pStress,               /* Argument to xStress */
29825  PCache *p                    /* Preallocated space for the PCache */
29826){
29827  memset(p, 0, sizeof(PCache));
29828  p->szPage = szPage;
29829  p->szExtra = szExtra;
29830  p->bPurgeable = bPurgeable;
29831  p->xStress = xStress;
29832  p->pStress = pStress;
29833  p->nMax = 100;
29834}
29835
29836/*
29837** Change the page size for PCache object. The caller must ensure that there
29838** are no outstanding page references when this function is called.
29839*/
29840SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
29841  assert( pCache->nRef==0 && pCache->pDirty==0 );
29842  if( pCache->pCache ){
29843    sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
29844    pCache->pCache = 0;
29845    pCache->pPage1 = 0;
29846  }
29847  pCache->szPage = szPage;
29848}
29849
29850/*
29851** Try to obtain a page from the cache.
29852*/
29853SQLITE_PRIVATE int sqlite3PcacheFetch(
29854  PCache *pCache,       /* Obtain the page from this cache */
29855  Pgno pgno,            /* Page number to obtain */
29856  int createFlag,       /* If true, create page if it does not exist already */
29857  PgHdr **ppPage        /* Write the page here */
29858){
29859  PgHdr *pPage = 0;
29860  int eCreate;
29861
29862  assert( pCache!=0 );
29863  assert( createFlag==1 || createFlag==0 );
29864  assert( pgno>0 );
29865
29866  /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
29867  ** allocate it now.
29868  */
29869  if( !pCache->pCache && createFlag ){
29870    sqlite3_pcache *p;
29871    int nByte;
29872    nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
29873    p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
29874    if( !p ){
29875      return SQLITE_NOMEM;
29876    }
29877    sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
29878    pCache->pCache = p;
29879  }
29880
29881  eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
29882  if( pCache->pCache ){
29883    pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
29884  }
29885
29886  if( !pPage && eCreate==1 ){
29887    PgHdr *pPg;
29888
29889    /* Find a dirty page to write-out and recycle. First try to find a
29890    ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
29891    ** cleared), but if that is not possible settle for any other
29892    ** unreferenced dirty page.
29893    */
29894    expensive_assert( pcacheCheckSynced(pCache) );
29895    for(pPg=pCache->pSynced;
29896        pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
29897        pPg=pPg->pDirtyPrev
29898    );
29899    pCache->pSynced = pPg;
29900    if( !pPg ){
29901      for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
29902    }
29903    if( pPg ){
29904      int rc;
29905      rc = pCache->xStress(pCache->pStress, pPg);
29906      if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
29907        return rc;
29908      }
29909    }
29910
29911    pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
29912  }
29913
29914  if( pPage ){
29915    if( !pPage->pData ){
29916      memset(pPage, 0, sizeof(PgHdr) + pCache->szExtra);
29917      pPage->pExtra = (void*)&pPage[1];
29918      pPage->pData = (void *)&((char *)pPage)[sizeof(PgHdr) + pCache->szExtra];
29919      pPage->pCache = pCache;
29920      pPage->pgno = pgno;
29921    }
29922    assert( pPage->pCache==pCache );
29923    assert( pPage->pgno==pgno );
29924    assert( pPage->pExtra==(void *)&pPage[1] );
29925
29926    if( 0==pPage->nRef ){
29927      pCache->nRef++;
29928    }
29929    pPage->nRef++;
29930    if( pgno==1 ){
29931      pCache->pPage1 = pPage;
29932    }
29933  }
29934  *ppPage = pPage;
29935  return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
29936}
29937
29938/*
29939** Decrement the reference count on a page. If the page is clean and the
29940** reference count drops to 0, then it is made elible for recycling.
29941*/
29942SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
29943  assert( p->nRef>0 );
29944  p->nRef--;
29945  if( p->nRef==0 ){
29946    PCache *pCache = p->pCache;
29947    pCache->nRef--;
29948    if( (p->flags&PGHDR_DIRTY)==0 ){
29949      pcacheUnpin(p);
29950    }else{
29951      /* Move the page to the head of the dirty list. */
29952      pcacheRemoveFromDirtyList(p);
29953      pcacheAddToDirtyList(p);
29954    }
29955  }
29956}
29957
29958/*
29959** Increase the reference count of a supplied page by 1.
29960*/
29961SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
29962  assert(p->nRef>0);
29963  p->nRef++;
29964}
29965
29966/*
29967** Drop a page from the cache. There must be exactly one reference to the
29968** page. This function deletes that reference, so after it returns the
29969** page pointed to by p is invalid.
29970*/
29971SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
29972  PCache *pCache;
29973  assert( p->nRef==1 );
29974  if( p->flags&PGHDR_DIRTY ){
29975    pcacheRemoveFromDirtyList(p);
29976  }
29977  pCache = p->pCache;
29978  pCache->nRef--;
29979  if( p->pgno==1 ){
29980    pCache->pPage1 = 0;
29981  }
29982  sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
29983}
29984
29985/*
29986** Make sure the page is marked as dirty. If it isn't dirty already,
29987** make it so.
29988*/
29989SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
29990  p->flags &= ~PGHDR_DONT_WRITE;
29991  assert( p->nRef>0 );
29992  if( 0==(p->flags & PGHDR_DIRTY) ){
29993    p->flags |= PGHDR_DIRTY;
29994    pcacheAddToDirtyList( p);
29995  }
29996}
29997
29998/*
29999** Make sure the page is marked as clean. If it isn't clean already,
30000** make it so.
30001*/
30002SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
30003  if( (p->flags & PGHDR_DIRTY) ){
30004    pcacheRemoveFromDirtyList(p);
30005    p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
30006    if( p->nRef==0 ){
30007      pcacheUnpin(p);
30008    }
30009  }
30010}
30011
30012/*
30013** Make every page in the cache clean.
30014*/
30015SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
30016  PgHdr *p;
30017  while( (p = pCache->pDirty)!=0 ){
30018    sqlite3PcacheMakeClean(p);
30019  }
30020}
30021
30022/*
30023** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
30024*/
30025SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
30026  PgHdr *p;
30027  for(p=pCache->pDirty; p; p=p->pDirtyNext){
30028    p->flags &= ~PGHDR_NEED_SYNC;
30029  }
30030  pCache->pSynced = pCache->pDirtyTail;
30031}
30032
30033/*
30034** Change the page number of page p to newPgno.
30035*/
30036SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
30037  PCache *pCache = p->pCache;
30038  assert( p->nRef>0 );
30039  assert( newPgno>0 );
30040  sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
30041  p->pgno = newPgno;
30042  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
30043    pcacheRemoveFromDirtyList(p);
30044    pcacheAddToDirtyList(p);
30045  }
30046}
30047
30048/*
30049** Drop every cache entry whose page number is greater than "pgno". The
30050** caller must ensure that there are no outstanding references to any pages
30051** other than page 1 with a page number greater than pgno.
30052**
30053** If there is a reference to page 1 and the pgno parameter passed to this
30054** function is 0, then the data area associated with page 1 is zeroed, but
30055** the page object is not dropped.
30056*/
30057SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
30058  if( pCache->pCache ){
30059    PgHdr *p;
30060    PgHdr *pNext;
30061    for(p=pCache->pDirty; p; p=pNext){
30062      pNext = p->pDirtyNext;
30063      if( p->pgno>pgno ){
30064        assert( p->flags&PGHDR_DIRTY );
30065        sqlite3PcacheMakeClean(p);
30066      }
30067    }
30068    if( pgno==0 && pCache->pPage1 ){
30069      memset(pCache->pPage1->pData, 0, pCache->szPage);
30070      pgno = 1;
30071    }
30072    sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
30073  }
30074}
30075
30076/*
30077** Close a cache.
30078*/
30079SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
30080  if( pCache->pCache ){
30081    sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
30082  }
30083}
30084
30085/*
30086** Discard the contents of the cache.
30087*/
30088SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
30089  sqlite3PcacheTruncate(pCache, 0);
30090}
30091
30092/*
30093** Merge two lists of pages connected by pDirty and in pgno order.
30094** Do not both fixing the pDirtyPrev pointers.
30095*/
30096static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
30097  PgHdr result, *pTail;
30098  pTail = &result;
30099  while( pA && pB ){
30100    if( pA->pgno<pB->pgno ){
30101      pTail->pDirty = pA;
30102      pTail = pA;
30103      pA = pA->pDirty;
30104    }else{
30105      pTail->pDirty = pB;
30106      pTail = pB;
30107      pB = pB->pDirty;
30108    }
30109  }
30110  if( pA ){
30111    pTail->pDirty = pA;
30112  }else if( pB ){
30113    pTail->pDirty = pB;
30114  }else{
30115    pTail->pDirty = 0;
30116  }
30117  return result.pDirty;
30118}
30119
30120/*
30121** Sort the list of pages in accending order by pgno.  Pages are
30122** connected by pDirty pointers.  The pDirtyPrev pointers are
30123** corrupted by this sort.
30124**
30125** Since there cannot be more than 2^31 distinct pages in a database,
30126** there cannot be more than 31 buckets required by the merge sorter.
30127** One extra bucket is added to catch overflow in case something
30128** ever changes to make the previous sentence incorrect.
30129*/
30130#define N_SORT_BUCKET  32
30131static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
30132  PgHdr *a[N_SORT_BUCKET], *p;
30133  int i;
30134  memset(a, 0, sizeof(a));
30135  while( pIn ){
30136    p = pIn;
30137    pIn = p->pDirty;
30138    p->pDirty = 0;
30139    for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
30140      if( a[i]==0 ){
30141        a[i] = p;
30142        break;
30143      }else{
30144        p = pcacheMergeDirtyList(a[i], p);
30145        a[i] = 0;
30146      }
30147    }
30148    if( NEVER(i==N_SORT_BUCKET-1) ){
30149      /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
30150      ** the input list.  But that is impossible.
30151      */
30152      a[i] = pcacheMergeDirtyList(a[i], p);
30153    }
30154  }
30155  p = a[0];
30156  for(i=1; i<N_SORT_BUCKET; i++){
30157    p = pcacheMergeDirtyList(p, a[i]);
30158  }
30159  return p;
30160}
30161
30162/*
30163** Return a list of all dirty pages in the cache, sorted by page number.
30164*/
30165SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
30166  PgHdr *p;
30167  for(p=pCache->pDirty; p; p=p->pDirtyNext){
30168    p->pDirty = p->pDirtyNext;
30169  }
30170  return pcacheSortDirtyList(pCache->pDirty);
30171}
30172
30173/*
30174** Return the total number of referenced pages held by the cache.
30175*/
30176SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
30177  return pCache->nRef;
30178}
30179
30180/*
30181** Return the number of references to the page supplied as an argument.
30182*/
30183SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
30184  return p->nRef;
30185}
30186
30187/*
30188** Return the total number of pages in the cache.
30189*/
30190SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
30191  int nPage = 0;
30192  if( pCache->pCache ){
30193    nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
30194  }
30195  return nPage;
30196}
30197
30198#ifdef SQLITE_TEST
30199/*
30200** Get the suggested cache-size value.
30201*/
30202SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
30203  return pCache->nMax;
30204}
30205#endif
30206
30207/*
30208** Set the suggested cache-size value.
30209*/
30210SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
30211  pCache->nMax = mxPage;
30212  if( pCache->pCache ){
30213    sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
30214  }
30215}
30216
30217#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
30218/*
30219** For all dirty pages currently in the cache, invoke the specified
30220** callback. This is only used if the SQLITE_CHECK_PAGES macro is
30221** defined.
30222*/
30223SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
30224  PgHdr *pDirty;
30225  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
30226    xIter(pDirty);
30227  }
30228}
30229#endif
30230
30231/************** End of pcache.c **********************************************/
30232/************** Begin file pcache1.c *****************************************/
30233/*
30234** 2008 November 05
30235**
30236** The author disclaims copyright to this source code.  In place of
30237** a legal notice, here is a blessing:
30238**
30239**    May you do good and not evil.
30240**    May you find forgiveness for yourself and forgive others.
30241**    May you share freely, never taking more than you give.
30242**
30243*************************************************************************
30244**
30245** This file implements the default page cache implementation (the
30246** sqlite3_pcache interface). It also contains part of the implementation
30247** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
30248** If the default page cache implementation is overriden, then neither of
30249** these two features are available.
30250*/
30251
30252
30253typedef struct PCache1 PCache1;
30254typedef struct PgHdr1 PgHdr1;
30255typedef struct PgFreeslot PgFreeslot;
30256
30257/* Pointers to structures of this type are cast and returned as
30258** opaque sqlite3_pcache* handles
30259*/
30260struct PCache1 {
30261  /* Cache configuration parameters. Page size (szPage) and the purgeable
30262  ** flag (bPurgeable) are set when the cache is created. nMax may be
30263  ** modified at any time by a call to the pcache1CacheSize() method.
30264  ** The global mutex must be held when accessing nMax.
30265  */
30266  int szPage;                         /* Size of allocated pages in bytes */
30267  int bPurgeable;                     /* True if cache is purgeable */
30268  unsigned int nMin;                  /* Minimum number of pages reserved */
30269  unsigned int nMax;                  /* Configured "cache_size" value */
30270
30271  /* Hash table of all pages. The following variables may only be accessed
30272  ** when the accessor is holding the global mutex (see pcache1EnterMutex()
30273  ** and pcache1LeaveMutex()).
30274  */
30275  unsigned int nRecyclable;           /* Number of pages in the LRU list */
30276  unsigned int nPage;                 /* Total number of pages in apHash */
30277  unsigned int nHash;                 /* Number of slots in apHash[] */
30278  PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
30279
30280  unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
30281};
30282
30283/*
30284** Each cache entry is represented by an instance of the following
30285** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated
30286** directly before this structure in memory (see the PGHDR1_TO_PAGE()
30287** macro below).
30288*/
30289struct PgHdr1 {
30290  unsigned int iKey;             /* Key value (page number) */
30291  PgHdr1 *pNext;                 /* Next in hash table chain */
30292  PCache1 *pCache;               /* Cache that currently owns this page */
30293  PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
30294  PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
30295};
30296
30297/*
30298** Free slots in the allocator used to divide up the buffer provided using
30299** the SQLITE_CONFIG_PAGECACHE mechanism.
30300*/
30301struct PgFreeslot {
30302  PgFreeslot *pNext;  /* Next free slot */
30303};
30304
30305/*
30306** Global data used by this cache.
30307*/
30308static SQLITE_WSD struct PCacheGlobal {
30309  sqlite3_mutex *mutex;               /* static mutex MUTEX_STATIC_LRU */
30310
30311  int nMaxPage;                       /* Sum of nMaxPage for purgeable caches */
30312  int nMinPage;                       /* Sum of nMinPage for purgeable caches */
30313  int nCurrentPage;                   /* Number of purgeable pages allocated */
30314  PgHdr1 *pLruHead, *pLruTail;        /* LRU list of unpinned pages */
30315
30316  /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
30317  int szSlot;                         /* Size of each free slot */
30318  void *pStart, *pEnd;                /* Bounds of pagecache malloc range */
30319  PgFreeslot *pFree;                  /* Free page blocks */
30320  int isInit;                         /* True if initialized */
30321} pcache1_g;
30322
30323/*
30324** All code in this file should access the global structure above via the
30325** alias "pcache1". This ensures that the WSD emulation is used when
30326** compiling for systems that do not support real WSD.
30327*/
30328#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
30329
30330/*
30331** When a PgHdr1 structure is allocated, the associated PCache1.szPage
30332** bytes of data are located directly before it in memory (i.e. the total
30333** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
30334** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
30335** an argument and returns a pointer to the associated block of szPage
30336** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
30337** a pointer to a block of szPage bytes of data and the return value is
30338** a pointer to the associated PgHdr1 structure.
30339**
30340**   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
30341*/
30342#define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
30343#define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
30344
30345/*
30346** Macros to enter and leave the global LRU mutex.
30347*/
30348#define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex)
30349#define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex)
30350
30351/******************************************************************************/
30352/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
30353
30354/*
30355** This function is called during initialization if a static buffer is
30356** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
30357** verb to sqlite3_config(). Parameter pBuf points to an allocation large
30358** enough to contain 'n' buffers of 'sz' bytes each.
30359*/
30360SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
30361  if( pcache1.isInit ){
30362    PgFreeslot *p;
30363    sz = ROUNDDOWN8(sz);
30364    pcache1.szSlot = sz;
30365    pcache1.pStart = pBuf;
30366    pcache1.pFree = 0;
30367    while( n-- ){
30368      p = (PgFreeslot*)pBuf;
30369      p->pNext = pcache1.pFree;
30370      pcache1.pFree = p;
30371      pBuf = (void*)&((char*)pBuf)[sz];
30372    }
30373    pcache1.pEnd = pBuf;
30374  }
30375}
30376
30377/*
30378** Malloc function used within this file to allocate space from the buffer
30379** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
30380** such buffer exists or there is no space left in it, this function falls
30381** back to sqlite3Malloc().
30382*/
30383static void *pcache1Alloc(int nByte){
30384  void *p;
30385  assert( sqlite3_mutex_held(pcache1.mutex) );
30386  if( nByte<=pcache1.szSlot && pcache1.pFree ){
30387    assert( pcache1.isInit );
30388    p = (PgHdr1 *)pcache1.pFree;
30389    pcache1.pFree = pcache1.pFree->pNext;
30390    sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
30391    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
30392  }else{
30393
30394    /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
30395    ** global pcache mutex and unlock the pager-cache object pCache. This is
30396    ** so that if the attempt to allocate a new buffer causes the the
30397    ** configured soft-heap-limit to be breached, it will be possible to
30398    ** reclaim memory from this pager-cache.
30399    */
30400    pcache1LeaveMutex();
30401    p = sqlite3Malloc(nByte);
30402    pcache1EnterMutex();
30403    if( p ){
30404      int sz = sqlite3MallocSize(p);
30405      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
30406    }
30407  }
30408  return p;
30409}
30410
30411/*
30412** Free an allocated buffer obtained from pcache1Alloc().
30413*/
30414static void pcache1Free(void *p){
30415  assert( sqlite3_mutex_held(pcache1.mutex) );
30416  if( p==0 ) return;
30417  if( p>=pcache1.pStart && p<pcache1.pEnd ){
30418    PgFreeslot *pSlot;
30419    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
30420    pSlot = (PgFreeslot*)p;
30421    pSlot->pNext = pcache1.pFree;
30422    pcache1.pFree = pSlot;
30423  }else{
30424    int iSize = sqlite3MallocSize(p);
30425    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
30426    sqlite3_free(p);
30427  }
30428}
30429
30430/*
30431** Allocate a new page object initially associated with cache pCache.
30432*/
30433static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
30434  int nByte = sizeof(PgHdr1) + pCache->szPage;
30435  void *pPg = pcache1Alloc(nByte);
30436  PgHdr1 *p;
30437  if( pPg ){
30438    p = PAGE_TO_PGHDR1(pCache, pPg);
30439    if( pCache->bPurgeable ){
30440      pcache1.nCurrentPage++;
30441    }
30442  }else{
30443    p = 0;
30444  }
30445  return p;
30446}
30447
30448/*
30449** Free a page object allocated by pcache1AllocPage().
30450**
30451** The pointer is allowed to be NULL, which is prudent.  But it turns out
30452** that the current implementation happens to never call this routine
30453** with a NULL pointer, so we mark the NULL test with ALWAYS().
30454*/
30455static void pcache1FreePage(PgHdr1 *p){
30456  if( ALWAYS(p) ){
30457    if( p->pCache->bPurgeable ){
30458      pcache1.nCurrentPage--;
30459    }
30460    pcache1Free(PGHDR1_TO_PAGE(p));
30461  }
30462}
30463
30464/*
30465** Malloc function used by SQLite to obtain space from the buffer configured
30466** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
30467** exists, this function falls back to sqlite3Malloc().
30468*/
30469SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
30470  void *p;
30471  pcache1EnterMutex();
30472  p = pcache1Alloc(sz);
30473  pcache1LeaveMutex();
30474  return p;
30475}
30476
30477/*
30478** Free an allocated buffer obtained from sqlite3PageMalloc().
30479*/
30480SQLITE_PRIVATE void sqlite3PageFree(void *p){
30481  pcache1EnterMutex();
30482  pcache1Free(p);
30483  pcache1LeaveMutex();
30484}
30485
30486/******************************************************************************/
30487/******** General Implementation Functions ************************************/
30488
30489/*
30490** This function is used to resize the hash table used by the cache passed
30491** as the first argument.
30492**
30493** The global mutex must be held when this function is called.
30494*/
30495static int pcache1ResizeHash(PCache1 *p){
30496  PgHdr1 **apNew;
30497  unsigned int nNew;
30498  unsigned int i;
30499
30500  assert( sqlite3_mutex_held(pcache1.mutex) );
30501
30502  nNew = p->nHash*2;
30503  if( nNew<256 ){
30504    nNew = 256;
30505  }
30506
30507  pcache1LeaveMutex();
30508  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
30509  apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
30510  if( p->nHash ){ sqlite3EndBenignMalloc(); }
30511  pcache1EnterMutex();
30512  if( apNew ){
30513    memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
30514    for(i=0; i<p->nHash; i++){
30515      PgHdr1 *pPage;
30516      PgHdr1 *pNext = p->apHash[i];
30517      while( (pPage = pNext)!=0 ){
30518        unsigned int h = pPage->iKey % nNew;
30519        pNext = pPage->pNext;
30520        pPage->pNext = apNew[h];
30521        apNew[h] = pPage;
30522      }
30523    }
30524    sqlite3_free(p->apHash);
30525    p->apHash = apNew;
30526    p->nHash = nNew;
30527  }
30528
30529  return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
30530}
30531
30532/*
30533** This function is used internally to remove the page pPage from the
30534** global LRU list, if is part of it. If pPage is not part of the global
30535** LRU list, then this function is a no-op.
30536**
30537** The global mutex must be held when this function is called.
30538*/
30539static void pcache1PinPage(PgHdr1 *pPage){
30540  assert( sqlite3_mutex_held(pcache1.mutex) );
30541  if( pPage && (pPage->pLruNext || pPage==pcache1.pLruTail) ){
30542    if( pPage->pLruPrev ){
30543      pPage->pLruPrev->pLruNext = pPage->pLruNext;
30544    }
30545    if( pPage->pLruNext ){
30546      pPage->pLruNext->pLruPrev = pPage->pLruPrev;
30547    }
30548    if( pcache1.pLruHead==pPage ){
30549      pcache1.pLruHead = pPage->pLruNext;
30550    }
30551    if( pcache1.pLruTail==pPage ){
30552      pcache1.pLruTail = pPage->pLruPrev;
30553    }
30554    pPage->pLruNext = 0;
30555    pPage->pLruPrev = 0;
30556    pPage->pCache->nRecyclable--;
30557  }
30558}
30559
30560
30561/*
30562** Remove the page supplied as an argument from the hash table
30563** (PCache1.apHash structure) that it is currently stored in.
30564**
30565** The global mutex must be held when this function is called.
30566*/
30567static void pcache1RemoveFromHash(PgHdr1 *pPage){
30568  unsigned int h;
30569  PCache1 *pCache = pPage->pCache;
30570  PgHdr1 **pp;
30571
30572  h = pPage->iKey % pCache->nHash;
30573  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
30574  *pp = (*pp)->pNext;
30575
30576  pCache->nPage--;
30577}
30578
30579/*
30580** If there are currently more than pcache.nMaxPage pages allocated, try
30581** to recycle pages to reduce the number allocated to pcache.nMaxPage.
30582*/
30583static void pcache1EnforceMaxPage(void){
30584  assert( sqlite3_mutex_held(pcache1.mutex) );
30585  while( pcache1.nCurrentPage>pcache1.nMaxPage && pcache1.pLruTail ){
30586    PgHdr1 *p = pcache1.pLruTail;
30587    pcache1PinPage(p);
30588    pcache1RemoveFromHash(p);
30589    pcache1FreePage(p);
30590  }
30591}
30592
30593/*
30594** Discard all pages from cache pCache with a page number (key value)
30595** greater than or equal to iLimit. Any pinned pages that meet this
30596** criteria are unpinned before they are discarded.
30597**
30598** The global mutex must be held when this function is called.
30599*/
30600static void pcache1TruncateUnsafe(
30601  PCache1 *pCache,
30602  unsigned int iLimit
30603){
30604  TESTONLY( unsigned int nPage = 0; )      /* Used to assert pCache->nPage is correct */
30605  unsigned int h;
30606  assert( sqlite3_mutex_held(pcache1.mutex) );
30607  for(h=0; h<pCache->nHash; h++){
30608    PgHdr1 **pp = &pCache->apHash[h];
30609    PgHdr1 *pPage;
30610    while( (pPage = *pp)!=0 ){
30611      if( pPage->iKey>=iLimit ){
30612        pCache->nPage--;
30613        *pp = pPage->pNext;
30614        pcache1PinPage(pPage);
30615        pcache1FreePage(pPage);
30616      }else{
30617        pp = &pPage->pNext;
30618        TESTONLY( nPage++; )
30619      }
30620    }
30621  }
30622  assert( pCache->nPage==nPage );
30623}
30624
30625/******************************************************************************/
30626/******** sqlite3_pcache Methods **********************************************/
30627
30628/*
30629** Implementation of the sqlite3_pcache.xInit method.
30630*/
30631static int pcache1Init(void *NotUsed){
30632  UNUSED_PARAMETER(NotUsed);
30633  assert( pcache1.isInit==0 );
30634  memset(&pcache1, 0, sizeof(pcache1));
30635  if( sqlite3GlobalConfig.bCoreMutex ){
30636    pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
30637  }
30638  pcache1.isInit = 1;
30639  return SQLITE_OK;
30640}
30641
30642/*
30643** Implementation of the sqlite3_pcache.xShutdown method.
30644** Note that the static mutex allocated in xInit does
30645** not need to be freed.
30646*/
30647static void pcache1Shutdown(void *NotUsed){
30648  UNUSED_PARAMETER(NotUsed);
30649  assert( pcache1.isInit!=0 );
30650  memset(&pcache1, 0, sizeof(pcache1));
30651}
30652
30653/*
30654** Implementation of the sqlite3_pcache.xCreate method.
30655**
30656** Allocate a new cache.
30657*/
30658static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
30659  PCache1 *pCache;
30660
30661  pCache = (PCache1 *)sqlite3_malloc(sizeof(PCache1));
30662  if( pCache ){
30663    memset(pCache, 0, sizeof(PCache1));
30664    pCache->szPage = szPage;
30665    pCache->bPurgeable = (bPurgeable ? 1 : 0);
30666    if( bPurgeable ){
30667      pCache->nMin = 10;
30668      pcache1EnterMutex();
30669      pcache1.nMinPage += pCache->nMin;
30670      pcache1LeaveMutex();
30671    }
30672  }
30673  return (sqlite3_pcache *)pCache;
30674}
30675
30676/*
30677** Implementation of the sqlite3_pcache.xCachesize method.
30678**
30679** Configure the cache_size limit for a cache.
30680*/
30681static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
30682  PCache1 *pCache = (PCache1 *)p;
30683  if( pCache->bPurgeable ){
30684    pcache1EnterMutex();
30685    pcache1.nMaxPage += (nMax - pCache->nMax);
30686    pCache->nMax = nMax;
30687    pcache1EnforceMaxPage();
30688    pcache1LeaveMutex();
30689  }
30690}
30691
30692/*
30693** Implementation of the sqlite3_pcache.xPagecount method.
30694*/
30695static int pcache1Pagecount(sqlite3_pcache *p){
30696  int n;
30697  pcache1EnterMutex();
30698  n = ((PCache1 *)p)->nPage;
30699  pcache1LeaveMutex();
30700  return n;
30701}
30702
30703/*
30704** Implementation of the sqlite3_pcache.xFetch method.
30705**
30706** Fetch a page by key value.
30707**
30708** Whether or not a new page may be allocated by this function depends on
30709** the value of the createFlag argument.  0 means do not allocate a new
30710** page.  1 means allocate a new page if space is easily available.  2
30711** means to try really hard to allocate a new page.
30712**
30713** For a non-purgeable cache (a cache used as the storage for an in-memory
30714** database) there is really no difference between createFlag 1 and 2.  So
30715** the calling function (pcache.c) will never have a createFlag of 1 on
30716** a non-purgable cache.
30717**
30718** There are three different approaches to obtaining space for a page,
30719** depending on the value of parameter createFlag (which may be 0, 1 or 2).
30720**
30721**   1. Regardless of the value of createFlag, the cache is searched for a
30722**      copy of the requested page. If one is found, it is returned.
30723**
30724**   2. If createFlag==0 and the page is not already in the cache, NULL is
30725**      returned.
30726**
30727**   3. If createFlag is 1, and the page is not already in the cache,
30728**      and if either of the following are true, return NULL:
30729**
30730**       (a) the number of pages pinned by the cache is greater than
30731**           PCache1.nMax, or
30732**       (b) the number of pages pinned by the cache is greater than
30733**           the sum of nMax for all purgeable caches, less the sum of
30734**           nMin for all other purgeable caches.
30735**
30736**   4. If none of the first three conditions apply and the cache is marked
30737**      as purgeable, and if one of the following is true:
30738**
30739**       (a) The number of pages allocated for the cache is already
30740**           PCache1.nMax, or
30741**
30742**       (b) The number of pages allocated for all purgeable caches is
30743**           already equal to or greater than the sum of nMax for all
30744**           purgeable caches,
30745**
30746**      then attempt to recycle a page from the LRU list. If it is the right
30747**      size, return the recycled buffer. Otherwise, free the buffer and
30748**      proceed to step 5.
30749**
30750**   5. Otherwise, allocate and return a new page buffer.
30751*/
30752static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
30753  unsigned int nPinned;
30754  PCache1 *pCache = (PCache1 *)p;
30755  PgHdr1 *pPage = 0;
30756
30757  assert( pCache->bPurgeable || createFlag!=1 );
30758  pcache1EnterMutex();
30759  if( createFlag==1 ) sqlite3BeginBenignMalloc();
30760
30761  /* Search the hash table for an existing entry. */
30762  if( pCache->nHash>0 ){
30763    unsigned int h = iKey % pCache->nHash;
30764    for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
30765  }
30766
30767  if( pPage || createFlag==0 ){
30768    pcache1PinPage(pPage);
30769    goto fetch_out;
30770  }
30771
30772  /* Step 3 of header comment. */
30773  nPinned = pCache->nPage - pCache->nRecyclable;
30774  if( createFlag==1 && (
30775        nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
30776     || nPinned>=(pCache->nMax * 9 / 10)
30777  )){
30778    goto fetch_out;
30779  }
30780
30781  if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
30782    goto fetch_out;
30783  }
30784
30785  /* Step 4. Try to recycle a page buffer if appropriate. */
30786  if( pCache->bPurgeable && pcache1.pLruTail && (
30787     (pCache->nPage+1>=pCache->nMax) || pcache1.nCurrentPage>=pcache1.nMaxPage
30788  )){
30789    pPage = pcache1.pLruTail;
30790    pcache1RemoveFromHash(pPage);
30791    pcache1PinPage(pPage);
30792    if( pPage->pCache->szPage!=pCache->szPage ){
30793      pcache1FreePage(pPage);
30794      pPage = 0;
30795    }else{
30796      pcache1.nCurrentPage -= (pPage->pCache->bPurgeable - pCache->bPurgeable);
30797    }
30798  }
30799
30800  /* Step 5. If a usable page buffer has still not been found,
30801  ** attempt to allocate a new one.
30802  */
30803  if( !pPage ){
30804    pPage = pcache1AllocPage(pCache);
30805  }
30806
30807  if( pPage ){
30808    unsigned int h = iKey % pCache->nHash;
30809    pCache->nPage++;
30810    pPage->iKey = iKey;
30811    pPage->pNext = pCache->apHash[h];
30812    pPage->pCache = pCache;
30813    pPage->pLruPrev = 0;
30814    pPage->pLruNext = 0;
30815    *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
30816    pCache->apHash[h] = pPage;
30817  }
30818
30819fetch_out:
30820  if( pPage && iKey>pCache->iMaxKey ){
30821    pCache->iMaxKey = iKey;
30822  }
30823  if( createFlag==1 ) sqlite3EndBenignMalloc();
30824  pcache1LeaveMutex();
30825  return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
30826}
30827
30828
30829/*
30830** Implementation of the sqlite3_pcache.xUnpin method.
30831**
30832** Mark a page as unpinned (eligible for asynchronous recycling).
30833*/
30834static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
30835  PCache1 *pCache = (PCache1 *)p;
30836  PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
30837
30838  assert( pPage->pCache==pCache );
30839  pcache1EnterMutex();
30840
30841  /* It is an error to call this function if the page is already
30842  ** part of the global LRU list.
30843  */
30844  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
30845  assert( pcache1.pLruHead!=pPage && pcache1.pLruTail!=pPage );
30846
30847  if( reuseUnlikely || pcache1.nCurrentPage>pcache1.nMaxPage ){
30848    pcache1RemoveFromHash(pPage);
30849    pcache1FreePage(pPage);
30850  }else{
30851    /* Add the page to the global LRU list. Normally, the page is added to
30852    ** the head of the list (last page to be recycled). However, if the
30853    ** reuseUnlikely flag passed to this function is true, the page is added
30854    ** to the tail of the list (first page to be recycled).
30855    */
30856    if( pcache1.pLruHead ){
30857      pcache1.pLruHead->pLruPrev = pPage;
30858      pPage->pLruNext = pcache1.pLruHead;
30859      pcache1.pLruHead = pPage;
30860    }else{
30861      pcache1.pLruTail = pPage;
30862      pcache1.pLruHead = pPage;
30863    }
30864    pCache->nRecyclable++;
30865  }
30866
30867  pcache1LeaveMutex();
30868}
30869
30870/*
30871** Implementation of the sqlite3_pcache.xRekey method.
30872*/
30873static void pcache1Rekey(
30874  sqlite3_pcache *p,
30875  void *pPg,
30876  unsigned int iOld,
30877  unsigned int iNew
30878){
30879  PCache1 *pCache = (PCache1 *)p;
30880  PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
30881  PgHdr1 **pp;
30882  unsigned int h;
30883  assert( pPage->iKey==iOld );
30884  assert( pPage->pCache==pCache );
30885
30886  pcache1EnterMutex();
30887
30888  h = iOld%pCache->nHash;
30889  pp = &pCache->apHash[h];
30890  while( (*pp)!=pPage ){
30891    pp = &(*pp)->pNext;
30892  }
30893  *pp = pPage->pNext;
30894
30895  h = iNew%pCache->nHash;
30896  pPage->iKey = iNew;
30897  pPage->pNext = pCache->apHash[h];
30898  pCache->apHash[h] = pPage;
30899  if( iNew>pCache->iMaxKey ){
30900    pCache->iMaxKey = iNew;
30901  }
30902
30903  pcache1LeaveMutex();
30904}
30905
30906/*
30907** Implementation of the sqlite3_pcache.xTruncate method.
30908**
30909** Discard all unpinned pages in the cache with a page number equal to
30910** or greater than parameter iLimit. Any pinned pages with a page number
30911** equal to or greater than iLimit are implicitly unpinned.
30912*/
30913static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
30914  PCache1 *pCache = (PCache1 *)p;
30915  pcache1EnterMutex();
30916  if( iLimit<=pCache->iMaxKey ){
30917    pcache1TruncateUnsafe(pCache, iLimit);
30918    pCache->iMaxKey = iLimit-1;
30919  }
30920  pcache1LeaveMutex();
30921}
30922
30923/*
30924** Implementation of the sqlite3_pcache.xDestroy method.
30925**
30926** Destroy a cache allocated using pcache1Create().
30927*/
30928static void pcache1Destroy(sqlite3_pcache *p){
30929  PCache1 *pCache = (PCache1 *)p;
30930  pcache1EnterMutex();
30931  pcache1TruncateUnsafe(pCache, 0);
30932  pcache1.nMaxPage -= pCache->nMax;
30933  pcache1.nMinPage -= pCache->nMin;
30934  pcache1EnforceMaxPage();
30935  pcache1LeaveMutex();
30936  sqlite3_free(pCache->apHash);
30937  sqlite3_free(pCache);
30938}
30939
30940/*
30941** This function is called during initialization (sqlite3_initialize()) to
30942** install the default pluggable cache module, assuming the user has not
30943** already provided an alternative.
30944*/
30945SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
30946  static sqlite3_pcache_methods defaultMethods = {
30947    0,                       /* pArg */
30948    pcache1Init,             /* xInit */
30949    pcache1Shutdown,         /* xShutdown */
30950    pcache1Create,           /* xCreate */
30951    pcache1Cachesize,        /* xCachesize */
30952    pcache1Pagecount,        /* xPagecount */
30953    pcache1Fetch,            /* xFetch */
30954    pcache1Unpin,            /* xUnpin */
30955    pcache1Rekey,            /* xRekey */
30956    pcache1Truncate,         /* xTruncate */
30957    pcache1Destroy           /* xDestroy */
30958  };
30959  sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
30960}
30961
30962#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
30963/*
30964** This function is called to free superfluous dynamically allocated memory
30965** held by the pager system. Memory in use by any SQLite pager allocated
30966** by the current thread may be sqlite3_free()ed.
30967**
30968** nReq is the number of bytes of memory required. Once this much has
30969** been released, the function returns. The return value is the total number
30970** of bytes of memory released.
30971*/
30972SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
30973  int nFree = 0;
30974  if( pcache1.pStart==0 ){
30975    PgHdr1 *p;
30976    pcache1EnterMutex();
30977    while( (nReq<0 || nFree<nReq) && (p=pcache1.pLruTail) ){
30978      nFree += sqlite3MallocSize(PGHDR1_TO_PAGE(p));
30979      pcache1PinPage(p);
30980      pcache1RemoveFromHash(p);
30981      pcache1FreePage(p);
30982    }
30983    pcache1LeaveMutex();
30984  }
30985  return nFree;
30986}
30987#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
30988
30989#ifdef SQLITE_TEST
30990/*
30991** This function is used by test procedures to inspect the internal state
30992** of the global cache.
30993*/
30994SQLITE_PRIVATE void sqlite3PcacheStats(
30995  int *pnCurrent,      /* OUT: Total number of pages cached */
30996  int *pnMax,          /* OUT: Global maximum cache size */
30997  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
30998  int *pnRecyclable    /* OUT: Total number of pages available for recycling */
30999){
31000  PgHdr1 *p;
31001  int nRecyclable = 0;
31002  for(p=pcache1.pLruHead; p; p=p->pLruNext){
31003    nRecyclable++;
31004  }
31005  *pnCurrent = pcache1.nCurrentPage;
31006  *pnMax = pcache1.nMaxPage;
31007  *pnMin = pcache1.nMinPage;
31008  *pnRecyclable = nRecyclable;
31009}
31010#endif
31011
31012/************** End of pcache1.c *********************************************/
31013/************** Begin file rowset.c ******************************************/
31014/*
31015** 2008 December 3
31016**
31017** The author disclaims copyright to this source code.  In place of
31018** a legal notice, here is a blessing:
31019**
31020**    May you do good and not evil.
31021**    May you find forgiveness for yourself and forgive others.
31022**    May you share freely, never taking more than you give.
31023**
31024*************************************************************************
31025**
31026** This module implements an object we call a "RowSet".
31027**
31028** The RowSet object is a collection of rowids.  Rowids
31029** are inserted into the RowSet in an arbitrary order.  Inserts
31030** can be intermixed with tests to see if a given rowid has been
31031** previously inserted into the RowSet.
31032**
31033** After all inserts are finished, it is possible to extract the
31034** elements of the RowSet in sorted order.  Once this extraction
31035** process has started, no new elements may be inserted.
31036**
31037** Hence, the primitive operations for a RowSet are:
31038**
31039**    CREATE
31040**    INSERT
31041**    TEST
31042**    SMALLEST
31043**    DESTROY
31044**
31045** The CREATE and DESTROY primitives are the constructor and destructor,
31046** obviously.  The INSERT primitive adds a new element to the RowSet.
31047** TEST checks to see if an element is already in the RowSet.  SMALLEST
31048** extracts the least value from the RowSet.
31049**
31050** The INSERT primitive might allocate additional memory.  Memory is
31051** allocated in chunks so most INSERTs do no allocation.  There is an
31052** upper bound on the size of allocated memory.  No memory is freed
31053** until DESTROY.
31054**
31055** The TEST primitive includes a "batch" number.  The TEST primitive
31056** will only see elements that were inserted before the last change
31057** in the batch number.  In other words, if an INSERT occurs between
31058** two TESTs where the TESTs have the same batch nubmer, then the
31059** value added by the INSERT will not be visible to the second TEST.
31060** The initial batch number is zero, so if the very first TEST contains
31061** a non-zero batch number, it will see all prior INSERTs.
31062**
31063** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
31064** that is attempted.
31065**
31066** The cost of an INSERT is roughly constant.  (Sometime new memory
31067** has to be allocated on an INSERT.)  The cost of a TEST with a new
31068** batch number is O(NlogN) where N is the number of elements in the RowSet.
31069** The cost of a TEST using the same batch number is O(logN).  The cost
31070** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
31071** primitives are constant time.  The cost of DESTROY is O(N).
31072**
31073** There is an added cost of O(N) when switching between TEST and
31074** SMALLEST primitives.
31075*/
31076
31077
31078/*
31079** Target size for allocation chunks.
31080*/
31081#define ROWSET_ALLOCATION_SIZE 1024
31082
31083/*
31084** The number of rowset entries per allocation chunk.
31085*/
31086#define ROWSET_ENTRY_PER_CHUNK  \
31087                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
31088
31089/*
31090** Each entry in a RowSet is an instance of the following object.
31091*/
31092struct RowSetEntry {
31093  i64 v;                        /* ROWID value for this entry */
31094  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
31095  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
31096};
31097
31098/*
31099** RowSetEntry objects are allocated in large chunks (instances of the
31100** following structure) to reduce memory allocation overhead.  The
31101** chunks are kept on a linked list so that they can be deallocated
31102** when the RowSet is destroyed.
31103*/
31104struct RowSetChunk {
31105  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
31106  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
31107};
31108
31109/*
31110** A RowSet in an instance of the following structure.
31111**
31112** A typedef of this structure if found in sqliteInt.h.
31113*/
31114struct RowSet {
31115  struct RowSetChunk *pChunk;    /* List of all chunk allocations */
31116  sqlite3 *db;                   /* The database connection */
31117  struct RowSetEntry *pEntry;    /* List of entries using pRight */
31118  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
31119  struct RowSetEntry *pFresh;    /* Source of new entry objects */
31120  struct RowSetEntry *pTree;     /* Binary tree of entries */
31121  u16 nFresh;                    /* Number of objects on pFresh */
31122  u8 isSorted;                   /* True if pEntry is sorted */
31123  u8 iBatch;                     /* Current insert batch */
31124};
31125
31126/*
31127** Turn bulk memory into a RowSet object.  N bytes of memory
31128** are available at pSpace.  The db pointer is used as a memory context
31129** for any subsequent allocations that need to occur.
31130** Return a pointer to the new RowSet object.
31131**
31132** It must be the case that N is sufficient to make a Rowset.  If not
31133** an assertion fault occurs.
31134**
31135** If N is larger than the minimum, use the surplus as an initial
31136** allocation of entries available to be filled.
31137*/
31138SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
31139  RowSet *p;
31140  assert( N >= ROUND8(sizeof(*p)) );
31141  p = pSpace;
31142  p->pChunk = 0;
31143  p->db = db;
31144  p->pEntry = 0;
31145  p->pLast = 0;
31146  p->pTree = 0;
31147  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
31148  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
31149  p->isSorted = 1;
31150  p->iBatch = 0;
31151  return p;
31152}
31153
31154/*
31155** Deallocate all chunks from a RowSet.  This frees all memory that
31156** the RowSet has allocated over its lifetime.  This routine is
31157** the destructor for the RowSet.
31158*/
31159SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
31160  struct RowSetChunk *pChunk, *pNextChunk;
31161  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
31162    pNextChunk = pChunk->pNextChunk;
31163    sqlite3DbFree(p->db, pChunk);
31164  }
31165  p->pChunk = 0;
31166  p->nFresh = 0;
31167  p->pEntry = 0;
31168  p->pLast = 0;
31169  p->pTree = 0;
31170  p->isSorted = 1;
31171}
31172
31173/*
31174** Insert a new value into a RowSet.
31175**
31176** The mallocFailed flag of the database connection is set if a
31177** memory allocation fails.
31178*/
31179SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
31180  struct RowSetEntry *pEntry;  /* The new entry */
31181  struct RowSetEntry *pLast;   /* The last prior entry */
31182  assert( p!=0 );
31183  if( p->nFresh==0 ){
31184    struct RowSetChunk *pNew;
31185    pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
31186    if( pNew==0 ){
31187      return;
31188    }
31189    pNew->pNextChunk = p->pChunk;
31190    p->pChunk = pNew;
31191    p->pFresh = pNew->aEntry;
31192    p->nFresh = ROWSET_ENTRY_PER_CHUNK;
31193  }
31194  pEntry = p->pFresh++;
31195  p->nFresh--;
31196  pEntry->v = rowid;
31197  pEntry->pRight = 0;
31198  pLast = p->pLast;
31199  if( pLast ){
31200    if( p->isSorted && rowid<=pLast->v ){
31201      p->isSorted = 0;
31202    }
31203    pLast->pRight = pEntry;
31204  }else{
31205    assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
31206    p->pEntry = pEntry;
31207  }
31208  p->pLast = pEntry;
31209}
31210
31211/*
31212** Merge two lists of RowSetEntry objects.  Remove duplicates.
31213**
31214** The input lists are connected via pRight pointers and are
31215** assumed to each already be in sorted order.
31216*/
31217static struct RowSetEntry *rowSetMerge(
31218  struct RowSetEntry *pA,    /* First sorted list to be merged */
31219  struct RowSetEntry *pB     /* Second sorted list to be merged */
31220){
31221  struct RowSetEntry head;
31222  struct RowSetEntry *pTail;
31223
31224  pTail = &head;
31225  while( pA && pB ){
31226    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
31227    assert( pB->pRight==0 || pB->v<=pB->pRight->v );
31228    if( pA->v<pB->v ){
31229      pTail->pRight = pA;
31230      pA = pA->pRight;
31231      pTail = pTail->pRight;
31232    }else if( pB->v<pA->v ){
31233      pTail->pRight = pB;
31234      pB = pB->pRight;
31235      pTail = pTail->pRight;
31236    }else{
31237      pA = pA->pRight;
31238    }
31239  }
31240  if( pA ){
31241    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
31242    pTail->pRight = pA;
31243  }else{
31244    assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
31245    pTail->pRight = pB;
31246  }
31247  return head.pRight;
31248}
31249
31250/*
31251** Sort all elements on the pEntry list of the RowSet into ascending order.
31252*/
31253static void rowSetSort(RowSet *p){
31254  unsigned int i;
31255  struct RowSetEntry *pEntry;
31256  struct RowSetEntry *aBucket[40];
31257
31258  assert( p->isSorted==0 );
31259  memset(aBucket, 0, sizeof(aBucket));
31260  while( p->pEntry ){
31261    pEntry = p->pEntry;
31262    p->pEntry = pEntry->pRight;
31263    pEntry->pRight = 0;
31264    for(i=0; aBucket[i]; i++){
31265      pEntry = rowSetMerge(aBucket[i], pEntry);
31266      aBucket[i] = 0;
31267    }
31268    aBucket[i] = pEntry;
31269  }
31270  pEntry = 0;
31271  for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
31272    pEntry = rowSetMerge(pEntry, aBucket[i]);
31273  }
31274  p->pEntry = pEntry;
31275  p->pLast = 0;
31276  p->isSorted = 1;
31277}
31278
31279
31280/*
31281** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
31282** Convert this tree into a linked list connected by the pRight pointers
31283** and return pointers to the first and last elements of the new list.
31284*/
31285static void rowSetTreeToList(
31286  struct RowSetEntry *pIn,         /* Root of the input tree */
31287  struct RowSetEntry **ppFirst,    /* Write head of the output list here */
31288  struct RowSetEntry **ppLast      /* Write tail of the output list here */
31289){
31290  assert( pIn!=0 );
31291  if( pIn->pLeft ){
31292    struct RowSetEntry *p;
31293    rowSetTreeToList(pIn->pLeft, ppFirst, &p);
31294    p->pRight = pIn;
31295  }else{
31296    *ppFirst = pIn;
31297  }
31298  if( pIn->pRight ){
31299    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
31300  }else{
31301    *ppLast = pIn;
31302  }
31303  assert( (*ppLast)->pRight==0 );
31304}
31305
31306
31307/*
31308** Convert a sorted list of elements (connected by pRight) into a binary
31309** tree with depth of iDepth.  A depth of 1 means the tree contains a single
31310** node taken from the head of *ppList.  A depth of 2 means a tree with
31311** three nodes.  And so forth.
31312**
31313** Use as many entries from the input list as required and update the
31314** *ppList to point to the unused elements of the list.  If the input
31315** list contains too few elements, then construct an incomplete tree
31316** and leave *ppList set to NULL.
31317**
31318** Return a pointer to the root of the constructed binary tree.
31319*/
31320static struct RowSetEntry *rowSetNDeepTree(
31321  struct RowSetEntry **ppList,
31322  int iDepth
31323){
31324  struct RowSetEntry *p;         /* Root of the new tree */
31325  struct RowSetEntry *pLeft;     /* Left subtree */
31326  if( *ppList==0 ){
31327    return 0;
31328  }
31329  if( iDepth==1 ){
31330    p = *ppList;
31331    *ppList = p->pRight;
31332    p->pLeft = p->pRight = 0;
31333    return p;
31334  }
31335  pLeft = rowSetNDeepTree(ppList, iDepth-1);
31336  p = *ppList;
31337  if( p==0 ){
31338    return pLeft;
31339  }
31340  p->pLeft = pLeft;
31341  *ppList = p->pRight;
31342  p->pRight = rowSetNDeepTree(ppList, iDepth-1);
31343  return p;
31344}
31345
31346/*
31347** Convert a sorted list of elements into a binary tree. Make the tree
31348** as deep as it needs to be in order to contain the entire list.
31349*/
31350static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
31351  int iDepth;           /* Depth of the tree so far */
31352  struct RowSetEntry *p;       /* Current tree root */
31353  struct RowSetEntry *pLeft;   /* Left subtree */
31354
31355  assert( pList!=0 );
31356  p = pList;
31357  pList = p->pRight;
31358  p->pLeft = p->pRight = 0;
31359  for(iDepth=1; pList; iDepth++){
31360    pLeft = p;
31361    p = pList;
31362    pList = p->pRight;
31363    p->pLeft = pLeft;
31364    p->pRight = rowSetNDeepTree(&pList, iDepth);
31365  }
31366  return p;
31367}
31368
31369/*
31370** Convert the list in p->pEntry into a sorted list if it is not
31371** sorted already.  If there is a binary tree on p->pTree, then
31372** convert it into a list too and merge it into the p->pEntry list.
31373*/
31374static void rowSetToList(RowSet *p){
31375  if( !p->isSorted ){
31376    rowSetSort(p);
31377  }
31378  if( p->pTree ){
31379    struct RowSetEntry *pHead, *pTail;
31380    rowSetTreeToList(p->pTree, &pHead, &pTail);
31381    p->pTree = 0;
31382    p->pEntry = rowSetMerge(p->pEntry, pHead);
31383  }
31384}
31385
31386/*
31387** Extract the smallest element from the RowSet.
31388** Write the element into *pRowid.  Return 1 on success.  Return
31389** 0 if the RowSet is already empty.
31390**
31391** After this routine has been called, the sqlite3RowSetInsert()
31392** routine may not be called again.
31393*/
31394SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
31395  rowSetToList(p);
31396  if( p->pEntry ){
31397    *pRowid = p->pEntry->v;
31398    p->pEntry = p->pEntry->pRight;
31399    if( p->pEntry==0 ){
31400      sqlite3RowSetClear(p);
31401    }
31402    return 1;
31403  }else{
31404    return 0;
31405  }
31406}
31407
31408/*
31409** Check to see if element iRowid was inserted into the the rowset as
31410** part of any insert batch prior to iBatch.  Return 1 or 0.
31411*/
31412SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
31413  struct RowSetEntry *p;
31414  if( iBatch!=pRowSet->iBatch ){
31415    if( pRowSet->pEntry ){
31416      rowSetToList(pRowSet);
31417      pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
31418      pRowSet->pEntry = 0;
31419      pRowSet->pLast = 0;
31420    }
31421    pRowSet->iBatch = iBatch;
31422  }
31423  p = pRowSet->pTree;
31424  while( p ){
31425    if( p->v<iRowid ){
31426      p = p->pRight;
31427    }else if( p->v>iRowid ){
31428      p = p->pLeft;
31429    }else{
31430      return 1;
31431    }
31432  }
31433  return 0;
31434}
31435
31436/************** End of rowset.c **********************************************/
31437/************** Begin file pager.c *******************************************/
31438/*
31439** 2001 September 15
31440**
31441** The author disclaims copyright to this source code.  In place of
31442** a legal notice, here is a blessing:
31443**
31444**    May you do good and not evil.
31445**    May you find forgiveness for yourself and forgive others.
31446**    May you share freely, never taking more than you give.
31447**
31448*************************************************************************
31449** This is the implementation of the page cache subsystem or "pager".
31450**
31451** The pager is used to access a database disk file.  It implements
31452** atomic commit and rollback through the use of a journal file that
31453** is separate from the database file.  The pager also implements file
31454** locking to prevent two processes from writing the same database
31455** file simultaneously, or one process from reading the database while
31456** another is writing.
31457*/
31458#ifndef SQLITE_OMIT_DISKIO
31459
31460/*
31461** Macros for troubleshooting.  Normally turned off
31462*/
31463#if 0
31464int sqlite3PagerTrace=1;  /* True to enable tracing */
31465#define sqlite3DebugPrintf printf
31466#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
31467#else
31468#define PAGERTRACE(X)
31469#endif
31470
31471/*
31472** The following two macros are used within the PAGERTRACE() macros above
31473** to print out file-descriptors.
31474**
31475** PAGERID() takes a pointer to a Pager struct as its argument. The
31476** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
31477** struct as its argument.
31478*/
31479#define PAGERID(p) ((int)(p->fd))
31480#define FILEHANDLEID(fd) ((int)fd)
31481
31482/*
31483** The page cache as a whole is always in one of the following
31484** states:
31485**
31486**   PAGER_UNLOCK        The page cache is not currently reading or
31487**                       writing the database file.  There is no
31488**                       data held in memory.  This is the initial
31489**                       state.
31490**
31491**   PAGER_SHARED        The page cache is reading the database.
31492**                       Writing is not permitted.  There can be
31493**                       multiple readers accessing the same database
31494**                       file at the same time.
31495**
31496**   PAGER_RESERVED      This process has reserved the database for writing
31497**                       but has not yet made any changes.  Only one process
31498**                       at a time can reserve the database.  The original
31499**                       database file has not been modified so other
31500**                       processes may still be reading the on-disk
31501**                       database file.
31502**
31503**   PAGER_EXCLUSIVE     The page cache is writing the database.
31504**                       Access is exclusive.  No other processes or
31505**                       threads can be reading or writing while one
31506**                       process is writing.
31507**
31508**   PAGER_SYNCED        The pager moves to this state from PAGER_EXCLUSIVE
31509**                       after all dirty pages have been written to the
31510**                       database file and the file has been synced to
31511**                       disk. All that remains to do is to remove or
31512**                       truncate the journal file and the transaction
31513**                       will be committed.
31514**
31515** The page cache comes up in PAGER_UNLOCK.  The first time a
31516** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
31517** After all pages have been released using sqlite_page_unref(),
31518** the state transitions back to PAGER_UNLOCK.  The first time
31519** that sqlite3PagerWrite() is called, the state transitions to
31520** PAGER_RESERVED.  (Note that sqlite3PagerWrite() can only be
31521** called on an outstanding page which means that the pager must
31522** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
31523** PAGER_RESERVED means that there is an open rollback journal.
31524** The transition to PAGER_EXCLUSIVE occurs before any changes
31525** are made to the database file, though writes to the rollback
31526** journal occurs with just PAGER_RESERVED.  After an sqlite3PagerRollback()
31527** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
31528** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
31529*/
31530#define PAGER_UNLOCK      0
31531#define PAGER_SHARED      1   /* same as SHARED_LOCK */
31532#define PAGER_RESERVED    2   /* same as RESERVED_LOCK */
31533#define PAGER_EXCLUSIVE   4   /* same as EXCLUSIVE_LOCK */
31534#define PAGER_SYNCED      5
31535
31536/*
31537** A macro used for invoking the codec if there is one
31538*/
31539#ifdef SQLITE_HAS_CODEC
31540# define CODEC1(P,D,N,X,E) \
31541    if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
31542# define CODEC2(P,D,N,X,E,O) \
31543    if( P->xCodec==0 ){ O=(char*)D; }else \
31544    if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
31545#else
31546# define CODEC1(P,D,N,X,E)   /* NO-OP */
31547# define CODEC2(P,D,N,X,E,O) O=(char*)D
31548#endif
31549
31550/*
31551** The maximum allowed sector size. 64KiB. If the xSectorsize() method
31552** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
31553** This could conceivably cause corruption following a power failure on
31554** such a system. This is currently an undocumented limit.
31555*/
31556#define MAX_SECTOR_SIZE 0x10000
31557
31558/*
31559** An instance of the following structure is allocated for each active
31560** savepoint and statement transaction in the system. All such structures
31561** are stored in the Pager.aSavepoint[] array, which is allocated and
31562** resized using sqlite3Realloc().
31563**
31564** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
31565** set to 0. If a journal-header is written into the main journal while
31566** the savepoint is active, then iHdrOffset is set to the byte offset
31567** immediately following the last journal record written into the main
31568** journal before the journal-header. This is required during savepoint
31569** rollback (see pagerPlaybackSavepoint()).
31570*/
31571typedef struct PagerSavepoint PagerSavepoint;
31572struct PagerSavepoint {
31573  i64 iOffset;                 /* Starting offset in main journal */
31574  i64 iHdrOffset;              /* See above */
31575  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
31576  Pgno nOrig;                  /* Original number of pages in file */
31577  Pgno iSubRec;                /* Index of first record in sub-journal */
31578};
31579
31580/*
31581** A open page cache is an instance of the following structure.
31582**
31583** errCode
31584**
31585**   Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
31586**   or SQLITE_FULL. Once one of the first three errors occurs, it persists
31587**   and is returned as the result of every major pager API call.  The
31588**   SQLITE_FULL return code is slightly different. It persists only until the
31589**   next successful rollback is performed on the pager cache. Also,
31590**   SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
31591**   APIs, they may still be used successfully.
31592**
31593** dbSizeValid, dbSize, dbOrigSize, dbFileSize
31594**
31595**   Managing the size of the database file in pages is a little complicated.
31596**   The variable Pager.dbSize contains the number of pages that the database
31597**   image currently contains. As the database image grows or shrinks this
31598**   variable is updated. The variable Pager.dbFileSize contains the number
31599**   of pages in the database file. This may be different from Pager.dbSize
31600**   if some pages have been appended to the database image but not yet written
31601**   out from the cache to the actual file on disk. Or if the image has been
31602**   truncated by an incremental-vacuum operation. The Pager.dbOrigSize variable
31603**   contains the number of pages in the database image when the current
31604**   transaction was opened. The contents of all three of these variables is
31605**   only guaranteed to be correct if the boolean Pager.dbSizeValid is true.
31606**
31607**   TODO: Under what conditions is dbSizeValid set? Cleared?
31608**
31609** changeCountDone
31610**
31611**   This boolean variable is used to make sure that the change-counter
31612**   (the 4-byte header field at byte offset 24 of the database file) is
31613**   not updated more often than necessary.
31614**
31615**   It is set to true when the change-counter field is updated, which
31616**   can only happen if an exclusive lock is held on the database file.
31617**   It is cleared (set to false) whenever an exclusive lock is
31618**   relinquished on the database file. Each time a transaction is committed,
31619**   The changeCountDone flag is inspected. If it is true, the work of
31620**   updating the change-counter is omitted for the current transaction.
31621**
31622**   This mechanism means that when running in exclusive mode, a connection
31623**   need only update the change-counter once, for the first transaction
31624**   committed.
31625**
31626** dbModified
31627**
31628**   The dbModified flag is set whenever a database page is dirtied.
31629**   It is cleared at the end of each transaction.
31630**
31631**   It is used when committing or otherwise ending a transaction. If
31632**   the dbModified flag is clear then less work has to be done.
31633**
31634** journalStarted
31635**
31636**   This flag is set whenever the the main journal is synced.
31637**
31638**   The point of this flag is that it must be set after the
31639**   first journal header in a journal file has been synced to disk.
31640**   After this has happened, new pages appended to the database
31641**   do not need the PGHDR_NEED_SYNC flag set, as they do not need
31642**   to wait for a journal sync before they can be written out to
31643**   the database file (see function pager_write()).
31644**
31645** setMaster
31646**
31647**   This variable is used to ensure that the master journal file name
31648**   (if any) is only written into the journal file once.
31649**
31650**   When committing a transaction, the master journal file name (if any)
31651**   may be written into the journal file while the pager is still in
31652**   PAGER_RESERVED state (see CommitPhaseOne() for the action). It
31653**   then attempts to upgrade to an exclusive lock. If this attempt
31654**   fails, then SQLITE_BUSY may be returned to the user and the user
31655**   may attempt to commit the transaction again later (calling
31656**   CommitPhaseOne() again). This flag is used to ensure that the
31657**   master journal name is only written to the journal file the first
31658**   time CommitPhaseOne() is called.
31659**
31660** doNotSync
31661**
31662**   This variable is set and cleared by sqlite3PagerWrite().
31663**
31664** needSync
31665**
31666**   TODO: It might be easier to set this variable in writeJournalHdr()
31667**   and writeMasterJournal() only. Change its meaning to "unsynced data
31668**   has been written to the journal".
31669**
31670** subjInMemory
31671**
31672**   This is a boolean variable. If true, then any required sub-journal
31673**   is opened as an in-memory journal file. If false, then in-memory
31674**   sub-journals are only used for in-memory pager files.
31675*/
31676struct Pager {
31677  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
31678  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
31679  u8 journalMode;             /* On of the PAGER_JOURNALMODE_* values */
31680  u8 useJournal;              /* Use a rollback journal on this file */
31681  u8 noReadlock;              /* Do not bother to obtain readlocks */
31682  u8 noSync;                  /* Do not sync the journal if true */
31683  u8 fullSync;                /* Do extra syncs of the journal for robustness */
31684  u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
31685  u8 tempFile;                /* zFilename is a temporary file */
31686  u8 readOnly;                /* True for a read-only database */
31687  u8 memDb;                   /* True to inhibit all file I/O */
31688
31689  /* The following block contains those class members that are dynamically
31690  ** modified during normal operations. The other variables in this structure
31691  ** are either constant throughout the lifetime of the pager, or else
31692  ** used to store configuration parameters that affect the way the pager
31693  ** operates.
31694  **
31695  ** The 'state' variable is described in more detail along with the
31696  ** descriptions of the values it may take - PAGER_UNLOCK etc. Many of the
31697  ** other variables in this block are described in the comment directly
31698  ** above this class definition.
31699  */
31700  u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
31701  u8 dbModified;              /* True if there are any changes to the Db */
31702  u8 needSync;                /* True if an fsync() is needed on the journal */
31703  u8 journalStarted;          /* True if header of journal is synced */
31704  u8 changeCountDone;         /* Set after incrementing the change-counter */
31705  u8 setMaster;               /* True if a m-j name has been written to jrnl */
31706  u8 doNotSync;               /* Boolean. While true, do not spill the cache */
31707  u8 dbSizeValid;             /* Set when dbSize is correct */
31708  u8 subjInMemory;            /* True to use in-memory sub-journals */
31709  Pgno dbSize;                /* Number of pages in the database */
31710  Pgno dbOrigSize;            /* dbSize before the current transaction */
31711  Pgno dbFileSize;            /* Number of pages in the database file */
31712  int errCode;                /* One of several kinds of errors */
31713  int nRec;                   /* Pages journalled since last j-header written */
31714  u32 cksumInit;              /* Quasi-random value added to every checksum */
31715  u32 nSubRec;                /* Number of records written to sub-journal */
31716  Bitvec *pInJournal;         /* One bit for each page in the database file */
31717  sqlite3_file *fd;           /* File descriptor for database */
31718  sqlite3_file *jfd;          /* File descriptor for main journal */
31719  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
31720  i64 journalOff;             /* Current write offset in the journal file */
31721  i64 journalHdr;             /* Byte offset to previous journal header */
31722  PagerSavepoint *aSavepoint; /* Array of active savepoints */
31723  int nSavepoint;             /* Number of elements in aSavepoint[] */
31724  char dbFileVers[16];        /* Changes whenever database file changes */
31725  u32 sectorSize;             /* Assumed sector size during rollback */
31726
31727  u16 nExtra;                 /* Add this many bytes to each in-memory page */
31728  i16 nReserve;               /* Number of unused bytes at end of each page */
31729  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
31730  int pageSize;               /* Number of bytes in a page */
31731  Pgno mxPgno;                /* Maximum allowed size of the database */
31732  char *zFilename;            /* Name of the database file */
31733  char *zJournal;             /* Name of the journal file */
31734  int (*xBusyHandler)(void*); /* Function to call when busy */
31735  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
31736#ifdef SQLITE_TEST
31737  int nHit, nMiss;            /* Cache hits and missing */
31738  int nRead, nWrite;          /* Database pages read/written */
31739#endif
31740  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
31741#ifdef SQLITE_HAS_CODEC
31742  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
31743  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
31744  void (*xCodecFree)(void*);             /* Destructor for the codec */
31745  void *pCodec;               /* First argument to xCodec... methods */
31746#endif
31747  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
31748  i64 journalSizeLimit;       /* Size limit for persistent journal files */
31749  PCache *pPCache;            /* Pointer to page cache object */
31750  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
31751};
31752
31753/*
31754** The following global variables hold counters used for
31755** testing purposes only.  These variables do not exist in
31756** a non-testing build.  These variables are not thread-safe.
31757*/
31758#ifdef SQLITE_TEST
31759SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
31760SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
31761SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
31762# define PAGER_INCR(v)  v++
31763#else
31764# define PAGER_INCR(v)
31765#endif
31766
31767
31768
31769/*
31770** Journal files begin with the following magic string.  The data
31771** was obtained from /dev/random.  It is used only as a sanity check.
31772**
31773** Since version 2.8.0, the journal format contains additional sanity
31774** checking information.  If the power fails while the journal is being
31775** written, semi-random garbage data might appear in the journal
31776** file after power is restored.  If an attempt is then made
31777** to roll the journal back, the database could be corrupted.  The additional
31778** sanity checking data is an attempt to discover the garbage in the
31779** journal and ignore it.
31780**
31781** The sanity checking information for the new journal format consists
31782** of a 32-bit checksum on each page of data.  The checksum covers both
31783** the page number and the pPager->pageSize bytes of data for the page.
31784** This cksum is initialized to a 32-bit random value that appears in the
31785** journal file right after the header.  The random initializer is important,
31786** because garbage data that appears at the end of a journal is likely
31787** data that was once in other files that have now been deleted.  If the
31788** garbage data came from an obsolete journal file, the checksums might
31789** be correct.  But by initializing the checksum to random value which
31790** is different for every journal, we minimize that risk.
31791*/
31792static const unsigned char aJournalMagic[] = {
31793  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
31794};
31795
31796/*
31797** The size of the of each page record in the journal is given by
31798** the following macro.
31799*/
31800#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
31801
31802/*
31803** The journal header size for this pager. This is usually the same
31804** size as a single disk sector. See also setSectorSize().
31805*/
31806#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
31807
31808/*
31809** The macro MEMDB is true if we are dealing with an in-memory database.
31810** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
31811** the value of MEMDB will be a constant and the compiler will optimize
31812** out code that would never execute.
31813*/
31814#ifdef SQLITE_OMIT_MEMORYDB
31815# define MEMDB 0
31816#else
31817# define MEMDB pPager->memDb
31818#endif
31819
31820/*
31821** The maximum legal page number is (2^31 - 1).
31822*/
31823#define PAGER_MAX_PGNO 2147483647
31824
31825#ifndef NDEBUG
31826/*
31827** Usage:
31828**
31829**   assert( assert_pager_state(pPager) );
31830*/
31831static int assert_pager_state(Pager *pPager){
31832
31833  /* A temp-file is always in PAGER_EXCLUSIVE or PAGER_SYNCED state. */
31834  assert( pPager->tempFile==0 || pPager->state>=PAGER_EXCLUSIVE );
31835
31836  /* The changeCountDone flag is always set for temp-files */
31837  assert( pPager->tempFile==0 || pPager->changeCountDone );
31838
31839  return 1;
31840}
31841#endif
31842
31843/*
31844** Return true if it is necessary to write page *pPg into the sub-journal.
31845** A page needs to be written into the sub-journal if there exists one
31846** or more open savepoints for which:
31847**
31848**   * The page-number is less than or equal to PagerSavepoint.nOrig, and
31849**   * The bit corresponding to the page-number is not set in
31850**     PagerSavepoint.pInSavepoint.
31851*/
31852static int subjRequiresPage(PgHdr *pPg){
31853  Pgno pgno = pPg->pgno;
31854  Pager *pPager = pPg->pPager;
31855  int i;
31856  for(i=0; i<pPager->nSavepoint; i++){
31857    PagerSavepoint *p = &pPager->aSavepoint[i];
31858    if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
31859      return 1;
31860    }
31861  }
31862  return 0;
31863}
31864
31865/*
31866** Return true if the page is already in the journal file.
31867*/
31868static int pageInJournal(PgHdr *pPg){
31869  return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
31870}
31871
31872/*
31873** Read a 32-bit integer from the given file descriptor.  Store the integer
31874** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
31875** error code is something goes wrong.
31876**
31877** All values are stored on disk as big-endian.
31878*/
31879static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
31880  unsigned char ac[4];
31881  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
31882  if( rc==SQLITE_OK ){
31883    *pRes = sqlite3Get4byte(ac);
31884  }
31885  return rc;
31886}
31887
31888/*
31889** Write a 32-bit integer into a string buffer in big-endian byte order.
31890*/
31891#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
31892
31893/*
31894** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
31895** on success or an error code is something goes wrong.
31896*/
31897static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
31898  char ac[4];
31899  put32bits(ac, val);
31900  return sqlite3OsWrite(fd, ac, 4, offset);
31901}
31902
31903/*
31904** The argument to this macro is a file descriptor (type sqlite3_file*).
31905** Return 0 if it is not open, or non-zero (but not 1) if it is.
31906**
31907** This is so that expressions can be written as:
31908**
31909**   if( isOpen(pPager->jfd) ){ ...
31910**
31911** instead of
31912**
31913**   if( pPager->jfd->pMethods ){ ...
31914*/
31915#define isOpen(pFd) ((pFd)->pMethods)
31916
31917/*
31918** If file pFd is open, call sqlite3OsUnlock() on it.
31919*/
31920static int osUnlock(sqlite3_file *pFd, int eLock){
31921  if( !isOpen(pFd) ){
31922    return SQLITE_OK;
31923  }
31924  return sqlite3OsUnlock(pFd, eLock);
31925}
31926
31927/*
31928** This function determines whether or not the atomic-write optimization
31929** can be used with this pager. The optimization can be used if:
31930**
31931**  (a) the value returned by OsDeviceCharacteristics() indicates that
31932**      a database page may be written atomically, and
31933**  (b) the value returned by OsSectorSize() is less than or equal
31934**      to the page size.
31935**
31936** The optimization is also always enabled for temporary files. It is
31937** an error to call this function if pPager is opened on an in-memory
31938** database.
31939**
31940** If the optimization cannot be used, 0 is returned. If it can be used,
31941** then the value returned is the size of the journal file when it
31942** contains rollback data for exactly one page.
31943*/
31944#ifdef SQLITE_ENABLE_ATOMIC_WRITE
31945static int jrnlBufferSize(Pager *pPager){
31946  assert( !MEMDB );
31947  if( !pPager->tempFile ){
31948    int dc;                           /* Device characteristics */
31949    int nSector;                      /* Sector size */
31950    int szPage;                       /* Page size */
31951
31952    assert( isOpen(pPager->fd) );
31953    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
31954    nSector = pPager->sectorSize;
31955    szPage = pPager->pageSize;
31956
31957    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
31958    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
31959    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
31960      return 0;
31961    }
31962  }
31963
31964  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
31965}
31966#endif
31967
31968/*
31969** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
31970** on the cache using a hash function.  This is used for testing
31971** and debugging only.
31972*/
31973#ifdef SQLITE_CHECK_PAGES
31974/*
31975** Return a 32-bit hash of the page data for pPage.
31976*/
31977static u32 pager_datahash(int nByte, unsigned char *pData){
31978  u32 hash = 0;
31979  int i;
31980  for(i=0; i<nByte; i++){
31981    hash = (hash*1039) + pData[i];
31982  }
31983  return hash;
31984}
31985static u32 pager_pagehash(PgHdr *pPage){
31986  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
31987}
31988static void pager_set_pagehash(PgHdr *pPage){
31989  pPage->pageHash = pager_pagehash(pPage);
31990}
31991
31992/*
31993** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
31994** is defined, and NDEBUG is not defined, an assert() statement checks
31995** that the page is either dirty or still matches the calculated page-hash.
31996*/
31997#define CHECK_PAGE(x) checkPage(x)
31998static void checkPage(PgHdr *pPg){
31999  Pager *pPager = pPg->pPager;
32000  assert( !pPg->pageHash || pPager->errCode
32001      || (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
32002}
32003
32004#else
32005#define pager_datahash(X,Y)  0
32006#define pager_pagehash(X)  0
32007#define CHECK_PAGE(x)
32008#endif  /* SQLITE_CHECK_PAGES */
32009
32010/*
32011** When this is called the journal file for pager pPager must be open.
32012** This function attempts to read a master journal file name from the
32013** end of the file and, if successful, copies it into memory supplied
32014** by the caller. See comments above writeMasterJournal() for the format
32015** used to store a master journal file name at the end of a journal file.
32016**
32017** zMaster must point to a buffer of at least nMaster bytes allocated by
32018** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
32019** enough space to write the master journal name). If the master journal
32020** name in the journal is longer than nMaster bytes (including a
32021** nul-terminator), then this is handled as if no master journal name
32022** were present in the journal.
32023**
32024** If a master journal file name is present at the end of the journal
32025** file, then it is copied into the buffer pointed to by zMaster. A
32026** nul-terminator byte is appended to the buffer following the master
32027** journal file name.
32028**
32029** If it is determined that no master journal file name is present
32030** zMaster[0] is set to 0 and SQLITE_OK returned.
32031**
32032** If an error occurs while reading from the journal file, an SQLite
32033** error code is returned.
32034*/
32035static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
32036  int rc;                    /* Return code */
32037  u32 len;                   /* Length in bytes of master journal name */
32038  i64 szJ;                   /* Total size in bytes of journal file pJrnl */
32039  u32 cksum;                 /* MJ checksum value read from journal */
32040  u32 u;                     /* Unsigned loop counter */
32041  unsigned char aMagic[8];   /* A buffer to hold the magic header */
32042  zMaster[0] = '\0';
32043
32044  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
32045   || szJ<16
32046   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
32047   || len>=nMaster
32048   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
32049   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
32050   || memcmp(aMagic, aJournalMagic, 8)
32051   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
32052  ){
32053    return rc;
32054  }
32055
32056  /* See if the checksum matches the master journal name */
32057  for(u=0; u<len; u++){
32058    cksum -= zMaster[u];
32059  }
32060  if( cksum ){
32061    /* If the checksum doesn't add up, then one or more of the disk sectors
32062    ** containing the master journal filename is corrupted. This means
32063    ** definitely roll back, so just return SQLITE_OK and report a (nul)
32064    ** master-journal filename.
32065    */
32066    len = 0;
32067  }
32068  zMaster[len] = '\0';
32069
32070  return SQLITE_OK;
32071}
32072
32073/*
32074** Return the offset of the sector boundary at or immediately
32075** following the value in pPager->journalOff, assuming a sector
32076** size of pPager->sectorSize bytes.
32077**
32078** i.e for a sector size of 512:
32079**
32080**   Pager.journalOff          Return value
32081**   ---------------------------------------
32082**   0                         0
32083**   512                       512
32084**   100                       512
32085**   2000                      2048
32086**
32087*/
32088static i64 journalHdrOffset(Pager *pPager){
32089  i64 offset = 0;
32090  i64 c = pPager->journalOff;
32091  if( c ){
32092    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
32093  }
32094  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
32095  assert( offset>=c );
32096  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
32097  return offset;
32098}
32099
32100/*
32101** The journal file must be open when this function is called.
32102**
32103** This function is a no-op if the journal file has not been written to
32104** within the current transaction (i.e. if Pager.journalOff==0).
32105**
32106** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
32107** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
32108** zero the 28-byte header at the start of the journal file. In either case,
32109** if the pager is not in no-sync mode, sync the journal file immediately
32110** after writing or truncating it.
32111**
32112** If Pager.journalSizeLimit is set to a positive, non-zero value, and
32113** following the truncation or zeroing described above the size of the
32114** journal file in bytes is larger than this value, then truncate the
32115** journal file to Pager.journalSizeLimit bytes. The journal file does
32116** not need to be synced following this operation.
32117**
32118** If an IO error occurs, abandon processing and return the IO error code.
32119** Otherwise, return SQLITE_OK.
32120*/
32121static int zeroJournalHdr(Pager *pPager, int doTruncate){
32122  int rc = SQLITE_OK;                               /* Return code */
32123  assert( isOpen(pPager->jfd) );
32124  if( pPager->journalOff ){
32125    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
32126
32127    IOTRACE(("JZEROHDR %p\n", pPager))
32128    if( doTruncate || iLimit==0 ){
32129      rc = sqlite3OsTruncate(pPager->jfd, 0);
32130    }else{
32131      static const char zeroHdr[28] = {0};
32132      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
32133    }
32134    if( rc==SQLITE_OK && !pPager->noSync ){
32135      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
32136    }
32137
32138    /* At this point the transaction is committed but the write lock
32139    ** is still held on the file. If there is a size limit configured for
32140    ** the persistent journal and the journal file currently consumes more
32141    ** space than that limit allows for, truncate it now. There is no need
32142    ** to sync the file following this operation.
32143    */
32144    if( rc==SQLITE_OK && iLimit>0 ){
32145      i64 sz;
32146      rc = sqlite3OsFileSize(pPager->jfd, &sz);
32147      if( rc==SQLITE_OK && sz>iLimit ){
32148        rc = sqlite3OsTruncate(pPager->jfd, iLimit);
32149      }
32150    }
32151  }
32152  return rc;
32153}
32154
32155/*
32156** The journal file must be open when this routine is called. A journal
32157** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
32158** current location.
32159**
32160** The format for the journal header is as follows:
32161** - 8 bytes: Magic identifying journal format.
32162** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
32163** - 4 bytes: Random number used for page hash.
32164** - 4 bytes: Initial database page count.
32165** - 4 bytes: Sector size used by the process that wrote this journal.
32166** - 4 bytes: Database page size.
32167**
32168** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
32169*/
32170static int writeJournalHdr(Pager *pPager){
32171  int rc = SQLITE_OK;                 /* Return code */
32172  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
32173  u32 nHeader = pPager->pageSize;     /* Size of buffer pointed to by zHeader */
32174  u32 nWrite;                         /* Bytes of header sector written */
32175  int ii;                             /* Loop counter */
32176
32177  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
32178
32179  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
32180    nHeader = JOURNAL_HDR_SZ(pPager);
32181  }
32182
32183  /* If there are active savepoints and any of them were created
32184  ** since the most recent journal header was written, update the
32185  ** PagerSavepoint.iHdrOffset fields now.
32186  */
32187  for(ii=0; ii<pPager->nSavepoint; ii++){
32188    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
32189      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
32190    }
32191  }
32192
32193  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
32194
32195  /*
32196  ** Write the nRec Field - the number of page records that follow this
32197  ** journal header. Normally, zero is written to this value at this time.
32198  ** After the records are added to the journal (and the journal synced,
32199  ** if in full-sync mode), the zero is overwritten with the true number
32200  ** of records (see syncJournal()).
32201  **
32202  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
32203  ** reading the journal this value tells SQLite to assume that the
32204  ** rest of the journal file contains valid page records. This assumption
32205  ** is dangerous, as if a failure occurred whilst writing to the journal
32206  ** file it may contain some garbage data. There are two scenarios
32207  ** where this risk can be ignored:
32208  **
32209  **   * When the pager is in no-sync mode. Corruption can follow a
32210  **     power failure in this case anyway.
32211  **
32212  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
32213  **     that garbage data is never appended to the journal file.
32214  */
32215  assert( isOpen(pPager->fd) || pPager->noSync );
32216  if( (pPager->noSync) || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
32217   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
32218  ){
32219    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
32220    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
32221  }else{
32222    memset(zHeader, 0, sizeof(aJournalMagic)+4);
32223  }
32224
32225  /* The random check-hash initialiser */
32226  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
32227  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
32228  /* The initial database size */
32229  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
32230  /* The assumed sector size for this process */
32231  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
32232
32233  /* The page size */
32234  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
32235
32236  /* Initializing the tail of the buffer is not necessary.  Everything
32237  ** works find if the following memset() is omitted.  But initializing
32238  ** the memory prevents valgrind from complaining, so we are willing to
32239  ** take the performance hit.
32240  */
32241  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
32242         nHeader-(sizeof(aJournalMagic)+20));
32243
32244  /* In theory, it is only necessary to write the 28 bytes that the
32245  ** journal header consumes to the journal file here. Then increment the
32246  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
32247  ** record is written to the following sector (leaving a gap in the file
32248  ** that will be implicitly filled in by the OS).
32249  **
32250  ** However it has been discovered that on some systems this pattern can
32251  ** be significantly slower than contiguously writing data to the file,
32252  ** even if that means explicitly writing data to the block of
32253  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
32254  ** is done.
32255  **
32256  ** The loop is required here in case the sector-size is larger than the
32257  ** database page size. Since the zHeader buffer is only Pager.pageSize
32258  ** bytes in size, more than one call to sqlite3OsWrite() may be required
32259  ** to populate the entire journal header sector.
32260  */
32261  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
32262    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
32263    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
32264    pPager->journalOff += nHeader;
32265  }
32266
32267  return rc;
32268}
32269
32270/*
32271** The journal file must be open when this is called. A journal header file
32272** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
32273** file. The current location in the journal file is given by
32274** pPager->journalOff. See comments above function writeJournalHdr() for
32275** a description of the journal header format.
32276**
32277** If the header is read successfully, *pNRec is set to the number of
32278** page records following this header and *pDbSize is set to the size of the
32279** database before the transaction began, in pages. Also, pPager->cksumInit
32280** is set to the value read from the journal header. SQLITE_OK is returned
32281** in this case.
32282**
32283** If the journal header file appears to be corrupted, SQLITE_DONE is
32284** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
32285** cannot be read from the journal file an error code is returned.
32286*/
32287static int readJournalHdr(
32288  Pager *pPager,               /* Pager object */
32289  int isHot,
32290  i64 journalSize,             /* Size of the open journal file in bytes */
32291  u32 *pNRec,                  /* OUT: Value read from the nRec field */
32292  u32 *pDbSize                 /* OUT: Value of original database size field */
32293){
32294  int rc;                      /* Return code */
32295  unsigned char aMagic[8];     /* A buffer to hold the magic header */
32296  i64 iHdrOff;                 /* Offset of journal header being read */
32297
32298  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
32299
32300  /* Advance Pager.journalOff to the start of the next sector. If the
32301  ** journal file is too small for there to be a header stored at this
32302  ** point, return SQLITE_DONE.
32303  */
32304  pPager->journalOff = journalHdrOffset(pPager);
32305  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
32306    return SQLITE_DONE;
32307  }
32308  iHdrOff = pPager->journalOff;
32309
32310  /* Read in the first 8 bytes of the journal header. If they do not match
32311  ** the  magic string found at the start of each journal header, return
32312  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
32313  ** proceed.
32314  */
32315  if( isHot || iHdrOff!=pPager->journalHdr ){
32316    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
32317    if( rc ){
32318      return rc;
32319    }
32320    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
32321      return SQLITE_DONE;
32322    }
32323  }
32324
32325  /* Read the first three 32-bit fields of the journal header: The nRec
32326  ** field, the checksum-initializer and the database size at the start
32327  ** of the transaction. Return an error code if anything goes wrong.
32328  */
32329  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
32330   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
32331   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
32332  ){
32333    return rc;
32334  }
32335
32336  if( pPager->journalOff==0 ){
32337    u32 iPageSize;               /* Page-size field of journal header */
32338    u32 iSectorSize;             /* Sector-size field of journal header */
32339    u16 iPageSize16;             /* Copy of iPageSize in 16-bit variable */
32340
32341    /* Read the page-size and sector-size journal header fields. */
32342    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
32343     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
32344    ){
32345      return rc;
32346    }
32347
32348    /* Check that the values read from the page-size and sector-size fields
32349    ** are within range. To be 'in range', both values need to be a power
32350    ** of two greater than or equal to 512 or 32, and not greater than their
32351    ** respective compile time maximum limits.
32352    */
32353    if( iPageSize<512                  || iSectorSize<32
32354     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
32355     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
32356    ){
32357      /* If the either the page-size or sector-size in the journal-header is
32358      ** invalid, then the process that wrote the journal-header must have
32359      ** crashed before the header was synced. In this case stop reading
32360      ** the journal file here.
32361      */
32362      return SQLITE_DONE;
32363    }
32364
32365    /* Update the page-size to match the value read from the journal.
32366    ** Use a testcase() macro to make sure that malloc failure within
32367    ** PagerSetPagesize() is tested.
32368    */
32369    iPageSize16 = (u16)iPageSize;
32370    rc = sqlite3PagerSetPagesize(pPager, &iPageSize16, -1);
32371    testcase( rc!=SQLITE_OK );
32372    assert( rc!=SQLITE_OK || iPageSize16==(u16)iPageSize );
32373
32374    /* Update the assumed sector-size to match the value used by
32375    ** the process that created this journal. If this journal was
32376    ** created by a process other than this one, then this routine
32377    ** is being called from within pager_playback(). The local value
32378    ** of Pager.sectorSize is restored at the end of that routine.
32379    */
32380    pPager->sectorSize = iSectorSize;
32381  }
32382
32383  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
32384  return rc;
32385}
32386
32387
32388/*
32389** Write the supplied master journal name into the journal file for pager
32390** pPager at the current location. The master journal name must be the last
32391** thing written to a journal file. If the pager is in full-sync mode, the
32392** journal file descriptor is advanced to the next sector boundary before
32393** anything is written. The format is:
32394**
32395**   + 4 bytes: PAGER_MJ_PGNO.
32396**   + N bytes: Master journal filename in utf-8.
32397**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
32398**   + 4 bytes: Master journal name checksum.
32399**   + 8 bytes: aJournalMagic[].
32400**
32401** The master journal page checksum is the sum of the bytes in the master
32402** journal name, where each byte is interpreted as a signed 8-bit integer.
32403**
32404** If zMaster is a NULL pointer (occurs for a single database transaction),
32405** this call is a no-op.
32406*/
32407static int writeMasterJournal(Pager *pPager, const char *zMaster){
32408  int rc;                          /* Return code */
32409  int nMaster;                     /* Length of string zMaster */
32410  i64 iHdrOff;                     /* Offset of header in journal file */
32411  i64 jrnlSize;                    /* Size of journal file on disk */
32412  u32 cksum = 0;                   /* Checksum of string zMaster */
32413
32414  if( !zMaster || pPager->setMaster
32415   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
32416   || pPager->journalMode==PAGER_JOURNALMODE_OFF
32417  ){
32418    return SQLITE_OK;
32419  }
32420  pPager->setMaster = 1;
32421  assert( isOpen(pPager->jfd) );
32422
32423  /* Calculate the length in bytes and the checksum of zMaster */
32424  for(nMaster=0; zMaster[nMaster]; nMaster++){
32425    cksum += zMaster[nMaster];
32426  }
32427
32428  /* If in full-sync mode, advance to the next disk sector before writing
32429  ** the master journal name. This is in case the previous page written to
32430  ** the journal has already been synced.
32431  */
32432  if( pPager->fullSync ){
32433    pPager->journalOff = journalHdrOffset(pPager);
32434  }
32435  iHdrOff = pPager->journalOff;
32436
32437  /* Write the master journal data to the end of the journal file. If
32438  ** an error occurs, return the error code to the caller.
32439  */
32440  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
32441   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
32442   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
32443   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
32444   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
32445  ){
32446    return rc;
32447  }
32448  pPager->journalOff += (nMaster+20);
32449  pPager->needSync = !pPager->noSync;
32450
32451  /* If the pager is in peristent-journal mode, then the physical
32452  ** journal-file may extend past the end of the master-journal name
32453  ** and 8 bytes of magic data just written to the file. This is
32454  ** dangerous because the code to rollback a hot-journal file
32455  ** will not be able to find the master-journal name to determine
32456  ** whether or not the journal is hot.
32457  **
32458  ** Easiest thing to do in this scenario is to truncate the journal
32459  ** file to the required size.
32460  */
32461  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
32462   && jrnlSize>pPager->journalOff
32463  ){
32464    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
32465  }
32466  return rc;
32467}
32468
32469/*
32470** Find a page in the hash table given its page number. Return
32471** a pointer to the page or NULL if the requested page is not
32472** already in memory.
32473*/
32474static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
32475  PgHdr *p;                         /* Return value */
32476
32477  /* It is not possible for a call to PcacheFetch() with createFlag==0 to
32478  ** fail, since no attempt to allocate dynamic memory will be made.
32479  */
32480  (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
32481  return p;
32482}
32483
32484/*
32485** Unless the pager is in error-state, discard all in-memory pages. If
32486** the pager is in error-state, then this call is a no-op.
32487**
32488** TODO: Why can we not reset the pager while in error state?
32489*/
32490static void pager_reset(Pager *pPager){
32491  if( SQLITE_OK==pPager->errCode ){
32492    sqlite3BackupRestart(pPager->pBackup);
32493    sqlite3PcacheClear(pPager->pPCache);
32494    pPager->dbSizeValid = 0;
32495  }
32496}
32497
32498/*
32499** Free all structures in the Pager.aSavepoint[] array and set both
32500** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
32501** if it is open and the pager is not in exclusive mode.
32502*/
32503static void releaseAllSavepoints(Pager *pPager){
32504  int ii;               /* Iterator for looping through Pager.aSavepoint */
32505  for(ii=0; ii<pPager->nSavepoint; ii++){
32506    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
32507  }
32508  if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
32509    sqlite3OsClose(pPager->sjfd);
32510  }
32511  sqlite3_free(pPager->aSavepoint);
32512  pPager->aSavepoint = 0;
32513  pPager->nSavepoint = 0;
32514  pPager->nSubRec = 0;
32515}
32516
32517/*
32518** Set the bit number pgno in the PagerSavepoint.pInSavepoint
32519** bitvecs of all open savepoints. Return SQLITE_OK if successful
32520** or SQLITE_NOMEM if a malloc failure occurs.
32521*/
32522static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
32523  int ii;                   /* Loop counter */
32524  int rc = SQLITE_OK;       /* Result code */
32525
32526  for(ii=0; ii<pPager->nSavepoint; ii++){
32527    PagerSavepoint *p = &pPager->aSavepoint[ii];
32528    if( pgno<=p->nOrig ){
32529      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
32530      testcase( rc==SQLITE_NOMEM );
32531      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
32532    }
32533  }
32534  return rc;
32535}
32536
32537/*
32538** Unlock the database file. This function is a no-op if the pager
32539** is in exclusive mode.
32540**
32541** If the pager is currently in error state, discard the contents of
32542** the cache and reset the Pager structure internal state. If there is
32543** an open journal-file, then the next time a shared-lock is obtained
32544** on the pager file (by this or any other process), it will be
32545** treated as a hot-journal and rolled back.
32546*/
32547static void pager_unlock(Pager *pPager){
32548  if( !pPager->exclusiveMode ){
32549    int rc;                      /* Return code */
32550
32551    /* Always close the journal file when dropping the database lock.
32552    ** Otherwise, another connection with journal_mode=delete might
32553    ** delete the file out from under us.
32554    */
32555    sqlite3OsClose(pPager->jfd);
32556    sqlite3BitvecDestroy(pPager->pInJournal);
32557    pPager->pInJournal = 0;
32558    releaseAllSavepoints(pPager);
32559
32560    /* If the file is unlocked, somebody else might change it. The
32561    ** values stored in Pager.dbSize etc. might become invalid if
32562    ** this happens. TODO: Really, this doesn't need to be cleared
32563    ** until the change-counter check fails in PagerSharedLock().
32564    */
32565    pPager->dbSizeValid = 0;
32566
32567    rc = osUnlock(pPager->fd, NO_LOCK);
32568    if( rc ){
32569      pPager->errCode = rc;
32570    }
32571    IOTRACE(("UNLOCK %p\n", pPager))
32572
32573    /* If Pager.errCode is set, the contents of the pager cache cannot be
32574    ** trusted. Now that the pager file is unlocked, the contents of the
32575    ** cache can be discarded and the error code safely cleared.
32576    */
32577    if( pPager->errCode ){
32578      if( rc==SQLITE_OK ){
32579        pPager->errCode = SQLITE_OK;
32580      }
32581      pager_reset(pPager);
32582    }
32583
32584    pPager->changeCountDone = 0;
32585    pPager->state = PAGER_UNLOCK;
32586    pPager->dbModified = 0;
32587  }
32588}
32589
32590/*
32591** This function should be called when an IOERR, CORRUPT or FULL error
32592** may have occurred. The first argument is a pointer to the pager
32593** structure, the second the error-code about to be returned by a pager
32594** API function. The value returned is a copy of the second argument
32595** to this function.
32596**
32597** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
32598** the error becomes persistent. Until the persisten error is cleared,
32599** subsequent API calls on this Pager will immediately return the same
32600** error code.
32601**
32602** A persistent error indicates that the contents of the pager-cache
32603** cannot be trusted. This state can be cleared by completely discarding
32604** the contents of the pager-cache. If a transaction was active when
32605** the persistent error occurred, then the rollback journal may need
32606** to be replayed to restore the contents of the database file (as if
32607** it were a hot-journal).
32608*/
32609static int pager_error(Pager *pPager, int rc){
32610  int rc2 = rc & 0xff;
32611  assert( rc==SQLITE_OK || !MEMDB );
32612  assert(
32613       pPager->errCode==SQLITE_FULL ||
32614       pPager->errCode==SQLITE_OK ||
32615       (pPager->errCode & 0xff)==SQLITE_IOERR
32616  );
32617  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
32618    pPager->errCode = rc;
32619  }
32620  return rc;
32621}
32622
32623/*
32624** Execute a rollback if a transaction is active and unlock the
32625** database file.
32626**
32627** If the pager has already entered the error state, do not attempt
32628** the rollback at this time. Instead, pager_unlock() is called. The
32629** call to pager_unlock() will discard all in-memory pages, unlock
32630** the database file and clear the error state. If this means that
32631** there is a hot-journal left in the file-system, the next connection
32632** to obtain a shared lock on the pager (which may be this one) will
32633** roll it back.
32634**
32635** If the pager has not already entered the error state, but an IO or
32636** malloc error occurs during a rollback, then this will itself cause
32637** the pager to enter the error state. Which will be cleared by the
32638** call to pager_unlock(), as described above.
32639*/
32640static void pagerUnlockAndRollback(Pager *pPager){
32641  if( pPager->errCode==SQLITE_OK && pPager->state>=PAGER_RESERVED ){
32642    sqlite3BeginBenignMalloc();
32643    sqlite3PagerRollback(pPager);
32644    sqlite3EndBenignMalloc();
32645  }
32646  pager_unlock(pPager);
32647}
32648
32649/*
32650** This routine ends a transaction. A transaction is usually ended by
32651** either a COMMIT or a ROLLBACK operation. This routine may be called
32652** after rollback of a hot-journal, or if an error occurs while opening
32653** the journal file or writing the very first journal-header of a
32654** database transaction.
32655**
32656** If the pager is in PAGER_SHARED or PAGER_UNLOCK state when this
32657** routine is called, it is a no-op (returns SQLITE_OK).
32658**
32659** Otherwise, any active savepoints are released.
32660**
32661** If the journal file is open, then it is "finalized". Once a journal
32662** file has been finalized it is not possible to use it to roll back a
32663** transaction. Nor will it be considered to be a hot-journal by this
32664** or any other database connection. Exactly how a journal is finalized
32665** depends on whether or not the pager is running in exclusive mode and
32666** the current journal-mode (Pager.journalMode value), as follows:
32667**
32668**   journalMode==MEMORY
32669**     Journal file descriptor is simply closed. This destroys an
32670**     in-memory journal.
32671**
32672**   journalMode==TRUNCATE
32673**     Journal file is truncated to zero bytes in size.
32674**
32675**   journalMode==PERSIST
32676**     The first 28 bytes of the journal file are zeroed. This invalidates
32677**     the first journal header in the file, and hence the entire journal
32678**     file. An invalid journal file cannot be rolled back.
32679**
32680**   journalMode==DELETE
32681**     The journal file is closed and deleted using sqlite3OsDelete().
32682**
32683**     If the pager is running in exclusive mode, this method of finalizing
32684**     the journal file is never used. Instead, if the journalMode is
32685**     DELETE and the pager is in exclusive mode, the method described under
32686**     journalMode==PERSIST is used instead.
32687**
32688** After the journal is finalized, if running in non-exclusive mode, the
32689** pager moves to PAGER_SHARED state (and downgrades the lock on the
32690** database file accordingly).
32691**
32692** If the pager is running in exclusive mode and is in PAGER_SYNCED state,
32693** it moves to PAGER_EXCLUSIVE. No locks are downgraded when running in
32694** exclusive mode.
32695**
32696** SQLITE_OK is returned if no error occurs. If an error occurs during
32697** any of the IO operations to finalize the journal file or unlock the
32698** database then the IO error code is returned to the user. If the
32699** operation to finalize the journal file fails, then the code still
32700** tries to unlock the database file if not in exclusive mode. If the
32701** unlock operation fails as well, then the first error code related
32702** to the first error encountered (the journal finalization one) is
32703** returned.
32704*/
32705static int pager_end_transaction(Pager *pPager, int hasMaster){
32706  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
32707  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
32708
32709  if( pPager->state<PAGER_RESERVED ){
32710    return SQLITE_OK;
32711  }
32712  releaseAllSavepoints(pPager);
32713
32714  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
32715  if( isOpen(pPager->jfd) ){
32716
32717    /* Finalize the journal file. */
32718    if( sqlite3IsMemJournal(pPager->jfd) ){
32719      assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
32720      sqlite3OsClose(pPager->jfd);
32721    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
32722      if( pPager->journalOff==0 ){
32723        rc = SQLITE_OK;
32724      }else{
32725        rc = sqlite3OsTruncate(pPager->jfd, 0);
32726      }
32727      pPager->journalOff = 0;
32728      pPager->journalStarted = 0;
32729    }else if( pPager->exclusiveMode
32730     || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
32731    ){
32732      rc = zeroJournalHdr(pPager, hasMaster);
32733      pager_error(pPager, rc);
32734      pPager->journalOff = 0;
32735      pPager->journalStarted = 0;
32736    }else{
32737      /* This branch may be executed with Pager.journalMode==MEMORY if
32738      ** a hot-journal was just rolled back. In this case the journal
32739      ** file should be closed and deleted. If this connection writes to
32740      ** the database file, it will do so using an in-memory journal.  */
32741      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
32742           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
32743      );
32744      sqlite3OsClose(pPager->jfd);
32745      if( !pPager->tempFile ){
32746        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
32747      }
32748    }
32749
32750#ifdef SQLITE_CHECK_PAGES
32751    sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
32752#endif
32753
32754    sqlite3PcacheCleanAll(pPager->pPCache);
32755    sqlite3BitvecDestroy(pPager->pInJournal);
32756    pPager->pInJournal = 0;
32757    pPager->nRec = 0;
32758  }
32759
32760  if( !pPager->exclusiveMode ){
32761    rc2 = osUnlock(pPager->fd, SHARED_LOCK);
32762    pPager->state = PAGER_SHARED;
32763    pPager->changeCountDone = 0;
32764  }else if( pPager->state==PAGER_SYNCED ){
32765    pPager->state = PAGER_EXCLUSIVE;
32766  }
32767  pPager->setMaster = 0;
32768  pPager->needSync = 0;
32769  pPager->dbModified = 0;
32770
32771  /* TODO: Is this optimal? Why is the db size invalidated here
32772  ** when the database file is not unlocked? */
32773  pPager->dbOrigSize = 0;
32774  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
32775  if( !MEMDB ){
32776    pPager->dbSizeValid = 0;
32777  }
32778
32779  return (rc==SQLITE_OK?rc2:rc);
32780}
32781
32782/*
32783** Parameter aData must point to a buffer of pPager->pageSize bytes
32784** of data. Compute and return a checksum based ont the contents of the
32785** page of data and the current value of pPager->cksumInit.
32786**
32787** This is not a real checksum. It is really just the sum of the
32788** random initial value (pPager->cksumInit) and every 200th byte
32789** of the page data, starting with byte offset (pPager->pageSize%200).
32790** Each byte is interpreted as an 8-bit unsigned integer.
32791**
32792** Changing the formula used to compute this checksum results in an
32793** incompatible journal file format.
32794**
32795** If journal corruption occurs due to a power failure, the most likely
32796** scenario is that one end or the other of the record will be changed.
32797** It is much less likely that the two ends of the journal record will be
32798** correct and the middle be corrupt.  Thus, this "checksum" scheme,
32799** though fast and simple, catches the mostly likely kind of corruption.
32800*/
32801static u32 pager_cksum(Pager *pPager, const u8 *aData){
32802  u32 cksum = pPager->cksumInit;         /* Checksum value to return */
32803  int i = pPager->pageSize-200;          /* Loop counter */
32804  while( i>0 ){
32805    cksum += aData[i];
32806    i -= 200;
32807  }
32808  return cksum;
32809}
32810
32811/*
32812** Read a single page from either the journal file (if isMainJrnl==1) or
32813** from the sub-journal (if isMainJrnl==0) and playback that page.
32814** The page begins at offset *pOffset into the file. The *pOffset
32815** value is increased to the start of the next page in the journal.
32816**
32817** The isMainJrnl flag is true if this is the main rollback journal and
32818** false for the statement journal.  The main rollback journal uses
32819** checksums - the statement journal does not.
32820**
32821** If the page number of the page record read from the (sub-)journal file
32822** is greater than the current value of Pager.dbSize, then playback is
32823** skipped and SQLITE_OK is returned.
32824**
32825** If pDone is not NULL, then it is a record of pages that have already
32826** been played back.  If the page at *pOffset has already been played back
32827** (if the corresponding pDone bit is set) then skip the playback.
32828** Make sure the pDone bit corresponding to the *pOffset page is set
32829** prior to returning.
32830**
32831** If the page record is successfully read from the (sub-)journal file
32832** and played back, then SQLITE_OK is returned. If an IO error occurs
32833** while reading the record from the (sub-)journal file or while writing
32834** to the database file, then the IO error code is returned. If data
32835** is successfully read from the (sub-)journal file but appears to be
32836** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
32837** two circumstances:
32838**
32839**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
32840**   * If the record is being rolled back from the main journal file
32841**     and the checksum field does not match the record content.
32842**
32843** Neither of these two scenarios are possible during a savepoint rollback.
32844**
32845** If this is a savepoint rollback, then memory may have to be dynamically
32846** allocated by this function. If this is the case and an allocation fails,
32847** SQLITE_NOMEM is returned.
32848*/
32849static int pager_playback_one_page(
32850  Pager *pPager,                /* The pager being played back */
32851  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
32852  int isUnsync,                 /* True if reading from unsynced main journal */
32853  i64 *pOffset,                 /* Offset of record to playback */
32854  int isSavepnt,                /* True for a savepoint rollback */
32855  Bitvec *pDone                 /* Bitvec of pages already played back */
32856){
32857  int rc;
32858  PgHdr *pPg;                   /* An existing page in the cache */
32859  Pgno pgno;                    /* The page number of a page in journal */
32860  u32 cksum;                    /* Checksum used for sanity checking */
32861  char *aData;                  /* Temporary storage for the page */
32862  sqlite3_file *jfd;            /* The file descriptor for the journal file */
32863
32864  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
32865  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
32866  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
32867  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
32868
32869  aData = pPager->pTmpSpace;
32870  assert( aData );         /* Temp storage must have already been allocated */
32871
32872  /* Read the page number and page data from the journal or sub-journal
32873  ** file. Return an error code to the caller if an IO error occurs.
32874  */
32875  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
32876  rc = read32bits(jfd, *pOffset, &pgno);
32877  if( rc!=SQLITE_OK ) return rc;
32878  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
32879  if( rc!=SQLITE_OK ) return rc;
32880  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
32881
32882  /* Sanity checking on the page.  This is more important that I originally
32883  ** thought.  If a power failure occurs while the journal is being written,
32884  ** it could cause invalid data to be written into the journal.  We need to
32885  ** detect this invalid data (with high probability) and ignore it.
32886  */
32887  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
32888    assert( !isSavepnt );
32889    return SQLITE_DONE;
32890  }
32891  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
32892    return SQLITE_OK;
32893  }
32894  if( isMainJrnl ){
32895    rc = read32bits(jfd, (*pOffset)-4, &cksum);
32896    if( rc ) return rc;
32897    if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
32898      return SQLITE_DONE;
32899    }
32900  }
32901
32902  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
32903    return rc;
32904  }
32905
32906  assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
32907
32908  /* If the pager is in RESERVED state, then there must be a copy of this
32909  ** page in the pager cache. In this case just update the pager cache,
32910  ** not the database file. The page is left marked dirty in this case.
32911  **
32912  ** An exception to the above rule: If the database is in no-sync mode
32913  ** and a page is moved during an incremental vacuum then the page may
32914  ** not be in the pager cache. Later: if a malloc() or IO error occurs
32915  ** during a Movepage() call, then the page may not be in the cache
32916  ** either. So the condition described in the above paragraph is not
32917  ** assert()able.
32918  **
32919  ** If in EXCLUSIVE state, then we update the pager cache if it exists
32920  ** and the main file. The page is then marked not dirty.
32921  **
32922  ** Ticket #1171:  The statement journal might contain page content that is
32923  ** different from the page content at the start of the transaction.
32924  ** This occurs when a page is changed prior to the start of a statement
32925  ** then changed again within the statement.  When rolling back such a
32926  ** statement we must not write to the original database unless we know
32927  ** for certain that original page contents are synced into the main rollback
32928  ** journal.  Otherwise, a power loss might leave modified data in the
32929  ** database file without an entry in the rollback journal that can
32930  ** restore the database to its original form.  Two conditions must be
32931  ** met before writing to the database files. (1) the database must be
32932  ** locked.  (2) we know that the original page content is fully synced
32933  ** in the main journal either because the page is not in cache or else
32934  ** the page is marked as needSync==0.
32935  **
32936  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
32937  ** is possible to fail a statement on a database that does not yet exist.
32938  ** Do not attempt to write if database file has never been opened.
32939  */
32940  pPg = pager_lookup(pPager, pgno);
32941  assert( pPg || !MEMDB );
32942  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
32943           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
32944           (isMainJrnl?"main-journal":"sub-journal")
32945  ));
32946  if( (pPager->state>=PAGER_EXCLUSIVE)
32947   && (pPg==0 || 0==(pPg->flags&PGHDR_NEED_SYNC))
32948   && isOpen(pPager->fd)
32949   && !isUnsync
32950  ){
32951    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
32952    rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
32953    if( pgno>pPager->dbFileSize ){
32954      pPager->dbFileSize = pgno;
32955    }
32956    if( pPager->pBackup ){
32957      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
32958      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
32959      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
32960    }
32961  }else if( !isMainJrnl && pPg==0 ){
32962    /* If this is a rollback of a savepoint and data was not written to
32963    ** the database and the page is not in-memory, there is a potential
32964    ** problem. When the page is next fetched by the b-tree layer, it
32965    ** will be read from the database file, which may or may not be
32966    ** current.
32967    **
32968    ** There are a couple of different ways this can happen. All are quite
32969    ** obscure. When running in synchronous mode, this can only happen
32970    ** if the page is on the free-list at the start of the transaction, then
32971    ** populated, then moved using sqlite3PagerMovepage().
32972    **
32973    ** The solution is to add an in-memory page to the cache containing
32974    ** the data just read from the sub-journal. Mark the page as dirty
32975    ** and if the pager requires a journal-sync, then mark the page as
32976    ** requiring a journal-sync before it is written.
32977    */
32978    assert( isSavepnt );
32979    if( (rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1))!=SQLITE_OK ){
32980      return rc;
32981    }
32982    pPg->flags &= ~PGHDR_NEED_READ;
32983    sqlite3PcacheMakeDirty(pPg);
32984  }
32985  if( pPg ){
32986    /* No page should ever be explicitly rolled back that is in use, except
32987    ** for page 1 which is held in use in order to keep the lock on the
32988    ** database active. However such a page may be rolled back as a result
32989    ** of an internal error resulting in an automatic call to
32990    ** sqlite3PagerRollback().
32991    */
32992    void *pData;
32993    pData = pPg->pData;
32994    memcpy(pData, (u8*)aData, pPager->pageSize);
32995    pPager->xReiniter(pPg);
32996    if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
32997      /* If the contents of this page were just restored from the main
32998      ** journal file, then its content must be as they were when the
32999      ** transaction was first opened. In this case we can mark the page
33000      ** as clean, since there will be no need to write it out to the.
33001      **
33002      ** There is one exception to this rule. If the page is being rolled
33003      ** back as part of a savepoint (or statement) rollback from an
33004      ** unsynced portion of the main journal file, then it is not safe
33005      ** to mark the page as clean. This is because marking the page as
33006      ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
33007      ** already in the journal file (recorded in Pager.pInJournal) and
33008      ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
33009      ** again within this transaction, it will be marked as dirty but
33010      ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
33011      ** be written out into the database file before its journal file
33012      ** segment is synced. If a crash occurs during or following this,
33013      ** database corruption may ensue.
33014      */
33015      sqlite3PcacheMakeClean(pPg);
33016    }
33017#ifdef SQLITE_CHECK_PAGES
33018    pPg->pageHash = pager_pagehash(pPg);
33019#endif
33020    /* If this was page 1, then restore the value of Pager.dbFileVers.
33021    ** Do this before any decoding. */
33022    if( pgno==1 ){
33023      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
33024    }
33025
33026    /* Decode the page just read from disk */
33027    CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
33028    sqlite3PcacheRelease(pPg);
33029  }
33030  return rc;
33031}
33032
33033/*
33034** Parameter zMaster is the name of a master journal file. A single journal
33035** file that referred to the master journal file has just been rolled back.
33036** This routine checks if it is possible to delete the master journal file,
33037** and does so if it is.
33038**
33039** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
33040** available for use within this function.
33041**
33042** When a master journal file is created, it is populated with the names
33043** of all of its child journals, one after another, formatted as utf-8
33044** encoded text. The end of each child journal file is marked with a
33045** nul-terminator byte (0x00). i.e. the entire contents of a master journal
33046** file for a transaction involving two databases might be:
33047**
33048**   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
33049**
33050** A master journal file may only be deleted once all of its child
33051** journals have been rolled back.
33052**
33053** This function reads the contents of the master-journal file into
33054** memory and loops through each of the child journal names. For
33055** each child journal, it checks if:
33056**
33057**   * if the child journal exists, and if so
33058**   * if the child journal contains a reference to master journal
33059**     file zMaster
33060**
33061** If a child journal can be found that matches both of the criteria
33062** above, this function returns without doing anything. Otherwise, if
33063** no such child journal can be found, file zMaster is deleted from
33064** the file-system using sqlite3OsDelete().
33065**
33066** If an IO error within this function, an error code is returned. This
33067** function allocates memory by calling sqlite3Malloc(). If an allocation
33068** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
33069** occur, SQLITE_OK is returned.
33070**
33071** TODO: This function allocates a single block of memory to load
33072** the entire contents of the master journal file. This could be
33073** a couple of kilobytes or so - potentially larger than the page
33074** size.
33075*/
33076static int pager_delmaster(Pager *pPager, const char *zMaster){
33077  sqlite3_vfs *pVfs = pPager->pVfs;
33078  int rc;                   /* Return code */
33079  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
33080  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
33081  char *zMasterJournal = 0; /* Contents of master journal file */
33082  i64 nMasterJournal;       /* Size of master journal file */
33083
33084  /* Allocate space for both the pJournal and pMaster file descriptors.
33085  ** If successful, open the master journal file for reading.
33086  */
33087  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
33088  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
33089  if( !pMaster ){
33090    rc = SQLITE_NOMEM;
33091  }else{
33092    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
33093    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
33094  }
33095  if( rc!=SQLITE_OK ) goto delmaster_out;
33096
33097  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
33098  if( rc!=SQLITE_OK ) goto delmaster_out;
33099
33100  if( nMasterJournal>0 ){
33101    char *zJournal;
33102    char *zMasterPtr = 0;
33103    int nMasterPtr = pVfs->mxPathname+1;
33104
33105    /* Load the entire master journal file into space obtained from
33106    ** sqlite3_malloc() and pointed to by zMasterJournal.
33107    */
33108    zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
33109    if( !zMasterJournal ){
33110      rc = SQLITE_NOMEM;
33111      goto delmaster_out;
33112    }
33113    zMasterPtr = &zMasterJournal[nMasterJournal+1];
33114    rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
33115    if( rc!=SQLITE_OK ) goto delmaster_out;
33116    zMasterJournal[nMasterJournal] = 0;
33117
33118    zJournal = zMasterJournal;
33119    while( (zJournal-zMasterJournal)<nMasterJournal ){
33120      int exists;
33121      rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
33122      if( rc!=SQLITE_OK ){
33123        goto delmaster_out;
33124      }
33125      if( exists ){
33126        /* One of the journals pointed to by the master journal exists.
33127        ** Open it and check if it points at the master journal. If
33128        ** so, return without deleting the master journal file.
33129        */
33130        int c;
33131        int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
33132        rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
33133        if( rc!=SQLITE_OK ){
33134          goto delmaster_out;
33135        }
33136
33137        rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
33138        sqlite3OsClose(pJournal);
33139        if( rc!=SQLITE_OK ){
33140          goto delmaster_out;
33141        }
33142
33143        c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
33144        if( c ){
33145          /* We have a match. Do not delete the master journal file. */
33146          goto delmaster_out;
33147        }
33148      }
33149      zJournal += (sqlite3Strlen30(zJournal)+1);
33150    }
33151  }
33152
33153  rc = sqlite3OsDelete(pVfs, zMaster, 0);
33154
33155delmaster_out:
33156  if( zMasterJournal ){
33157    sqlite3_free(zMasterJournal);
33158  }
33159  if( pMaster ){
33160    sqlite3OsClose(pMaster);
33161    assert( !isOpen(pJournal) );
33162  }
33163  sqlite3_free(pMaster);
33164  return rc;
33165}
33166
33167
33168/*
33169** This function is used to change the actual size of the database
33170** file in the file-system. This only happens when committing a transaction,
33171** or rolling back a transaction (including rolling back a hot-journal).
33172**
33173** If the main database file is not open, or an exclusive lock is not
33174** held, this function is a no-op. Otherwise, the size of the file is
33175** changed to nPage pages (nPage*pPager->pageSize bytes). If the file
33176** on disk is currently larger than nPage pages, then use the VFS
33177** xTruncate() method to truncate it.
33178**
33179** Or, it might might be the case that the file on disk is smaller than
33180** nPage pages. Some operating system implementations can get confused if
33181** you try to truncate a file to some size that is larger than it
33182** currently is, so detect this case and write a single zero byte to
33183** the end of the new file instead.
33184**
33185** If successful, return SQLITE_OK. If an IO error occurs while modifying
33186** the database file, return the error code to the caller.
33187*/
33188static int pager_truncate(Pager *pPager, Pgno nPage){
33189  int rc = SQLITE_OK;
33190  if( pPager->state>=PAGER_EXCLUSIVE && isOpen(pPager->fd) ){
33191    i64 currentSize, newSize;
33192    /* TODO: Is it safe to use Pager.dbFileSize here? */
33193    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
33194    newSize = pPager->pageSize*(i64)nPage;
33195    if( rc==SQLITE_OK && currentSize!=newSize ){
33196      if( currentSize>newSize ){
33197        rc = sqlite3OsTruncate(pPager->fd, newSize);
33198      }else{
33199        rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
33200      }
33201      if( rc==SQLITE_OK ){
33202        pPager->dbFileSize = nPage;
33203      }
33204    }
33205  }
33206  return rc;
33207}
33208
33209/*
33210** Set the value of the Pager.sectorSize variable for the given
33211** pager based on the value returned by the xSectorSize method
33212** of the open database file. The sector size will be used used
33213** to determine the size and alignment of journal header and
33214** master journal pointers within created journal files.
33215**
33216** For temporary files the effective sector size is always 512 bytes.
33217**
33218** Otherwise, for non-temporary files, the effective sector size is
33219** the value returned by the xSectorSize() method rounded up to 32 if
33220** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
33221** is greater than MAX_SECTOR_SIZE.
33222*/
33223static void setSectorSize(Pager *pPager){
33224  assert( isOpen(pPager->fd) || pPager->tempFile );
33225
33226  if( !pPager->tempFile ){
33227    /* Sector size doesn't matter for temporary files. Also, the file
33228    ** may not have been opened yet, in which case the OsSectorSize()
33229    ** call will segfault.
33230    */
33231    pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
33232  }
33233  if( pPager->sectorSize<32 ){
33234    pPager->sectorSize = 512;
33235  }
33236  if( pPager->sectorSize>MAX_SECTOR_SIZE ){
33237    assert( MAX_SECTOR_SIZE>=512 );
33238    pPager->sectorSize = MAX_SECTOR_SIZE;
33239  }
33240}
33241
33242/*
33243** Playback the journal and thus restore the database file to
33244** the state it was in before we started making changes.
33245**
33246** The journal file format is as follows:
33247**
33248**  (1)  8 byte prefix.  A copy of aJournalMagic[].
33249**  (2)  4 byte big-endian integer which is the number of valid page records
33250**       in the journal.  If this value is 0xffffffff, then compute the
33251**       number of page records from the journal size.
33252**  (3)  4 byte big-endian integer which is the initial value for the
33253**       sanity checksum.
33254**  (4)  4 byte integer which is the number of pages to truncate the
33255**       database to during a rollback.
33256**  (5)  4 byte big-endian integer which is the sector size.  The header
33257**       is this many bytes in size.
33258**  (6)  4 byte big-endian integer which is the page size.
33259**  (7)  zero padding out to the next sector size.
33260**  (8)  Zero or more pages instances, each as follows:
33261**        +  4 byte page number.
33262**        +  pPager->pageSize bytes of data.
33263**        +  4 byte checksum
33264**
33265** When we speak of the journal header, we mean the first 7 items above.
33266** Each entry in the journal is an instance of the 8th item.
33267**
33268** Call the value from the second bullet "nRec".  nRec is the number of
33269** valid page entries in the journal.  In most cases, you can compute the
33270** value of nRec from the size of the journal file.  But if a power
33271** failure occurred while the journal was being written, it could be the
33272** case that the size of the journal file had already been increased but
33273** the extra entries had not yet made it safely to disk.  In such a case,
33274** the value of nRec computed from the file size would be too large.  For
33275** that reason, we always use the nRec value in the header.
33276**
33277** If the nRec value is 0xffffffff it means that nRec should be computed
33278** from the file size.  This value is used when the user selects the
33279** no-sync option for the journal.  A power failure could lead to corruption
33280** in this case.  But for things like temporary table (which will be
33281** deleted when the power is restored) we don't care.
33282**
33283** If the file opened as the journal file is not a well-formed
33284** journal file then all pages up to the first corrupted page are rolled
33285** back (or no pages if the journal header is corrupted). The journal file
33286** is then deleted and SQLITE_OK returned, just as if no corruption had
33287** been encountered.
33288**
33289** If an I/O or malloc() error occurs, the journal-file is not deleted
33290** and an error code is returned.
33291**
33292** The isHot parameter indicates that we are trying to rollback a journal
33293** that might be a hot journal.  Or, it could be that the journal is
33294** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
33295** If the journal really is hot, reset the pager cache prior rolling
33296** back any content.  If the journal is merely persistent, no reset is
33297** needed.
33298*/
33299static int pager_playback(Pager *pPager, int isHot){
33300  sqlite3_vfs *pVfs = pPager->pVfs;
33301  i64 szJ;                 /* Size of the journal file in bytes */
33302  u32 nRec;                /* Number of Records in the journal */
33303  u32 u;                   /* Unsigned loop counter */
33304  Pgno mxPg = 0;           /* Size of the original file in pages */
33305  int rc;                  /* Result code of a subroutine */
33306  int res = 1;             /* Value returned by sqlite3OsAccess() */
33307  char *zMaster = 0;       /* Name of master journal file if any */
33308  int needPagerReset;      /* True to reset page prior to first page rollback */
33309
33310  /* Figure out how many records are in the journal.  Abort early if
33311  ** the journal is empty.
33312  */
33313  assert( isOpen(pPager->jfd) );
33314  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
33315  if( rc!=SQLITE_OK || szJ==0 ){
33316    goto end_playback;
33317  }
33318
33319  /* Read the master journal name from the journal, if it is present.
33320  ** If a master journal file name is specified, but the file is not
33321  ** present on disk, then the journal is not hot and does not need to be
33322  ** played back.
33323  **
33324  ** TODO: Technically the following is an error because it assumes that
33325  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
33326  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
33327  **  mxPathname is 512, which is the same as the minimum allowable value
33328  ** for pageSize.
33329  */
33330  zMaster = pPager->pTmpSpace;
33331  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
33332  if( rc==SQLITE_OK && zMaster[0] ){
33333    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
33334  }
33335  zMaster = 0;
33336  if( rc!=SQLITE_OK || !res ){
33337    goto end_playback;
33338  }
33339  pPager->journalOff = 0;
33340  needPagerReset = isHot;
33341
33342  /* This loop terminates either when a readJournalHdr() or
33343  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
33344  ** occurs.
33345  */
33346  while( 1 ){
33347    int isUnsync = 0;
33348
33349    /* Read the next journal header from the journal file.  If there are
33350    ** not enough bytes left in the journal file for a complete header, or
33351    ** it is corrupted, then a process must of failed while writing it.
33352    ** This indicates nothing more needs to be rolled back.
33353    */
33354    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
33355    if( rc!=SQLITE_OK ){
33356      if( rc==SQLITE_DONE ){
33357        rc = SQLITE_OK;
33358      }
33359      goto end_playback;
33360    }
33361
33362    /* If nRec is 0xffffffff, then this journal was created by a process
33363    ** working in no-sync mode. This means that the rest of the journal
33364    ** file consists of pages, there are no more journal headers. Compute
33365    ** the value of nRec based on this assumption.
33366    */
33367    if( nRec==0xffffffff ){
33368      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
33369      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
33370    }
33371
33372    /* If nRec is 0 and this rollback is of a transaction created by this
33373    ** process and if this is the final header in the journal, then it means
33374    ** that this part of the journal was being filled but has not yet been
33375    ** synced to disk.  Compute the number of pages based on the remaining
33376    ** size of the file.
33377    **
33378    ** The third term of the test was added to fix ticket #2565.
33379    ** When rolling back a hot journal, nRec==0 always means that the next
33380    ** chunk of the journal contains zero pages to be rolled back.  But
33381    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
33382    ** the journal, it means that the journal might contain additional
33383    ** pages that need to be rolled back and that the number of pages
33384    ** should be computed based on the journal file size.
33385    */
33386    if( nRec==0 && !isHot &&
33387        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
33388      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
33389      isUnsync = 1;
33390    }
33391
33392    /* If this is the first header read from the journal, truncate the
33393    ** database file back to its original size.
33394    */
33395    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
33396      rc = pager_truncate(pPager, mxPg);
33397      if( rc!=SQLITE_OK ){
33398        goto end_playback;
33399      }
33400      pPager->dbSize = mxPg;
33401    }
33402
33403    /* Copy original pages out of the journal and back into the
33404    ** database file and/or page cache.
33405    */
33406    for(u=0; u<nRec; u++){
33407      if( needPagerReset ){
33408        pager_reset(pPager);
33409        needPagerReset = 0;
33410      }
33411      rc = pager_playback_one_page(pPager,1,isUnsync,&pPager->journalOff,0,0);
33412      if( rc!=SQLITE_OK ){
33413        if( rc==SQLITE_DONE ){
33414          rc = SQLITE_OK;
33415          pPager->journalOff = szJ;
33416          break;
33417        }else{
33418          /* If we are unable to rollback, quit and return the error
33419          ** code.  This will cause the pager to enter the error state
33420          ** so that no further harm will be done.  Perhaps the next
33421          ** process to come along will be able to rollback the database.
33422          */
33423          goto end_playback;
33424        }
33425      }
33426    }
33427  }
33428  /*NOTREACHED*/
33429  assert( 0 );
33430
33431end_playback:
33432  /* Following a rollback, the database file should be back in its original
33433  ** state prior to the start of the transaction, so invoke the
33434  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
33435  ** assertion that the transaction counter was modified.
33436  */
33437  assert(
33438    pPager->fd->pMethods==0 ||
33439    sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
33440  );
33441
33442  /* If this playback is happening automatically as a result of an IO or
33443  ** malloc error that occurred after the change-counter was updated but
33444  ** before the transaction was committed, then the change-counter
33445  ** modification may just have been reverted. If this happens in exclusive
33446  ** mode, then subsequent transactions performed by the connection will not
33447  ** update the change-counter at all. This may lead to cache inconsistency
33448  ** problems for other processes at some point in the future. So, just
33449  ** in case this has happened, clear the changeCountDone flag now.
33450  */
33451  pPager->changeCountDone = pPager->tempFile;
33452
33453  if( rc==SQLITE_OK ){
33454    zMaster = pPager->pTmpSpace;
33455    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
33456    testcase( rc!=SQLITE_OK );
33457  }
33458  if( rc==SQLITE_OK && pPager->noSync==0 && pPager->state>=PAGER_EXCLUSIVE ){
33459    rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
33460  }
33461  if( rc==SQLITE_OK ){
33462    rc = pager_end_transaction(pPager, zMaster[0]!='\0');
33463    testcase( rc!=SQLITE_OK );
33464  }
33465  if( rc==SQLITE_OK && zMaster[0] && res ){
33466    /* If there was a master journal and this routine will return success,
33467    ** see if it is possible to delete the master journal.
33468    */
33469    rc = pager_delmaster(pPager, zMaster);
33470    testcase( rc!=SQLITE_OK );
33471  }
33472
33473  /* The Pager.sectorSize variable may have been updated while rolling
33474  ** back a journal created by a process with a different sector size
33475  ** value. Reset it to the correct value for this process.
33476  */
33477  setSectorSize(pPager);
33478  return rc;
33479}
33480
33481/*
33482** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
33483** the entire master journal file. The case pSavepoint==NULL occurs when
33484** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
33485** savepoint.
33486**
33487** When pSavepoint is not NULL (meaning a non-transaction savepoint is
33488** being rolled back), then the rollback consists of up to three stages,
33489** performed in the order specified:
33490**
33491**   * Pages are played back from the main journal starting at byte
33492**     offset PagerSavepoint.iOffset and continuing to
33493**     PagerSavepoint.iHdrOffset, or to the end of the main journal
33494**     file if PagerSavepoint.iHdrOffset is zero.
33495**
33496**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
33497**     back starting from the journal header immediately following
33498**     PagerSavepoint.iHdrOffset to the end of the main journal file.
33499**
33500**   * Pages are then played back from the sub-journal file, starting
33501**     with the PagerSavepoint.iSubRec and continuing to the end of
33502**     the journal file.
33503**
33504** Throughout the rollback process, each time a page is rolled back, the
33505** corresponding bit is set in a bitvec structure (variable pDone in the
33506** implementation below). This is used to ensure that a page is only
33507** rolled back the first time it is encountered in either journal.
33508**
33509** If pSavepoint is NULL, then pages are only played back from the main
33510** journal file. There is no need for a bitvec in this case.
33511**
33512** In either case, before playback commences the Pager.dbSize variable
33513** is reset to the value that it held at the start of the savepoint
33514** (or transaction). No page with a page-number greater than this value
33515** is played back. If one is encountered it is simply skipped.
33516*/
33517static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
33518  i64 szJ;                 /* Effective size of the main journal */
33519  i64 iHdrOff;             /* End of first segment of main-journal records */
33520  int rc = SQLITE_OK;      /* Return code */
33521  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
33522
33523  assert( pPager->state>=PAGER_SHARED );
33524
33525  /* Allocate a bitvec to use to store the set of pages rolled back */
33526  if( pSavepoint ){
33527    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
33528    if( !pDone ){
33529      return SQLITE_NOMEM;
33530    }
33531  }
33532
33533  /* Set the database size back to the value it was before the savepoint
33534  ** being reverted was opened.
33535  */
33536  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
33537
33538  /* Use pPager->journalOff as the effective size of the main rollback
33539  ** journal.  The actual file might be larger than this in
33540  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
33541  ** past pPager->journalOff is off-limits to us.
33542  */
33543  szJ = pPager->journalOff;
33544
33545  /* Begin by rolling back records from the main journal starting at
33546  ** PagerSavepoint.iOffset and continuing to the next journal header.
33547  ** There might be records in the main journal that have a page number
33548  ** greater than the current database size (pPager->dbSize) but those
33549  ** will be skipped automatically.  Pages are added to pDone as they
33550  ** are played back.
33551  */
33552  if( pSavepoint ){
33553    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
33554    pPager->journalOff = pSavepoint->iOffset;
33555    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
33556      rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
33557    }
33558    assert( rc!=SQLITE_DONE );
33559  }else{
33560    pPager->journalOff = 0;
33561  }
33562
33563  /* Continue rolling back records out of the main journal starting at
33564  ** the first journal header seen and continuing until the effective end
33565  ** of the main journal file.  Continue to skip out-of-range pages and
33566  ** continue adding pages rolled back to pDone.
33567  */
33568  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
33569    u32 ii;            /* Loop counter */
33570    u32 nJRec = 0;     /* Number of Journal Records */
33571    u32 dummy;
33572    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
33573    assert( rc!=SQLITE_DONE );
33574
33575    /*
33576    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
33577    ** test is related to ticket #2565.  See the discussion in the
33578    ** pager_playback() function for additional information.
33579    */
33580    if( nJRec==0
33581     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
33582    ){
33583      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
33584    }
33585    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
33586      rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
33587    }
33588    assert( rc!=SQLITE_DONE );
33589  }
33590  assert( rc!=SQLITE_OK || pPager->journalOff==szJ );
33591
33592  /* Finally,  rollback pages from the sub-journal.  Page that were
33593  ** previously rolled back out of the main journal (and are hence in pDone)
33594  ** will be skipped.  Out-of-range pages are also skipped.
33595  */
33596  if( pSavepoint ){
33597    u32 ii;            /* Loop counter */
33598    i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
33599    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
33600      assert( offset==ii*(4+pPager->pageSize) );
33601      rc = pager_playback_one_page(pPager, 0, 0, &offset, 1, pDone);
33602    }
33603    assert( rc!=SQLITE_DONE );
33604  }
33605
33606  sqlite3BitvecDestroy(pDone);
33607  if( rc==SQLITE_OK ){
33608    pPager->journalOff = szJ;
33609  }
33610  return rc;
33611}
33612
33613/*
33614** Change the maximum number of in-memory pages that are allowed.
33615*/
33616SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
33617  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
33618}
33619
33620/*
33621** Adjust the robustness of the database to damage due to OS crashes
33622** or power failures by changing the number of syncs()s when writing
33623** the rollback journal.  There are three levels:
33624**
33625**    OFF       sqlite3OsSync() is never called.  This is the default
33626**              for temporary and transient files.
33627**
33628**    NORMAL    The journal is synced once before writes begin on the
33629**              database.  This is normally adequate protection, but
33630**              it is theoretically possible, though very unlikely,
33631**              that an inopertune power failure could leave the journal
33632**              in a state which would cause damage to the database
33633**              when it is rolled back.
33634**
33635**    FULL      The journal is synced twice before writes begin on the
33636**              database (with some additional information - the nRec field
33637**              of the journal header - being written in between the two
33638**              syncs).  If we assume that writing a
33639**              single disk sector is atomic, then this mode provides
33640**              assurance that the journal will not be corrupted to the
33641**              point of causing damage to the database during rollback.
33642**
33643** Numeric values associated with these states are OFF==1, NORMAL=2,
33644** and FULL=3.
33645*/
33646#ifndef SQLITE_OMIT_PAGER_PRAGMAS
33647SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int bFullFsync){
33648  pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
33649  pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
33650  pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
33651  if( pPager->noSync ) pPager->needSync = 0;
33652}
33653#endif
33654
33655/*
33656** The following global variable is incremented whenever the library
33657** attempts to open a temporary file.  This information is used for
33658** testing and analysis only.
33659*/
33660#ifdef SQLITE_TEST
33661SQLITE_API int sqlite3_opentemp_count = 0;
33662#endif
33663
33664/*
33665** Open a temporary file.
33666**
33667** Write the file descriptor into *pFile. Return SQLITE_OK on success
33668** or some other error code if we fail. The OS will automatically
33669** delete the temporary file when it is closed.
33670**
33671** The flags passed to the VFS layer xOpen() call are those specified
33672** by parameter vfsFlags ORed with the following:
33673**
33674**     SQLITE_OPEN_READWRITE
33675**     SQLITE_OPEN_CREATE
33676**     SQLITE_OPEN_EXCLUSIVE
33677**     SQLITE_OPEN_DELETEONCLOSE
33678*/
33679static int pagerOpentemp(
33680  Pager *pPager,        /* The pager object */
33681  sqlite3_file *pFile,  /* Write the file descriptor here */
33682  int vfsFlags          /* Flags passed through to the VFS */
33683){
33684  int rc;               /* Return code */
33685
33686#ifdef SQLITE_TEST
33687  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
33688#endif
33689
33690  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
33691            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
33692  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
33693  assert( rc!=SQLITE_OK || isOpen(pFile) );
33694  return rc;
33695}
33696
33697/*
33698** Set the busy handler function.
33699**
33700** The pager invokes the busy-handler if sqlite3OsLock() returns
33701** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
33702** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
33703** lock. It does *not* invoke the busy handler when upgrading from
33704** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
33705** (which occurs during hot-journal rollback). Summary:
33706**
33707**   Transition                        | Invokes xBusyHandler
33708**   --------------------------------------------------------
33709**   NO_LOCK       -> SHARED_LOCK      | Yes
33710**   SHARED_LOCK   -> RESERVED_LOCK    | No
33711**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
33712**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
33713**
33714** If the busy-handler callback returns non-zero, the lock is
33715** retried. If it returns zero, then the SQLITE_BUSY error is
33716** returned to the caller of the pager API function.
33717*/
33718SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
33719  Pager *pPager,                       /* Pager object */
33720  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
33721  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
33722){
33723  pPager->xBusyHandler = xBusyHandler;
33724  pPager->pBusyHandlerArg = pBusyHandlerArg;
33725}
33726
33727/*
33728** Report the current page size and number of reserved bytes back
33729** to the codec.
33730*/
33731#ifdef SQLITE_HAS_CODEC
33732static void pagerReportSize(Pager *pPager){
33733  if( pPager->xCodecSizeChng ){
33734    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
33735                           (int)pPager->nReserve);
33736  }
33737}
33738#else
33739# define pagerReportSize(X)     /* No-op if we do not support a codec */
33740#endif
33741
33742/*
33743** Change the page size used by the Pager object. The new page size
33744** is passed in *pPageSize.
33745**
33746** If the pager is in the error state when this function is called, it
33747** is a no-op. The value returned is the error state error code (i.e.
33748** one of SQLITE_IOERR, SQLITE_CORRUPT or SQLITE_FULL).
33749**
33750** Otherwise, if all of the following are true:
33751**
33752**   * the new page size (value of *pPageSize) is valid (a power
33753**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
33754**
33755**   * there are no outstanding page references, and
33756**
33757**   * the database is either not an in-memory database or it is
33758**     an in-memory database that currently consists of zero pages.
33759**
33760** then the pager object page size is set to *pPageSize.
33761**
33762** If the page size is changed, then this function uses sqlite3PagerMalloc()
33763** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
33764** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
33765** In all other cases, SQLITE_OK is returned.
33766**
33767** If the page size is not changed, either because one of the enumerated
33768** conditions above is not true, the pager was in error state when this
33769** function was called, or because the memory allocation attempt failed,
33770** then *pPageSize is set to the old, retained page size before returning.
33771*/
33772SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize, int nReserve){
33773  int rc = pPager->errCode;
33774
33775  if( rc==SQLITE_OK ){
33776    u16 pageSize = *pPageSize;
33777    assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
33778    if( (pPager->memDb==0 || pPager->dbSize==0)
33779     && sqlite3PcacheRefCount(pPager->pPCache)==0
33780     && pageSize && pageSize!=pPager->pageSize
33781    ){
33782      char *pNew = (char *)sqlite3PageMalloc(pageSize);
33783      if( !pNew ){
33784        rc = SQLITE_NOMEM;
33785      }else{
33786        pager_reset(pPager);
33787        pPager->pageSize = pageSize;
33788        sqlite3PageFree(pPager->pTmpSpace);
33789        pPager->pTmpSpace = pNew;
33790        sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
33791      }
33792    }
33793    *pPageSize = (u16)pPager->pageSize;
33794    if( nReserve<0 ) nReserve = pPager->nReserve;
33795    assert( nReserve>=0 && nReserve<1000 );
33796    pPager->nReserve = (i16)nReserve;
33797    pagerReportSize(pPager);
33798  }
33799  return rc;
33800}
33801
33802/*
33803** Return a pointer to the "temporary page" buffer held internally
33804** by the pager.  This is a buffer that is big enough to hold the
33805** entire content of a database page.  This buffer is used internally
33806** during rollback and will be overwritten whenever a rollback
33807** occurs.  But other modules are free to use it too, as long as
33808** no rollbacks are happening.
33809*/
33810SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
33811  return pPager->pTmpSpace;
33812}
33813
33814/*
33815** Attempt to set the maximum database page count if mxPage is positive.
33816** Make no changes if mxPage is zero or negative.  And never reduce the
33817** maximum page count below the current size of the database.
33818**
33819** Regardless of mxPage, return the current maximum page count.
33820*/
33821SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
33822  if( mxPage>0 ){
33823    pPager->mxPgno = mxPage;
33824  }
33825  sqlite3PagerPagecount(pPager, 0);
33826  return pPager->mxPgno;
33827}
33828
33829/*
33830** The following set of routines are used to disable the simulated
33831** I/O error mechanism.  These routines are used to avoid simulated
33832** errors in places where we do not care about errors.
33833**
33834** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
33835** and generate no code.
33836*/
33837#ifdef SQLITE_TEST
33838SQLITE_API extern int sqlite3_io_error_pending;
33839SQLITE_API extern int sqlite3_io_error_hit;
33840static int saved_cnt;
33841void disable_simulated_io_errors(void){
33842  saved_cnt = sqlite3_io_error_pending;
33843  sqlite3_io_error_pending = -1;
33844}
33845void enable_simulated_io_errors(void){
33846  sqlite3_io_error_pending = saved_cnt;
33847}
33848#else
33849# define disable_simulated_io_errors()
33850# define enable_simulated_io_errors()
33851#endif
33852
33853/*
33854** Read the first N bytes from the beginning of the file into memory
33855** that pDest points to.
33856**
33857** If the pager was opened on a transient file (zFilename==""), or
33858** opened on a file less than N bytes in size, the output buffer is
33859** zeroed and SQLITE_OK returned. The rationale for this is that this
33860** function is used to read database headers, and a new transient or
33861** zero sized database has a header than consists entirely of zeroes.
33862**
33863** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
33864** the error code is returned to the caller and the contents of the
33865** output buffer undefined.
33866*/
33867SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
33868  int rc = SQLITE_OK;
33869  memset(pDest, 0, N);
33870  assert( isOpen(pPager->fd) || pPager->tempFile );
33871  if( isOpen(pPager->fd) ){
33872    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
33873    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
33874    if( rc==SQLITE_IOERR_SHORT_READ ){
33875      rc = SQLITE_OK;
33876    }
33877  }
33878  return rc;
33879}
33880
33881/*
33882** Return the total number of pages in the database file associated
33883** with pPager. Normally, this is calculated as (<db file size>/<page-size>).
33884** However, if the file is between 1 and <page-size> bytes in size, then
33885** this is considered a 1 page file.
33886**
33887** If the pager is in error state when this function is called, then the
33888** error state error code is returned and *pnPage left unchanged. Or,
33889** if the file system has to be queried for the size of the file and
33890** the query attempt returns an IO error, the IO error code is returned
33891** and *pnPage is left unchanged.
33892**
33893** Otherwise, if everything is successful, then SQLITE_OK is returned
33894** and *pnPage is set to the number of pages in the database.
33895*/
33896SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager, int *pnPage){
33897  Pgno nPage;               /* Value to return via *pnPage */
33898
33899  /* If the pager is already in the error state, return the error code. */
33900  if( pPager->errCode ){
33901    return pPager->errCode;
33902  }
33903
33904  /* Determine the number of pages in the file. Store this in nPage. */
33905  if( pPager->dbSizeValid ){
33906    nPage = pPager->dbSize;
33907  }else{
33908    int rc;                 /* Error returned by OsFileSize() */
33909    i64 n = 0;              /* File size in bytes returned by OsFileSize() */
33910
33911    assert( isOpen(pPager->fd) || pPager->tempFile );
33912    if( isOpen(pPager->fd) && (0 != (rc = sqlite3OsFileSize(pPager->fd, &n))) ){
33913      pager_error(pPager, rc);
33914      return rc;
33915    }
33916    if( n>0 && n<pPager->pageSize ){
33917      nPage = 1;
33918    }else{
33919      nPage = (Pgno)(n / pPager->pageSize);
33920    }
33921    if( pPager->state!=PAGER_UNLOCK ){
33922      pPager->dbSize = nPage;
33923      pPager->dbFileSize = nPage;
33924      pPager->dbSizeValid = 1;
33925    }
33926  }
33927
33928  /* If the current number of pages in the file is greater than the
33929  ** configured maximum pager number, increase the allowed limit so
33930  ** that the file can be read.
33931  */
33932  if( nPage>pPager->mxPgno ){
33933    pPager->mxPgno = (Pgno)nPage;
33934  }
33935
33936  /* Set the output variable and return SQLITE_OK */
33937  if( pnPage ){
33938    *pnPage = nPage;
33939  }
33940  return SQLITE_OK;
33941}
33942
33943
33944/*
33945** Try to obtain a lock of type locktype on the database file. If
33946** a similar or greater lock is already held, this function is a no-op
33947** (returning SQLITE_OK immediately).
33948**
33949** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
33950** the busy callback if the lock is currently not available. Repeat
33951** until the busy callback returns false or until the attempt to
33952** obtain the lock succeeds.
33953**
33954** Return SQLITE_OK on success and an error code if we cannot obtain
33955** the lock. If the lock is obtained successfully, set the Pager.state
33956** variable to locktype before returning.
33957*/
33958static int pager_wait_on_lock(Pager *pPager, int locktype){
33959  int rc;                              /* Return code */
33960
33961  /* The OS lock values must be the same as the Pager lock values */
33962  assert( PAGER_SHARED==SHARED_LOCK );
33963  assert( PAGER_RESERVED==RESERVED_LOCK );
33964  assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
33965
33966  /* If the file is currently unlocked then the size must be unknown. It
33967  ** must not have been modified at this point.
33968  */
33969  assert( pPager->state>=PAGER_SHARED || pPager->dbSizeValid==0 );
33970  assert( pPager->state>=PAGER_SHARED || pPager->dbModified==0 );
33971
33972  /* Check that this is either a no-op (because the requested lock is
33973  ** already held, or one of the transistions that the busy-handler
33974  ** may be invoked during, according to the comment above
33975  ** sqlite3PagerSetBusyhandler().
33976  */
33977  assert( (pPager->state>=locktype)
33978       || (pPager->state==PAGER_UNLOCK && locktype==PAGER_SHARED)
33979       || (pPager->state==PAGER_RESERVED && locktype==PAGER_EXCLUSIVE)
33980  );
33981
33982  if( pPager->state>=locktype ){
33983    rc = SQLITE_OK;
33984  }else{
33985    do {
33986      rc = sqlite3OsLock(pPager->fd, locktype);
33987    }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
33988    if( rc==SQLITE_OK ){
33989      pPager->state = (u8)locktype;
33990      IOTRACE(("LOCK %p %d\n", pPager, locktype))
33991    }
33992  }
33993  return rc;
33994}
33995
33996/*
33997** Function assertTruncateConstraint(pPager) checks that one of the
33998** following is true for all dirty pages currently in the page-cache:
33999**
34000**   a) The page number is less than or equal to the size of the
34001**      current database image, in pages, OR
34002**
34003**   b) if the page content were written at this time, it would not
34004**      be necessary to write the current content out to the sub-journal
34005**      (as determined by function subjRequiresPage()).
34006**
34007** If the condition asserted by this function were not true, and the
34008** dirty page were to be discarded from the cache via the pagerStress()
34009** routine, pagerStress() would not write the current page content to
34010** the database file. If a savepoint transaction were rolled back after
34011** this happened, the correct behaviour would be to restore the current
34012** content of the page. However, since this content is not present in either
34013** the database file or the portion of the rollback journal and
34014** sub-journal rolled back the content could not be restored and the
34015** database image would become corrupt. It is therefore fortunate that
34016** this circumstance cannot arise.
34017*/
34018#if defined(SQLITE_DEBUG)
34019static void assertTruncateConstraintCb(PgHdr *pPg){
34020  assert( pPg->flags&PGHDR_DIRTY );
34021  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
34022}
34023static void assertTruncateConstraint(Pager *pPager){
34024  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
34025}
34026#else
34027# define assertTruncateConstraint(pPager)
34028#endif
34029
34030/*
34031** Truncate the in-memory database file image to nPage pages. This
34032** function does not actually modify the database file on disk. It
34033** just sets the internal state of the pager object so that the
34034** truncation will be done when the current transaction is committed.
34035*/
34036SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
34037  assert( pPager->dbSizeValid );
34038  assert( pPager->dbSize>=nPage );
34039  assert( pPager->state>=PAGER_RESERVED );
34040  pPager->dbSize = nPage;
34041  assertTruncateConstraint(pPager);
34042}
34043
34044/*
34045** Shutdown the page cache.  Free all memory and close all files.
34046**
34047** If a transaction was in progress when this routine is called, that
34048** transaction is rolled back.  All outstanding pages are invalidated
34049** and their memory is freed.  Any attempt to use a page associated
34050** with this page cache after this function returns will likely
34051** result in a coredump.
34052**
34053** This function always succeeds. If a transaction is active an attempt
34054** is made to roll it back. If an error occurs during the rollback
34055** a hot journal may be left in the filesystem but no error is returned
34056** to the caller.
34057*/
34058SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
34059  disable_simulated_io_errors();
34060  sqlite3BeginBenignMalloc();
34061  pPager->errCode = 0;
34062  pPager->exclusiveMode = 0;
34063  pager_reset(pPager);
34064  if( MEMDB ){
34065    pager_unlock(pPager);
34066  }else{
34067    /* Set Pager.journalHdr to -1 for the benefit of the pager_playback()
34068    ** call which may be made from within pagerUnlockAndRollback(). If it
34069    ** is not -1, then the unsynced portion of an open journal file may
34070    ** be played back into the database. If a power failure occurs while
34071    ** this is happening, the database may become corrupt.
34072    */
34073    pPager->journalHdr = -1;
34074    pagerUnlockAndRollback(pPager);
34075  }
34076  sqlite3EndBenignMalloc();
34077  enable_simulated_io_errors();
34078  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
34079  IOTRACE(("CLOSE %p\n", pPager))
34080  sqlite3OsClose(pPager->fd);
34081  sqlite3PageFree(pPager->pTmpSpace);
34082  sqlite3PcacheClose(pPager->pPCache);
34083
34084#ifdef SQLITE_HAS_CODEC
34085  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
34086#endif
34087
34088  assert( !pPager->aSavepoint && !pPager->pInJournal );
34089  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
34090
34091  sqlite3_free(pPager);
34092  return SQLITE_OK;
34093}
34094
34095#if !defined(NDEBUG) || defined(SQLITE_TEST)
34096/*
34097** Return the page number for page pPg.
34098*/
34099SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
34100  return pPg->pgno;
34101}
34102#endif
34103
34104/*
34105** Increment the reference count for page pPg.
34106*/
34107SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
34108  sqlite3PcacheRef(pPg);
34109}
34110
34111/*
34112** Sync the journal. In other words, make sure all the pages that have
34113** been written to the journal have actually reached the surface of the
34114** disk and can be restored in the event of a hot-journal rollback.
34115**
34116** If the Pager.needSync flag is not set, then this function is a
34117** no-op. Otherwise, the actions required depend on the journal-mode
34118** and the device characteristics of the the file-system, as follows:
34119**
34120**   * If the journal file is an in-memory journal file, no action need
34121**     be taken.
34122**
34123**   * Otherwise, if the device does not support the SAFE_APPEND property,
34124**     then the nRec field of the most recently written journal header
34125**     is updated to contain the number of journal records that have
34126**     been written following it. If the pager is operating in full-sync
34127**     mode, then the journal file is synced before this field is updated.
34128**
34129**   * If the device does not support the SEQUENTIAL property, then
34130**     journal file is synced.
34131**
34132** Or, in pseudo-code:
34133**
34134**   if( NOT <in-memory journal> ){
34135**     if( NOT SAFE_APPEND ){
34136**       if( <full-sync mode> ) xSync(<journal file>);
34137**       <update nRec field>
34138**     }
34139**     if( NOT SEQUENTIAL ) xSync(<journal file>);
34140**   }
34141**
34142** The Pager.needSync flag is never be set for temporary files, or any
34143** file operating in no-sync mode (Pager.noSync set to non-zero).
34144**
34145** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
34146** page currently held in memory before returning SQLITE_OK. If an IO
34147** error is encountered, then the IO error code is returned to the caller.
34148*/
34149static int syncJournal(Pager *pPager){
34150  if( pPager->needSync ){
34151    assert( !pPager->tempFile );
34152    if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
34153      int rc;                              /* Return code */
34154      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
34155      assert( isOpen(pPager->jfd) );
34156
34157      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
34158        /* This block deals with an obscure problem. If the last connection
34159        ** that wrote to this database was operating in persistent-journal
34160        ** mode, then the journal file may at this point actually be larger
34161        ** than Pager.journalOff bytes. If the next thing in the journal
34162        ** file happens to be a journal-header (written as part of the
34163        ** previous connections transaction), and a crash or power-failure
34164        ** occurs after nRec is updated but before this connection writes
34165        ** anything else to the journal file (or commits/rolls back its
34166        ** transaction), then SQLite may become confused when doing the
34167        ** hot-journal rollback following recovery. It may roll back all
34168        ** of this connections data, then proceed to rolling back the old,
34169        ** out-of-date data that follows it. Database corruption.
34170        **
34171        ** To work around this, if the journal file does appear to contain
34172        ** a valid header following Pager.journalOff, then write a 0x00
34173        ** byte to the start of it to prevent it from being recognized.
34174        **
34175        ** Variable iNextHdrOffset is set to the offset at which this
34176        ** problematic header will occur, if it exists. aMagic is used
34177        ** as a temporary buffer to inspect the first couple of bytes of
34178        ** the potential journal header.
34179        */
34180        i64 iNextHdrOffset;
34181        u8 aMagic[8];
34182	u8 zHeader[sizeof(aJournalMagic)+4];
34183
34184	memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
34185	put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
34186
34187        iNextHdrOffset = journalHdrOffset(pPager);
34188        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
34189        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
34190          static const u8 zerobyte = 0;
34191          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
34192        }
34193        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
34194          return rc;
34195        }
34196
34197        /* Write the nRec value into the journal file header. If in
34198        ** full-synchronous mode, sync the journal first. This ensures that
34199        ** all data has really hit the disk before nRec is updated to mark
34200        ** it as a candidate for rollback.
34201        **
34202        ** This is not required if the persistent media supports the
34203        ** SAFE_APPEND property. Because in this case it is not possible
34204        ** for garbage data to be appended to the file, the nRec field
34205        ** is populated with 0xFFFFFFFF when the journal header is written
34206        ** and never needs to be updated.
34207        */
34208        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
34209          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
34210          IOTRACE(("JSYNC %p\n", pPager))
34211          rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
34212          if( rc!=SQLITE_OK ) return rc;
34213        }
34214        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
34215        rc = sqlite3OsWrite(
34216            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
34217	);
34218        if( rc!=SQLITE_OK ) return rc;
34219      }
34220      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
34221        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
34222        IOTRACE(("JSYNC %p\n", pPager))
34223        rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags|
34224          (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
34225        );
34226        if( rc!=SQLITE_OK ) return rc;
34227      }
34228    }
34229
34230    /* The journal file was just successfully synced. Set Pager.needSync
34231    ** to zero and clear the PGHDR_NEED_SYNC flag on all pagess.
34232    */
34233    pPager->needSync = 0;
34234    pPager->journalStarted = 1;
34235    sqlite3PcacheClearSyncFlags(pPager->pPCache);
34236  }
34237
34238  return SQLITE_OK;
34239}
34240
34241/*
34242** The argument is the first in a linked list of dirty pages connected
34243** by the PgHdr.pDirty pointer. This function writes each one of the
34244** in-memory pages in the list to the database file. The argument may
34245** be NULL, representing an empty list. In this case this function is
34246** a no-op.
34247**
34248** The pager must hold at least a RESERVED lock when this function
34249** is called. Before writing anything to the database file, this lock
34250** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
34251** SQLITE_BUSY is returned and no data is written to the database file.
34252**
34253** If the pager is a temp-file pager and the actual file-system file
34254** is not yet open, it is created and opened before any data is
34255** written out.
34256**
34257** Once the lock has been upgraded and, if necessary, the file opened,
34258** the pages are written out to the database file in list order. Writing
34259** a page is skipped if it meets either of the following criteria:
34260**
34261**   * The page number is greater than Pager.dbSize, or
34262**   * The PGHDR_DONT_WRITE flag is set on the page.
34263**
34264** If writing out a page causes the database file to grow, Pager.dbFileSize
34265** is updated accordingly. If page 1 is written out, then the value cached
34266** in Pager.dbFileVers[] is updated to match the new value stored in
34267** the database file.
34268**
34269** If everything is successful, SQLITE_OK is returned. If an IO error
34270** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
34271** be obtained, SQLITE_BUSY is returned.
34272*/
34273static int pager_write_pagelist(PgHdr *pList){
34274  Pager *pPager;                       /* Pager object */
34275  int rc;                              /* Return code */
34276
34277  if( NEVER(pList==0) ) return SQLITE_OK;
34278  pPager = pList->pPager;
34279
34280  /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
34281  ** database file. If there is already an EXCLUSIVE lock, the following
34282  ** call is a no-op.
34283  **
34284  ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
34285  ** through an intermediate state PENDING.   A PENDING lock prevents new
34286  ** readers from attaching to the database but is unsufficient for us to
34287  ** write.  The idea of a PENDING lock is to prevent new readers from
34288  ** coming in while we wait for existing readers to clear.
34289  **
34290  ** While the pager is in the RESERVED state, the original database file
34291  ** is unchanged and we can rollback without having to playback the
34292  ** journal into the original database file.  Once we transition to
34293  ** EXCLUSIVE, it means the database file has been changed and any rollback
34294  ** will require a journal playback.
34295  */
34296  assert( pPager->state>=PAGER_RESERVED );
34297  rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
34298
34299  /* If the file is a temp-file has not yet been opened, open it now. It
34300  ** is not possible for rc to be other than SQLITE_OK if this branch
34301  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
34302  */
34303  if( !isOpen(pPager->fd) ){
34304    assert( pPager->tempFile && rc==SQLITE_OK );
34305    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
34306  }
34307
34308  while( rc==SQLITE_OK && pList ){
34309    Pgno pgno = pList->pgno;
34310
34311    /* If there are dirty pages in the page cache with page numbers greater
34312    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
34313    ** make the file smaller (presumably by auto-vacuum code). Do not write
34314    ** any such pages to the file.
34315    **
34316    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
34317    ** set (set by sqlite3PagerDontWrite()).  Note that if compiled with
34318    ** SQLITE_SECURE_DELETE the PGHDR_DONT_WRITE bit is never set and so
34319    ** the second test is always true.
34320    */
34321    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
34322      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
34323      char *pData;                                   /* Data to write */
34324
34325      /* Encode the database */
34326      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
34327
34328      /* Write out the page data. */
34329      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
34330
34331      /* If page 1 was just written, update Pager.dbFileVers to match
34332      ** the value now stored in the database file. If writing this
34333      ** page caused the database file to grow, update dbFileSize.
34334      */
34335      if( pgno==1 ){
34336        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
34337      }
34338      if( pgno>pPager->dbFileSize ){
34339        pPager->dbFileSize = pgno;
34340      }
34341
34342      /* Update any backup objects copying the contents of this pager. */
34343      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
34344
34345      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
34346                   PAGERID(pPager), pgno, pager_pagehash(pList)));
34347      IOTRACE(("PGOUT %p %d\n", pPager, pgno));
34348      PAGER_INCR(sqlite3_pager_writedb_count);
34349      PAGER_INCR(pPager->nWrite);
34350    }else{
34351      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
34352    }
34353#ifdef SQLITE_CHECK_PAGES
34354    pList->pageHash = pager_pagehash(pList);
34355#endif
34356    pList = pList->pDirty;
34357  }
34358
34359  return rc;
34360}
34361
34362/*
34363** Append a record of the current state of page pPg to the sub-journal.
34364** It is the callers responsibility to use subjRequiresPage() to check
34365** that it is really required before calling this function.
34366**
34367** If successful, set the bit corresponding to pPg->pgno in the bitvecs
34368** for all open savepoints before returning.
34369**
34370** This function returns SQLITE_OK if everything is successful, an IO
34371** error code if the attempt to write to the sub-journal fails, or
34372** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
34373** bitvec.
34374*/
34375static int subjournalPage(PgHdr *pPg){
34376  int rc = SQLITE_OK;
34377  Pager *pPager = pPg->pPager;
34378  if( isOpen(pPager->sjfd) ){
34379    void *pData = pPg->pData;
34380    i64 offset = pPager->nSubRec*(4+pPager->pageSize);
34381    char *pData2;
34382
34383    CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
34384    PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
34385
34386    assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
34387    rc = write32bits(pPager->sjfd, offset, pPg->pgno);
34388    if( rc==SQLITE_OK ){
34389      rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
34390    }
34391  }
34392  if( rc==SQLITE_OK ){
34393    pPager->nSubRec++;
34394    assert( pPager->nSavepoint>0 );
34395    rc = addToSavepointBitvecs(pPager, pPg->pgno);
34396  }
34397  return rc;
34398}
34399
34400
34401/*
34402** This function is called by the pcache layer when it has reached some
34403** soft memory limit. The first argument is a pointer to a Pager object
34404** (cast as a void*). The pager is always 'purgeable' (not an in-memory
34405** database). The second argument is a reference to a page that is
34406** currently dirty but has no outstanding references. The page
34407** is always associated with the Pager object passed as the first
34408** argument.
34409**
34410** The job of this function is to make pPg clean by writing its contents
34411** out to the database file, if possible. This may involve syncing the
34412** journal file.
34413**
34414** If successful, sqlite3PcacheMakeClean() is called on the page and
34415** SQLITE_OK returned. If an IO error occurs while trying to make the
34416** page clean, the IO error code is returned. If the page cannot be
34417** made clean for some other reason, but no error occurs, then SQLITE_OK
34418** is returned by sqlite3PcacheMakeClean() is not called.
34419*/
34420static int pagerStress(void *p, PgHdr *pPg){
34421  Pager *pPager = (Pager *)p;
34422  int rc = SQLITE_OK;
34423
34424  assert( pPg->pPager==pPager );
34425  assert( pPg->flags&PGHDR_DIRTY );
34426
34427  /* The doNotSync flag is set by the sqlite3PagerWrite() function while it
34428  ** is journalling a set of two or more database pages that are stored
34429  ** on the same disk sector. Syncing the journal is not allowed while
34430  ** this is happening as it is important that all members of such a
34431  ** set of pages are synced to disk together. So, if the page this function
34432  ** is trying to make clean will require a journal sync and the doNotSync
34433  ** flag is set, return without doing anything. The pcache layer will
34434  ** just have to go ahead and allocate a new page buffer instead of
34435  ** reusing pPg.
34436  **
34437  ** Similarly, if the pager has already entered the error state, do not
34438  ** try to write the contents of pPg to disk.
34439  */
34440  if( NEVER(pPager->errCode)
34441   || (pPager->doNotSync && pPg->flags&PGHDR_NEED_SYNC)
34442  ){
34443    return SQLITE_OK;
34444  }
34445
34446  /* Sync the journal file if required. */
34447  if( pPg->flags&PGHDR_NEED_SYNC ){
34448    rc = syncJournal(pPager);
34449    if( rc==SQLITE_OK && pPager->fullSync &&
34450      !(pPager->journalMode==PAGER_JOURNALMODE_MEMORY) &&
34451      !(sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
34452    ){
34453      pPager->nRec = 0;
34454      rc = writeJournalHdr(pPager);
34455    }
34456  }
34457
34458  /* If the page number of this page is larger than the current size of
34459  ** the database image, it may need to be written to the sub-journal.
34460  ** This is because the call to pager_write_pagelist() below will not
34461  ** actually write data to the file in this case.
34462  **
34463  ** Consider the following sequence of events:
34464  **
34465  **   BEGIN;
34466  **     <journal page X>
34467  **     <modify page X>
34468  **     SAVEPOINT sp;
34469  **       <shrink database file to Y pages>
34470  **       pagerStress(page X)
34471  **     ROLLBACK TO sp;
34472  **
34473  ** If (X>Y), then when pagerStress is called page X will not be written
34474  ** out to the database file, but will be dropped from the cache. Then,
34475  ** following the "ROLLBACK TO sp" statement, reading page X will read
34476  ** data from the database file. This will be the copy of page X as it
34477  ** was when the transaction started, not as it was when "SAVEPOINT sp"
34478  ** was executed.
34479  **
34480  ** The solution is to write the current data for page X into the
34481  ** sub-journal file now (if it is not already there), so that it will
34482  ** be restored to its current value when the "ROLLBACK TO sp" is
34483  ** executed.
34484  */
34485  if( NEVER(
34486      rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
34487  ) ){
34488    rc = subjournalPage(pPg);
34489  }
34490
34491  /* Write the contents of the page out to the database file. */
34492  if( rc==SQLITE_OK ){
34493    pPg->pDirty = 0;
34494    rc = pager_write_pagelist(pPg);
34495  }
34496
34497  /* Mark the page as clean. */
34498  if( rc==SQLITE_OK ){
34499    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
34500    sqlite3PcacheMakeClean(pPg);
34501  }
34502
34503  return pager_error(pPager, rc);
34504}
34505
34506
34507/*
34508** Allocate and initialize a new Pager object and put a pointer to it
34509** in *ppPager. The pager should eventually be freed by passing it
34510** to sqlite3PagerClose().
34511**
34512** The zFilename argument is the path to the database file to open.
34513** If zFilename is NULL then a randomly-named temporary file is created
34514** and used as the file to be cached. Temporary files are be deleted
34515** automatically when they are closed. If zFilename is ":memory:" then
34516** all information is held in cache. It is never written to disk.
34517** This can be used to implement an in-memory database.
34518**
34519** The nExtra parameter specifies the number of bytes of space allocated
34520** along with each page reference. This space is available to the user
34521** via the sqlite3PagerGetExtra() API.
34522**
34523** The flags argument is used to specify properties that affect the
34524** operation of the pager. It should be passed some bitwise combination
34525** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
34526**
34527** The vfsFlags parameter is a bitmask to pass to the flags parameter
34528** of the xOpen() method of the supplied VFS when opening files.
34529**
34530** If the pager object is allocated and the specified file opened
34531** successfully, SQLITE_OK is returned and *ppPager set to point to
34532** the new pager object. If an error occurs, *ppPager is set to NULL
34533** and error code returned. This function may return SQLITE_NOMEM
34534** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
34535** various SQLITE_IO_XXX errors.
34536*/
34537SQLITE_PRIVATE int sqlite3PagerOpen(
34538  sqlite3_vfs *pVfs,       /* The virtual file system to use */
34539  Pager **ppPager,         /* OUT: Return the Pager structure here */
34540  const char *zFilename,   /* Name of the database file to open */
34541  int nExtra,              /* Extra bytes append to each in-memory page */
34542  int flags,               /* flags controlling this file */
34543  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
34544  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
34545){
34546  u8 *pPtr;
34547  Pager *pPager = 0;       /* Pager object to allocate and return */
34548  int rc = SQLITE_OK;      /* Return code */
34549  int tempFile = 0;        /* True for temp files (incl. in-memory files) */
34550  int memDb = 0;           /* True if this is an in-memory file */
34551  int readOnly = 0;        /* True if this is a read-only file */
34552  int journalFileSize;     /* Bytes to allocate for each journal fd */
34553  char *zPathname = 0;     /* Full path to database file */
34554  int nPathname = 0;       /* Number of bytes in zPathname */
34555  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
34556  int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
34557  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
34558  u16 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
34559
34560  /* Figure out how much space is required for each journal file-handle
34561  ** (there are two of them, the main journal and the sub-journal). This
34562  ** is the maximum space required for an in-memory journal file handle
34563  ** and a regular journal file-handle. Note that a "regular journal-handle"
34564  ** may be a wrapper capable of caching the first portion of the journal
34565  ** file in memory to implement the atomic-write optimization (see
34566  ** source file journal.c).
34567  */
34568  if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
34569    journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
34570  }else{
34571    journalFileSize = ROUND8(sqlite3MemJournalSize());
34572  }
34573
34574  /* Set the output variable to NULL in case an error occurs. */
34575  *ppPager = 0;
34576
34577  /* Compute and store the full pathname in an allocated buffer pointed
34578  ** to by zPathname, length nPathname. Or, if this is a temporary file,
34579  ** leave both nPathname and zPathname set to 0.
34580  */
34581  if( zFilename && zFilename[0] ){
34582    nPathname = pVfs->mxPathname+1;
34583    zPathname = sqlite3Malloc(nPathname*2);
34584    if( zPathname==0 ){
34585      return SQLITE_NOMEM;
34586    }
34587#ifndef SQLITE_OMIT_MEMORYDB
34588    if( strcmp(zFilename,":memory:")==0 ){
34589      memDb = 1;
34590      zPathname[0] = 0;
34591    }else
34592#endif
34593    {
34594      zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
34595      rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
34596    }
34597
34598    nPathname = sqlite3Strlen30(zPathname);
34599    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
34600      /* This branch is taken when the journal path required by
34601      ** the database being opened will be more than pVfs->mxPathname
34602      ** bytes in length. This means the database cannot be opened,
34603      ** as it will not be possible to open the journal file or even
34604      ** check for a hot-journal before reading.
34605      */
34606      rc = SQLITE_CANTOPEN_BKPT;
34607    }
34608    if( rc!=SQLITE_OK ){
34609      sqlite3_free(zPathname);
34610      return rc;
34611    }
34612  }
34613
34614  /* Allocate memory for the Pager structure, PCache object, the
34615  ** three file descriptors, the database file name and the journal
34616  ** file name. The layout in memory is as follows:
34617  **
34618  **     Pager object                    (sizeof(Pager) bytes)
34619  **     PCache object                   (sqlite3PcacheSize() bytes)
34620  **     Database file handle            (pVfs->szOsFile bytes)
34621  **     Sub-journal file handle         (journalFileSize bytes)
34622  **     Main journal file handle        (journalFileSize bytes)
34623  **     Database file name              (nPathname+1 bytes)
34624  **     Journal file name               (nPathname+8+1 bytes)
34625  */
34626  pPtr = (u8 *)sqlite3MallocZero(
34627    ROUND8(sizeof(*pPager)) +      /* Pager structure */
34628    ROUND8(pcacheSize) +           /* PCache object */
34629    ROUND8(pVfs->szOsFile) +       /* The main db file */
34630    journalFileSize * 2 +          /* The two journal files */
34631    nPathname + 1 +                /* zFilename */
34632    nPathname + 8 + 1              /* zJournal */
34633  );
34634  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
34635  if( !pPtr ){
34636    sqlite3_free(zPathname);
34637    return SQLITE_NOMEM;
34638  }
34639  pPager =              (Pager*)(pPtr);
34640  pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
34641  pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
34642  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
34643  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
34644  pPager->zFilename =    (char*)(pPtr += journalFileSize);
34645  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
34646
34647  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
34648  if( zPathname ){
34649    pPager->zJournal =   (char*)(pPtr += nPathname + 1);
34650    memcpy(pPager->zFilename, zPathname, nPathname);
34651    memcpy(pPager->zJournal, zPathname, nPathname);
34652    memcpy(&pPager->zJournal[nPathname], "-journal", 8);
34653    if( pPager->zFilename[0]==0 ) pPager->zJournal[0] = 0;
34654    sqlite3_free(zPathname);
34655  }
34656  pPager->pVfs = pVfs;
34657  pPager->vfsFlags = vfsFlags;
34658
34659  /* Open the pager file.
34660  */
34661  if( zFilename && zFilename[0] && !memDb ){
34662    int fout = 0;                    /* VFS flags returned by xOpen() */
34663    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
34664    readOnly = (fout&SQLITE_OPEN_READONLY);
34665
34666    /* If the file was successfully opened for read/write access,
34667    ** choose a default page size in case we have to create the
34668    ** database file. The default page size is the maximum of:
34669    **
34670    **    + SQLITE_DEFAULT_PAGE_SIZE,
34671    **    + The value returned by sqlite3OsSectorSize()
34672    **    + The largest page size that can be written atomically.
34673    */
34674    if( rc==SQLITE_OK && !readOnly ){
34675      setSectorSize(pPager);
34676      assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
34677      if( szPageDflt<pPager->sectorSize ){
34678        if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
34679          szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
34680        }else{
34681          szPageDflt = (u16)pPager->sectorSize;
34682        }
34683      }
34684#ifdef SQLITE_ENABLE_ATOMIC_WRITE
34685      {
34686        int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
34687        int ii;
34688        assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
34689        assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
34690        assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
34691        for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
34692          if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
34693            szPageDflt = ii;
34694          }
34695        }
34696      }
34697#endif
34698    }
34699  }else{
34700    /* If a temporary file is requested, it is not opened immediately.
34701    ** In this case we accept the default page size and delay actually
34702    ** opening the file until the first call to OsWrite().
34703    **
34704    ** This branch is also run for an in-memory database. An in-memory
34705    ** database is the same as a temp-file that is never written out to
34706    ** disk and uses an in-memory rollback journal.
34707    */
34708    tempFile = 1;
34709    pPager->state = PAGER_EXCLUSIVE;
34710    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
34711  }
34712
34713  /* The following call to PagerSetPagesize() serves to set the value of
34714  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
34715  */
34716  if( rc==SQLITE_OK ){
34717    assert( pPager->memDb==0 );
34718    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
34719    testcase( rc!=SQLITE_OK );
34720  }
34721
34722  /* If an error occurred in either of the blocks above, free the
34723  ** Pager structure and close the file.
34724  */
34725  if( rc!=SQLITE_OK ){
34726    assert( !pPager->pTmpSpace );
34727    sqlite3OsClose(pPager->fd);
34728    sqlite3_free(pPager);
34729    return rc;
34730  }
34731
34732  /* Initialize the PCache object. */
34733  assert( nExtra<1000 );
34734  nExtra = ROUND8(nExtra);
34735  sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
34736                    !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
34737
34738  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
34739  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
34740
34741  pPager->useJournal = (u8)useJournal;
34742  pPager->noReadlock = (noReadlock && readOnly) ?1:0;
34743  /* pPager->stmtOpen = 0; */
34744  /* pPager->stmtInUse = 0; */
34745  /* pPager->nRef = 0; */
34746  pPager->dbSizeValid = (u8)memDb;
34747  /* pPager->stmtSize = 0; */
34748  /* pPager->stmtJSize = 0; */
34749  /* pPager->nPage = 0; */
34750  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
34751  /* pPager->state = PAGER_UNLOCK; */
34752  assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
34753  /* pPager->errMask = 0; */
34754  pPager->tempFile = (u8)tempFile;
34755  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
34756          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
34757  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
34758  pPager->exclusiveMode = (u8)tempFile;
34759  pPager->changeCountDone = pPager->tempFile;
34760  pPager->memDb = (u8)memDb;
34761  pPager->readOnly = (u8)readOnly;
34762  /* pPager->needSync = 0; */
34763  assert( useJournal || pPager->tempFile );
34764  pPager->noSync = pPager->tempFile;
34765  pPager->fullSync = pPager->noSync ?0:1;
34766  pPager->sync_flags = SQLITE_SYNC_NORMAL;
34767  /* pPager->pFirst = 0; */
34768  /* pPager->pFirstSynced = 0; */
34769  /* pPager->pLast = 0; */
34770  pPager->nExtra = (u16)nExtra;
34771  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
34772  assert( isOpen(pPager->fd) || tempFile );
34773  setSectorSize(pPager);
34774  if( !useJournal ){
34775    pPager->journalMode = PAGER_JOURNALMODE_OFF;
34776  }else if( memDb ){
34777    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
34778  }
34779  /* pPager->xBusyHandler = 0; */
34780  /* pPager->pBusyHandlerArg = 0; */
34781  pPager->xReiniter = xReinit;
34782  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
34783  *ppPager = pPager;
34784  return SQLITE_OK;
34785}
34786
34787
34788
34789/*
34790** This function is called after transitioning from PAGER_UNLOCK to
34791** PAGER_SHARED state. It tests if there is a hot journal present in
34792** the file-system for the given pager. A hot journal is one that
34793** needs to be played back. According to this function, a hot-journal
34794** file exists if the following criteria are met:
34795**
34796**   * The journal file exists in the file system, and
34797**   * No process holds a RESERVED or greater lock on the database file, and
34798**   * The database file itself is greater than 0 bytes in size, and
34799**   * The first byte of the journal file exists and is not 0x00.
34800**
34801** If the current size of the database file is 0 but a journal file
34802** exists, that is probably an old journal left over from a prior
34803** database with the same name. In this case the journal file is
34804** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
34805** is returned.
34806**
34807** This routine does not check if there is a master journal filename
34808** at the end of the file. If there is, and that master journal file
34809** does not exist, then the journal file is not really hot. In this
34810** case this routine will return a false-positive. The pager_playback()
34811** routine will discover that the journal file is not really hot and
34812** will not roll it back.
34813**
34814** If a hot-journal file is found to exist, *pExists is set to 1 and
34815** SQLITE_OK returned. If no hot-journal file is present, *pExists is
34816** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
34817** to determine whether or not a hot-journal file exists, the IO error
34818** code is returned and the value of *pExists is undefined.
34819*/
34820static int hasHotJournal(Pager *pPager, int *pExists){
34821  sqlite3_vfs * const pVfs = pPager->pVfs;
34822  int rc;                       /* Return code */
34823  int exists;                   /* True if a journal file is present */
34824
34825  assert( pPager!=0 );
34826  assert( pPager->useJournal );
34827  assert( isOpen(pPager->fd) );
34828  assert( !isOpen(pPager->jfd) );
34829  assert( pPager->state <= PAGER_SHARED );
34830
34831  *pExists = 0;
34832  rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
34833  if( rc==SQLITE_OK && exists ){
34834    int locked;                 /* True if some process holds a RESERVED lock */
34835
34836    /* Race condition here:  Another process might have been holding the
34837    ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
34838    ** call above, but then delete the journal and drop the lock before
34839    ** we get to the following sqlite3OsCheckReservedLock() call.  If that
34840    ** is the case, this routine might think there is a hot journal when
34841    ** in fact there is none.  This results in a false-positive which will
34842    ** be dealt with by the playback routine.  Ticket #3883.
34843    */
34844    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
34845    if( rc==SQLITE_OK && !locked ){
34846      int nPage;
34847
34848      /* Check the size of the database file. If it consists of 0 pages,
34849      ** then delete the journal file. See the header comment above for
34850      ** the reasoning here.  Delete the obsolete journal file under
34851      ** a RESERVED lock to avoid race conditions and to avoid violating
34852      ** [H33020].
34853      */
34854      rc = sqlite3PagerPagecount(pPager, &nPage);
34855      if( rc==SQLITE_OK ){
34856        if( nPage==0 ){
34857          sqlite3BeginBenignMalloc();
34858          if( sqlite3OsLock(pPager->fd, RESERVED_LOCK)==SQLITE_OK ){
34859            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
34860            sqlite3OsUnlock(pPager->fd, SHARED_LOCK);
34861          }
34862          sqlite3EndBenignMalloc();
34863        }else{
34864          /* The journal file exists and no other connection has a reserved
34865          ** or greater lock on the database file. Now check that there is
34866          ** at least one non-zero bytes at the start of the journal file.
34867          ** If there is, then we consider this journal to be hot. If not,
34868          ** it can be ignored.
34869          */
34870          int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
34871          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
34872          if( rc==SQLITE_OK ){
34873            u8 first = 0;
34874            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
34875            if( rc==SQLITE_IOERR_SHORT_READ ){
34876              rc = SQLITE_OK;
34877            }
34878            sqlite3OsClose(pPager->jfd);
34879            *pExists = (first!=0);
34880          }else if( rc==SQLITE_CANTOPEN ){
34881            /* If we cannot open the rollback journal file in order to see if
34882            ** its has a zero header, that might be due to an I/O error, or
34883            ** it might be due to the race condition described above and in
34884            ** ticket #3883.  Either way, assume that the journal is hot.
34885            ** This might be a false positive.  But if it is, then the
34886            ** automatic journal playback and recovery mechanism will deal
34887            ** with it under an EXCLUSIVE lock where we do not need to
34888            ** worry so much with race conditions.
34889            */
34890            *pExists = 1;
34891            rc = SQLITE_OK;
34892          }
34893        }
34894      }
34895    }
34896  }
34897
34898  return rc;
34899}
34900
34901/*
34902** Read the content for page pPg out of the database file and into
34903** pPg->pData. A shared lock or greater must be held on the database
34904** file before this function is called.
34905**
34906** If page 1 is read, then the value of Pager.dbFileVers[] is set to
34907** the value read from the database file.
34908**
34909** If an IO error occurs, then the IO error is returned to the caller.
34910** Otherwise, SQLITE_OK is returned.
34911*/
34912static int readDbPage(PgHdr *pPg){
34913  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
34914  Pgno pgno = pPg->pgno;       /* Page number to read */
34915  int rc;                      /* Return code */
34916  i64 iOffset;                 /* Byte offset of file to read from */
34917
34918  assert( pPager->state>=PAGER_SHARED && !MEMDB );
34919  assert( isOpen(pPager->fd) );
34920
34921  if( NEVER(!isOpen(pPager->fd)) ){
34922    assert( pPager->tempFile );
34923    memset(pPg->pData, 0, pPager->pageSize);
34924    return SQLITE_OK;
34925  }
34926  iOffset = (pgno-1)*(i64)pPager->pageSize;
34927  rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
34928  if( rc==SQLITE_IOERR_SHORT_READ ){
34929    rc = SQLITE_OK;
34930  }
34931  if( pgno==1 ){
34932    u8 *dbFileVers = &((u8*)pPg->pData)[24];
34933    memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
34934  }
34935  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
34936
34937  PAGER_INCR(sqlite3_pager_readdb_count);
34938  PAGER_INCR(pPager->nRead);
34939  IOTRACE(("PGIN %p %d\n", pPager, pgno));
34940  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
34941               PAGERID(pPager), pgno, pager_pagehash(pPg)));
34942
34943  return rc;
34944}
34945
34946/*
34947** This function is called to obtain a shared lock on the database file.
34948** It is illegal to call sqlite3PagerAcquire() until after this function
34949** has been successfully called. If a shared-lock is already held when
34950** this function is called, it is a no-op.
34951**
34952** The following operations are also performed by this function.
34953**
34954**   1) If the pager is currently in PAGER_UNLOCK state (no lock held
34955**      on the database file), then an attempt is made to obtain a
34956**      SHARED lock on the database file. Immediately after obtaining
34957**      the SHARED lock, the file-system is checked for a hot-journal,
34958**      which is played back if present. Following any hot-journal
34959**      rollback, the contents of the cache are validated by checking
34960**      the 'change-counter' field of the database file header and
34961**      discarded if they are found to be invalid.
34962**
34963**   2) If the pager is running in exclusive-mode, and there are currently
34964**      no outstanding references to any pages, and is in the error state,
34965**      then an attempt is made to clear the error state by discarding
34966**      the contents of the page cache and rolling back any open journal
34967**      file.
34968**
34969** If the operation described by (2) above is not attempted, and if the
34970** pager is in an error state other than SQLITE_FULL when this is called,
34971** the error state error code is returned. It is permitted to read the
34972** database when in SQLITE_FULL error state.
34973**
34974** Otherwise, if everything is successful, SQLITE_OK is returned. If an
34975** IO error occurs while locking the database, checking for a hot-journal
34976** file or rolling back a journal file, the IO error code is returned.
34977*/
34978SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
34979  int rc = SQLITE_OK;                /* Return code */
34980  int isErrorReset = 0;              /* True if recovering from error state */
34981
34982  /* This routine is only called from b-tree and only when there are no
34983  ** outstanding pages */
34984  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
34985  if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
34986
34987  /* If this database is in an error-state, now is a chance to clear
34988  ** the error. Discard the contents of the pager-cache and rollback
34989  ** any hot journal in the file-system.
34990  */
34991  if( pPager->errCode ){
34992    if( isOpen(pPager->jfd) || pPager->zJournal ){
34993      isErrorReset = 1;
34994    }
34995    pPager->errCode = SQLITE_OK;
34996    pager_reset(pPager);
34997  }
34998
34999  if( pPager->state==PAGER_UNLOCK || isErrorReset ){
35000    sqlite3_vfs * const pVfs = pPager->pVfs;
35001    int isHotJournal = 0;
35002    assert( !MEMDB );
35003    assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
35004    if( pPager->noReadlock ){
35005      assert( pPager->readOnly );
35006      pPager->state = PAGER_SHARED;
35007    }else{
35008      rc = pager_wait_on_lock(pPager, SHARED_LOCK);
35009      if( rc!=SQLITE_OK ){
35010        assert( pPager->state==PAGER_UNLOCK );
35011        return pager_error(pPager, rc);
35012      }
35013    }
35014    assert( pPager->state>=SHARED_LOCK );
35015
35016    /* If a journal file exists, and there is no RESERVED lock on the
35017    ** database file, then it either needs to be played back or deleted.
35018    */
35019    if( !isErrorReset ){
35020      assert( pPager->state <= PAGER_SHARED );
35021      rc = hasHotJournal(pPager, &isHotJournal);
35022      if( rc!=SQLITE_OK ){
35023        goto failed;
35024      }
35025    }
35026    if( isErrorReset || isHotJournal ){
35027      /* Get an EXCLUSIVE lock on the database file. At this point it is
35028      ** important that a RESERVED lock is not obtained on the way to the
35029      ** EXCLUSIVE lock. If it were, another process might open the
35030      ** database file, detect the RESERVED lock, and conclude that the
35031      ** database is safe to read while this process is still rolling the
35032      ** hot-journal back.
35033      **
35034      ** Because the intermediate RESERVED lock is not requested, any
35035      ** other process attempting to access the database file will get to
35036      ** this point in the code and fail to obtain its own EXCLUSIVE lock
35037      ** on the database file.
35038      */
35039      if( pPager->state<EXCLUSIVE_LOCK ){
35040        rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
35041        if( rc!=SQLITE_OK ){
35042          rc = pager_error(pPager, rc);
35043          goto failed;
35044        }
35045        pPager->state = PAGER_EXCLUSIVE;
35046      }
35047
35048      /* Open the journal for read/write access. This is because in
35049      ** exclusive-access mode the file descriptor will be kept open and
35050      ** possibly used for a transaction later on. On some systems, the
35051      ** OsTruncate() call used in exclusive-access mode also requires
35052      ** a read/write file handle.
35053      */
35054      if( !isOpen(pPager->jfd) ){
35055        int res;
35056        rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
35057        if( rc==SQLITE_OK ){
35058          if( res ){
35059            int fout = 0;
35060            int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
35061            assert( !pPager->tempFile );
35062            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
35063            assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
35064            if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
35065              rc = SQLITE_CANTOPEN_BKPT;
35066              sqlite3OsClose(pPager->jfd);
35067            }
35068          }else{
35069            /* If the journal does not exist, it usually means that some
35070            ** other connection managed to get in and roll it back before
35071            ** this connection obtained the exclusive lock above. Or, it
35072            ** may mean that the pager was in the error-state when this
35073            ** function was called and the journal file does not exist.  */
35074            rc = pager_end_transaction(pPager, 0);
35075          }
35076        }
35077      }
35078      if( rc!=SQLITE_OK ){
35079        goto failed;
35080      }
35081
35082      /* TODO: Why are these cleared here? Is it necessary? */
35083      pPager->journalStarted = 0;
35084      pPager->journalOff = 0;
35085      pPager->setMaster = 0;
35086      pPager->journalHdr = 0;
35087
35088      /* Playback and delete the journal.  Drop the database write
35089      ** lock and reacquire the read lock. Purge the cache before
35090      ** playing back the hot-journal so that we don't end up with
35091      ** an inconsistent cache.
35092      */
35093      if( isOpen(pPager->jfd) ){
35094        rc = pager_playback(pPager, 1);
35095        if( rc!=SQLITE_OK ){
35096          rc = pager_error(pPager, rc);
35097          goto failed;
35098        }
35099      }
35100      assert( (pPager->state==PAGER_SHARED)
35101           || (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
35102      );
35103    }
35104
35105    if( pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0 ){
35106      /* The shared-lock has just been acquired on the database file
35107      ** and there are already pages in the cache (from a previous
35108      ** read or write transaction).  Check to see if the database
35109      ** has been modified.  If the database has changed, flush the
35110      ** cache.
35111      **
35112      ** Database changes is detected by looking at 15 bytes beginning
35113      ** at offset 24 into the file.  The first 4 of these 16 bytes are
35114      ** a 32-bit counter that is incremented with each change.  The
35115      ** other bytes change randomly with each file change when
35116      ** a codec is in use.
35117      **
35118      ** There is a vanishingly small chance that a change will not be
35119      ** detected.  The chance of an undetected change is so small that
35120      ** it can be neglected.
35121      */
35122      char dbFileVers[sizeof(pPager->dbFileVers)];
35123      sqlite3PagerPagecount(pPager, 0);
35124
35125      if( pPager->errCode ){
35126        rc = pPager->errCode;
35127        goto failed;
35128      }
35129
35130      assert( pPager->dbSizeValid );
35131      if( pPager->dbSize>0 ){
35132        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
35133        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
35134        if( rc!=SQLITE_OK ){
35135          goto failed;
35136        }
35137      }else{
35138        memset(dbFileVers, 0, sizeof(dbFileVers));
35139      }
35140
35141      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
35142        pager_reset(pPager);
35143      }
35144    }
35145    assert( pPager->exclusiveMode || pPager->state==PAGER_SHARED );
35146  }
35147
35148 failed:
35149  if( rc!=SQLITE_OK ){
35150    /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
35151    pager_unlock(pPager);
35152  }
35153  return rc;
35154}
35155
35156/*
35157** If the reference count has reached zero, rollback any active
35158** transaction and unlock the pager.
35159**
35160** Except, in locking_mode=EXCLUSIVE when there is nothing to in
35161** the rollback journal, the unlock is not performed and there is
35162** nothing to rollback, so this routine is a no-op.
35163*/
35164static void pagerUnlockIfUnused(Pager *pPager){
35165  if( (sqlite3PcacheRefCount(pPager->pPCache)==0)
35166   && (!pPager->exclusiveMode || pPager->journalOff>0)
35167  ){
35168    pagerUnlockAndRollback(pPager);
35169  }
35170}
35171
35172/*
35173** Acquire a reference to page number pgno in pager pPager (a page
35174** reference has type DbPage*). If the requested reference is
35175** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
35176**
35177** If the requested page is already in the cache, it is returned.
35178** Otherwise, a new page object is allocated and populated with data
35179** read from the database file. In some cases, the pcache module may
35180** choose not to allocate a new page object and may reuse an existing
35181** object with no outstanding references.
35182**
35183** The extra data appended to a page is always initialized to zeros the
35184** first time a page is loaded into memory. If the page requested is
35185** already in the cache when this function is called, then the extra
35186** data is left as it was when the page object was last used.
35187**
35188** If the database image is smaller than the requested page or if a
35189** non-zero value is passed as the noContent parameter and the
35190** requested page is not already stored in the cache, then no
35191** actual disk read occurs. In this case the memory image of the
35192** page is initialized to all zeros.
35193**
35194** If noContent is true, it means that we do not care about the contents
35195** of the page. This occurs in two seperate scenarios:
35196**
35197**   a) When reading a free-list leaf page from the database, and
35198**
35199**   b) When a savepoint is being rolled back and we need to load
35200**      a new page into the cache to populate with the data read
35201**      from the savepoint journal.
35202**
35203** If noContent is true, then the data returned is zeroed instead of
35204** being read from the database. Additionally, the bits corresponding
35205** to pgno in Pager.pInJournal (bitvec of pages already written to the
35206** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
35207** savepoints are set. This means if the page is made writable at any
35208** point in the future, using a call to sqlite3PagerWrite(), its contents
35209** will not be journaled. This saves IO.
35210**
35211** The acquisition might fail for several reasons.  In all cases,
35212** an appropriate error code is returned and *ppPage is set to NULL.
35213**
35214** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
35215** to find a page in the in-memory cache first.  If the page is not already
35216** in memory, this routine goes to disk to read it in whereas Lookup()
35217** just returns 0.  This routine acquires a read-lock the first time it
35218** has to go to disk, and could also playback an old journal if necessary.
35219** Since Lookup() never goes to disk, it never has to deal with locks
35220** or journal files.
35221*/
35222SQLITE_PRIVATE int sqlite3PagerAcquire(
35223  Pager *pPager,      /* The pager open on the database file */
35224  Pgno pgno,          /* Page number to fetch */
35225  DbPage **ppPage,    /* Write a pointer to the page here */
35226  int noContent       /* Do not bother reading content from disk if true */
35227){
35228  int rc;
35229  PgHdr *pPg;
35230
35231  assert( assert_pager_state(pPager) );
35232  assert( pPager->state>PAGER_UNLOCK );
35233
35234  if( pgno==0 ){
35235    return SQLITE_CORRUPT_BKPT;
35236  }
35237
35238  /* If the pager is in the error state, return an error immediately.
35239  ** Otherwise, request the page from the PCache layer. */
35240  if( pPager->errCode!=SQLITE_OK && pPager->errCode!=SQLITE_FULL ){
35241    rc = pPager->errCode;
35242  }else{
35243    rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
35244  }
35245
35246  if( rc!=SQLITE_OK ){
35247    /* Either the call to sqlite3PcacheFetch() returned an error or the
35248    ** pager was already in the error-state when this function was called.
35249    ** Set pPg to 0 and jump to the exception handler.  */
35250    pPg = 0;
35251    goto pager_acquire_err;
35252  }
35253  assert( (*ppPage)->pgno==pgno );
35254  assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
35255
35256  if( (*ppPage)->pPager ){
35257    /* In this case the pcache already contains an initialized copy of
35258    ** the page. Return without further ado.  */
35259    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
35260    PAGER_INCR(pPager->nHit);
35261    return SQLITE_OK;
35262
35263  }else{
35264    /* The pager cache has created a new page. Its content needs to
35265    ** be initialized.  */
35266    int nMax;
35267
35268    PAGER_INCR(pPager->nMiss);
35269    pPg = *ppPage;
35270    pPg->pPager = pPager;
35271
35272    /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
35273    ** number greater than this, or the unused locking-page, is requested. */
35274    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
35275      rc = SQLITE_CORRUPT_BKPT;
35276      goto pager_acquire_err;
35277    }
35278
35279    rc = sqlite3PagerPagecount(pPager, &nMax);
35280    if( rc!=SQLITE_OK ){
35281      goto pager_acquire_err;
35282    }
35283
35284    if( MEMDB || nMax<(int)pgno || noContent || !isOpen(pPager->fd) ){
35285      if( pgno>pPager->mxPgno ){
35286	rc = SQLITE_FULL;
35287	goto pager_acquire_err;
35288      }
35289      if( noContent ){
35290        /* Failure to set the bits in the InJournal bit-vectors is benign.
35291        ** It merely means that we might do some extra work to journal a
35292        ** page that does not need to be journaled.  Nevertheless, be sure
35293        ** to test the case where a malloc error occurs while trying to set
35294        ** a bit in a bit vector.
35295        */
35296        sqlite3BeginBenignMalloc();
35297        if( pgno<=pPager->dbOrigSize ){
35298          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
35299          testcase( rc==SQLITE_NOMEM );
35300        }
35301        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
35302        testcase( rc==SQLITE_NOMEM );
35303        sqlite3EndBenignMalloc();
35304      }
35305      memset(pPg->pData, 0, pPager->pageSize);
35306      IOTRACE(("ZERO %p %d\n", pPager, pgno));
35307    }else{
35308      assert( pPg->pPager==pPager );
35309      rc = readDbPage(pPg);
35310      if( rc!=SQLITE_OK ){
35311        goto pager_acquire_err;
35312      }
35313    }
35314#ifdef SQLITE_CHECK_PAGES
35315    pPg->pageHash = pager_pagehash(pPg);
35316#endif
35317  }
35318
35319  return SQLITE_OK;
35320
35321pager_acquire_err:
35322  assert( rc!=SQLITE_OK );
35323  if( pPg ){
35324    sqlite3PcacheDrop(pPg);
35325  }
35326  pagerUnlockIfUnused(pPager);
35327
35328  *ppPage = 0;
35329  return rc;
35330}
35331
35332/*
35333** Acquire a page if it is already in the in-memory cache.  Do
35334** not read the page from disk.  Return a pointer to the page,
35335** or 0 if the page is not in cache. Also, return 0 if the
35336** pager is in PAGER_UNLOCK state when this function is called,
35337** or if the pager is in an error state other than SQLITE_FULL.
35338**
35339** See also sqlite3PagerGet().  The difference between this routine
35340** and sqlite3PagerGet() is that _get() will go to the disk and read
35341** in the page if the page is not already in cache.  This routine
35342** returns NULL if the page is not in cache or if a disk I/O error
35343** has ever happened.
35344*/
35345SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
35346  PgHdr *pPg = 0;
35347  assert( pPager!=0 );
35348  assert( pgno!=0 );
35349  assert( pPager->pPCache!=0 );
35350  assert( pPager->state > PAGER_UNLOCK );
35351  sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
35352  return pPg;
35353}
35354
35355/*
35356** Release a page reference.
35357**
35358** If the number of references to the page drop to zero, then the
35359** page is added to the LRU list.  When all references to all pages
35360** are released, a rollback occurs and the lock on the database is
35361** removed.
35362*/
35363SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
35364  if( pPg ){
35365    Pager *pPager = pPg->pPager;
35366    sqlite3PcacheRelease(pPg);
35367    pagerUnlockIfUnused(pPager);
35368  }
35369}
35370
35371/*
35372** If the main journal file has already been opened, ensure that the
35373** sub-journal file is open too. If the main journal is not open,
35374** this function is a no-op.
35375**
35376** SQLITE_OK is returned if everything goes according to plan.
35377** An SQLITE_IOERR_XXX error code is returned if a call to
35378** sqlite3OsOpen() fails.
35379*/
35380static int openSubJournal(Pager *pPager){
35381  int rc = SQLITE_OK;
35382  if( isOpen(pPager->jfd) && !isOpen(pPager->sjfd) ){
35383    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
35384      sqlite3MemJournalOpen(pPager->sjfd);
35385    }else{
35386      rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
35387    }
35388  }
35389  return rc;
35390}
35391
35392/*
35393** This function is called at the start of every write transaction.
35394** There must already be a RESERVED or EXCLUSIVE lock on the database
35395** file when this routine is called.
35396**
35397** Open the journal file for pager pPager and write a journal header
35398** to the start of it. If there are active savepoints, open the sub-journal
35399** as well. This function is only used when the journal file is being
35400** opened to write a rollback log for a transaction. It is not used
35401** when opening a hot journal file to roll it back.
35402**
35403** If the journal file is already open (as it may be in exclusive mode),
35404** then this function just writes a journal header to the start of the
35405** already open file.
35406**
35407** Whether or not the journal file is opened by this function, the
35408** Pager.pInJournal bitvec structure is allocated.
35409**
35410** Return SQLITE_OK if everything is successful. Otherwise, return
35411** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
35412** an IO error code if opening or writing the journal file fails.
35413*/
35414static int pager_open_journal(Pager *pPager){
35415  int rc = SQLITE_OK;                        /* Return code */
35416  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
35417
35418  assert( pPager->state>=PAGER_RESERVED );
35419  assert( pPager->useJournal );
35420  assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF );
35421  assert( pPager->pInJournal==0 );
35422
35423  /* If already in the error state, this function is a no-op.  But on
35424  ** the other hand, this routine is never called if we are already in
35425  ** an error state. */
35426  if( NEVER(pPager->errCode) ) return pPager->errCode;
35427
35428  /* TODO: Is it really possible to get here with dbSizeValid==0? If not,
35429  ** the call to PagerPagecount() can be removed.
35430  */
35431  testcase( pPager->dbSizeValid==0 );
35432  sqlite3PagerPagecount(pPager, 0);
35433
35434  pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
35435  if( pPager->pInJournal==0 ){
35436    return SQLITE_NOMEM;
35437  }
35438
35439  /* Open the journal file if it is not already open. */
35440  if( !isOpen(pPager->jfd) ){
35441    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
35442      sqlite3MemJournalOpen(pPager->jfd);
35443    }else{
35444      const int flags =                   /* VFS flags to open journal file */
35445        SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
35446        (pPager->tempFile ?
35447          (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
35448          (SQLITE_OPEN_MAIN_JOURNAL)
35449        );
35450#ifdef SQLITE_ENABLE_ATOMIC_WRITE
35451      rc = sqlite3JournalOpen(
35452          pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
35453      );
35454#else
35455      rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
35456#endif
35457    }
35458    assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
35459  }
35460
35461
35462  /* Write the first journal header to the journal file and open
35463  ** the sub-journal if necessary.
35464  */
35465  if( rc==SQLITE_OK ){
35466    /* TODO: Check if all of these are really required. */
35467    pPager->dbOrigSize = pPager->dbSize;
35468    pPager->journalStarted = 0;
35469    pPager->needSync = 0;
35470    pPager->nRec = 0;
35471    pPager->journalOff = 0;
35472    pPager->setMaster = 0;
35473    pPager->journalHdr = 0;
35474    rc = writeJournalHdr(pPager);
35475  }
35476  if( rc==SQLITE_OK && pPager->nSavepoint ){
35477    rc = openSubJournal(pPager);
35478  }
35479
35480  if( rc!=SQLITE_OK ){
35481    sqlite3BitvecDestroy(pPager->pInJournal);
35482    pPager->pInJournal = 0;
35483  }
35484  return rc;
35485}
35486
35487/*
35488** Begin a write-transaction on the specified pager object. If a
35489** write-transaction has already been opened, this function is a no-op.
35490**
35491** If the exFlag argument is false, then acquire at least a RESERVED
35492** lock on the database file. If exFlag is true, then acquire at least
35493** an EXCLUSIVE lock. If such a lock is already held, no locking
35494** functions need be called.
35495**
35496** If this is not a temporary or in-memory file and, the journal file is
35497** opened if it has not been already. For a temporary file, the opening
35498** of the journal file is deferred until there is an actual need to
35499** write to the journal. TODO: Why handle temporary files differently?
35500**
35501** If the journal file is opened (or if it is already open), then a
35502** journal-header is written to the start of it.
35503**
35504** If the subjInMemory argument is non-zero, then any sub-journal opened
35505** within this transaction will be opened as an in-memory file. This
35506** has no effect if the sub-journal is already opened (as it may be when
35507** running in exclusive mode) or if the transaction does not require a
35508** sub-journal. If the subjInMemory argument is zero, then any required
35509** sub-journal is implemented in-memory if pPager is an in-memory database,
35510** or using a temporary file otherwise.
35511*/
35512SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
35513  int rc = SQLITE_OK;
35514  assert( pPager->state!=PAGER_UNLOCK );
35515  pPager->subjInMemory = (u8)subjInMemory;
35516  if( pPager->state==PAGER_SHARED ){
35517    assert( pPager->pInJournal==0 );
35518    assert( !MEMDB && !pPager->tempFile );
35519
35520    /* Obtain a RESERVED lock on the database file. If the exFlag parameter
35521    ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
35522    ** busy-handler callback can be used when upgrading to the EXCLUSIVE
35523    ** lock, but not when obtaining the RESERVED lock.
35524    */
35525    rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
35526    if( rc==SQLITE_OK ){
35527      pPager->state = PAGER_RESERVED;
35528      if( exFlag ){
35529        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
35530      }
35531    }
35532
35533    /* If the required locks were successfully obtained, open the journal
35534    ** file and write the first journal-header to it.
35535    */
35536    if( rc==SQLITE_OK && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
35537      rc = pager_open_journal(pPager);
35538    }
35539  }else if( isOpen(pPager->jfd) && pPager->journalOff==0 ){
35540    /* This happens when the pager was in exclusive-access mode the last
35541    ** time a (read or write) transaction was successfully concluded
35542    ** by this connection. Instead of deleting the journal file it was
35543    ** kept open and either was truncated to 0 bytes or its header was
35544    ** overwritten with zeros.
35545    */
35546    assert( pPager->nRec==0 );
35547    assert( pPager->dbOrigSize==0 );
35548    assert( pPager->pInJournal==0 );
35549    rc = pager_open_journal(pPager);
35550  }
35551
35552  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
35553  assert( !isOpen(pPager->jfd) || pPager->journalOff>0 || rc!=SQLITE_OK );
35554  if( rc!=SQLITE_OK ){
35555    assert( !pPager->dbModified );
35556    /* Ignore any IO error that occurs within pager_end_transaction(). The
35557    ** purpose of this call is to reset the internal state of the pager
35558    ** sub-system. It doesn't matter if the journal-file is not properly
35559    ** finalized at this point (since it is not a valid journal file anyway).
35560    */
35561    pager_end_transaction(pPager, 0);
35562  }
35563  return rc;
35564}
35565
35566/*
35567** Mark a single data page as writeable. The page is written into the
35568** main journal or sub-journal as required. If the page is written into
35569** one of the journals, the corresponding bit is set in the
35570** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
35571** of any open savepoints as appropriate.
35572*/
35573static int pager_write(PgHdr *pPg){
35574  void *pData = pPg->pData;
35575  Pager *pPager = pPg->pPager;
35576  int rc = SQLITE_OK;
35577
35578  /* This routine is not called unless a transaction has already been
35579  ** started.
35580  */
35581  assert( pPager->state>=PAGER_RESERVED );
35582
35583  /* If an error has been previously detected, we should not be
35584  ** calling this routine.  Repeat the error for robustness.
35585  */
35586  if( NEVER(pPager->errCode) )  return pPager->errCode;
35587
35588  /* Higher-level routines never call this function if database is not
35589  ** writable.  But check anyway, just for robustness. */
35590  if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
35591
35592  assert( !pPager->setMaster );
35593
35594  CHECK_PAGE(pPg);
35595
35596  /* Mark the page as dirty.  If the page has already been written
35597  ** to the journal then we can return right away.
35598  */
35599  sqlite3PcacheMakeDirty(pPg);
35600  if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
35601    pPager->dbModified = 1;
35602  }else{
35603
35604    /* If we get this far, it means that the page needs to be
35605    ** written to the transaction journal or the ckeckpoint journal
35606    ** or both.
35607    **
35608    ** Higher level routines should have already started a transaction,
35609    ** which means they have acquired the necessary locks and opened
35610    ** a rollback journal.  Double-check to makes sure this is the case.
35611    */
35612    rc = sqlite3PagerBegin(pPager, 0, pPager->subjInMemory);
35613    if( NEVER(rc!=SQLITE_OK) ){
35614      return rc;
35615    }
35616    if( !isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
35617      assert( pPager->useJournal );
35618      rc = pager_open_journal(pPager);
35619      if( rc!=SQLITE_OK ) return rc;
35620    }
35621    pPager->dbModified = 1;
35622
35623    /* The transaction journal now exists and we have a RESERVED or an
35624    ** EXCLUSIVE lock on the main database file.  Write the current page to
35625    ** the transaction journal if it is not there already.
35626    */
35627    if( !pageInJournal(pPg) && isOpen(pPager->jfd) ){
35628      if( pPg->pgno<=pPager->dbOrigSize ){
35629        u32 cksum;
35630        char *pData2;
35631
35632        /* We should never write to the journal file the page that
35633        ** contains the database locks.  The following assert verifies
35634        ** that we do not. */
35635        assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
35636        CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
35637        cksum = pager_cksum(pPager, (u8*)pData2);
35638        rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
35639        if( rc==SQLITE_OK ){
35640          rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
35641                              pPager->journalOff + 4);
35642          pPager->journalOff += pPager->pageSize+4;
35643        }
35644        if( rc==SQLITE_OK ){
35645          rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
35646          pPager->journalOff += 4;
35647        }
35648        IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
35649                 pPager->journalOff, pPager->pageSize));
35650        PAGER_INCR(sqlite3_pager_writej_count);
35651        PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
35652             PAGERID(pPager), pPg->pgno,
35653             ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
35654
35655        /* Even if an IO or diskfull error occurred while journalling the
35656        ** page in the block above, set the need-sync flag for the page.
35657        ** Otherwise, when the transaction is rolled back, the logic in
35658        ** playback_one_page() will think that the page needs to be restored
35659        ** in the database file. And if an IO error occurs while doing so,
35660        ** then corruption may follow.
35661        */
35662        if( !pPager->noSync ){
35663          pPg->flags |= PGHDR_NEED_SYNC;
35664          pPager->needSync = 1;
35665        }
35666
35667        /* An error has occurred writing to the journal file. The
35668        ** transaction will be rolled back by the layer above.
35669        */
35670        if( rc!=SQLITE_OK ){
35671          return rc;
35672        }
35673
35674        pPager->nRec++;
35675        assert( pPager->pInJournal!=0 );
35676        rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
35677        testcase( rc==SQLITE_NOMEM );
35678        assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
35679        rc |= addToSavepointBitvecs(pPager, pPg->pgno);
35680        if( rc!=SQLITE_OK ){
35681          assert( rc==SQLITE_NOMEM );
35682          return rc;
35683        }
35684      }else{
35685        if( !pPager->journalStarted && !pPager->noSync ){
35686          pPg->flags |= PGHDR_NEED_SYNC;
35687          pPager->needSync = 1;
35688        }
35689        PAGERTRACE(("APPEND %d page %d needSync=%d\n",
35690                PAGERID(pPager), pPg->pgno,
35691               ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
35692      }
35693    }
35694
35695    /* If the statement journal is open and the page is not in it,
35696    ** then write the current page to the statement journal.  Note that
35697    ** the statement journal format differs from the standard journal format
35698    ** in that it omits the checksums and the header.
35699    */
35700    if( subjRequiresPage(pPg) ){
35701      rc = subjournalPage(pPg);
35702    }
35703  }
35704
35705  /* Update the database size and return.
35706  */
35707  assert( pPager->state>=PAGER_SHARED );
35708  if( pPager->dbSize<pPg->pgno ){
35709    pPager->dbSize = pPg->pgno;
35710  }
35711  return rc;
35712}
35713
35714/*
35715** Mark a data page as writeable. This routine must be called before
35716** making changes to a page. The caller must check the return value
35717** of this function and be careful not to change any page data unless
35718** this routine returns SQLITE_OK.
35719**
35720** The difference between this function and pager_write() is that this
35721** function also deals with the special case where 2 or more pages
35722** fit on a single disk sector. In this case all co-resident pages
35723** must have been written to the journal file before returning.
35724**
35725** If an error occurs, SQLITE_NOMEM or an IO error code is returned
35726** as appropriate. Otherwise, SQLITE_OK.
35727*/
35728SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
35729  int rc = SQLITE_OK;
35730
35731  PgHdr *pPg = pDbPage;
35732  Pager *pPager = pPg->pPager;
35733  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
35734
35735  if( nPagePerSector>1 ){
35736    Pgno nPageCount;          /* Total number of pages in database file */
35737    Pgno pg1;                 /* First page of the sector pPg is located on. */
35738    int nPage;                /* Number of pages starting at pg1 to journal */
35739    int ii;                   /* Loop counter */
35740    int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
35741
35742    /* Set the doNotSync flag to 1. This is because we cannot allow a journal
35743    ** header to be written between the pages journaled by this function.
35744    */
35745    assert( !MEMDB );
35746    assert( pPager->doNotSync==0 );
35747    pPager->doNotSync = 1;
35748
35749    /* This trick assumes that both the page-size and sector-size are
35750    ** an integer power of 2. It sets variable pg1 to the identifier
35751    ** of the first page of the sector pPg is located on.
35752    */
35753    pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
35754
35755    sqlite3PagerPagecount(pPager, (int *)&nPageCount);
35756    if( pPg->pgno>nPageCount ){
35757      nPage = (pPg->pgno - pg1)+1;
35758    }else if( (pg1+nPagePerSector-1)>nPageCount ){
35759      nPage = nPageCount+1-pg1;
35760    }else{
35761      nPage = nPagePerSector;
35762    }
35763    assert(nPage>0);
35764    assert(pg1<=pPg->pgno);
35765    assert((pg1+nPage)>pPg->pgno);
35766
35767    for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
35768      Pgno pg = pg1+ii;
35769      PgHdr *pPage;
35770      if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
35771        if( pg!=PAGER_MJ_PGNO(pPager) ){
35772          rc = sqlite3PagerGet(pPager, pg, &pPage);
35773          if( rc==SQLITE_OK ){
35774            rc = pager_write(pPage);
35775            if( pPage->flags&PGHDR_NEED_SYNC ){
35776              needSync = 1;
35777              assert(pPager->needSync);
35778            }
35779            sqlite3PagerUnref(pPage);
35780          }
35781        }
35782      }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
35783        if( pPage->flags&PGHDR_NEED_SYNC ){
35784          needSync = 1;
35785        }
35786        sqlite3PagerUnref(pPage);
35787      }
35788    }
35789
35790    /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
35791    ** starting at pg1, then it needs to be set for all of them. Because
35792    ** writing to any of these nPage pages may damage the others, the
35793    ** journal file must contain sync()ed copies of all of them
35794    ** before any of them can be written out to the database file.
35795    */
35796    if( rc==SQLITE_OK && needSync ){
35797      assert( !MEMDB && pPager->noSync==0 );
35798      for(ii=0; ii<nPage; ii++){
35799        PgHdr *pPage = pager_lookup(pPager, pg1+ii);
35800        if( pPage ){
35801          pPage->flags |= PGHDR_NEED_SYNC;
35802          sqlite3PagerUnref(pPage);
35803        }
35804      }
35805      assert(pPager->needSync);
35806    }
35807
35808    assert( pPager->doNotSync==1 );
35809    pPager->doNotSync = 0;
35810  }else{
35811    rc = pager_write(pDbPage);
35812  }
35813  return rc;
35814}
35815
35816/*
35817** Return TRUE if the page given in the argument was previously passed
35818** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
35819** to change the content of the page.
35820*/
35821#ifndef NDEBUG
35822SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
35823  return pPg->flags&PGHDR_DIRTY;
35824}
35825#endif
35826
35827#ifndef SQLITE_SECURE_DELETE
35828/*
35829** A call to this routine tells the pager that it is not necessary to
35830** write the information on page pPg back to the disk, even though
35831** that page might be marked as dirty.  This happens, for example, when
35832** the page has been added as a leaf of the freelist and so its
35833** content no longer matters.
35834**
35835** The overlying software layer calls this routine when all of the data
35836** on the given page is unused. The pager marks the page as clean so
35837** that it does not get written to disk.
35838**
35839** Tests show that this optimization can quadruple the speed of large
35840** DELETE operations.
35841*/
35842SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
35843  Pager *pPager = pPg->pPager;
35844  if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
35845    PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
35846    IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
35847    pPg->flags |= PGHDR_DONT_WRITE;
35848#ifdef SQLITE_CHECK_PAGES
35849    pPg->pageHash = pager_pagehash(pPg);
35850#endif
35851  }
35852}
35853#endif /* !defined(SQLITE_SECURE_DELETE) */
35854
35855/*
35856** This routine is called to increment the value of the database file
35857** change-counter, stored as a 4-byte big-endian integer starting at
35858** byte offset 24 of the pager file.
35859**
35860** If the isDirectMode flag is zero, then this is done by calling
35861** sqlite3PagerWrite() on page 1, then modifying the contents of the
35862** page data. In this case the file will be updated when the current
35863** transaction is committed.
35864**
35865** The isDirectMode flag may only be non-zero if the library was compiled
35866** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
35867** if isDirect is non-zero, then the database file is updated directly
35868** by writing an updated version of page 1 using a call to the
35869** sqlite3OsWrite() function.
35870*/
35871static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
35872  int rc = SQLITE_OK;
35873
35874  /* Declare and initialize constant integer 'isDirect'. If the
35875  ** atomic-write optimization is enabled in this build, then isDirect
35876  ** is initialized to the value passed as the isDirectMode parameter
35877  ** to this function. Otherwise, it is always set to zero.
35878  **
35879  ** The idea is that if the atomic-write optimization is not
35880  ** enabled at compile time, the compiler can omit the tests of
35881  ** 'isDirect' below, as well as the block enclosed in the
35882  ** "if( isDirect )" condition.
35883  */
35884#ifndef SQLITE_ENABLE_ATOMIC_WRITE
35885# define DIRECT_MODE 0
35886  assert( isDirectMode==0 );
35887  UNUSED_PARAMETER(isDirectMode);
35888#else
35889# define DIRECT_MODE isDirectMode
35890#endif
35891
35892  assert( pPager->state>=PAGER_RESERVED );
35893  if( !pPager->changeCountDone && pPager->dbSize>0 ){
35894    PgHdr *pPgHdr;                /* Reference to page 1 */
35895    u32 change_counter;           /* Initial value of change-counter field */
35896
35897    assert( !pPager->tempFile && isOpen(pPager->fd) );
35898
35899    /* Open page 1 of the file for writing. */
35900    rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
35901    assert( pPgHdr==0 || rc==SQLITE_OK );
35902
35903    /* If page one was fetched successfully, and this function is not
35904    ** operating in direct-mode, make page 1 writable.  When not in
35905    ** direct mode, page 1 is always held in cache and hence the PagerGet()
35906    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
35907    */
35908    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
35909      rc = sqlite3PagerWrite(pPgHdr);
35910    }
35911
35912    if( rc==SQLITE_OK ){
35913      /* Increment the value just read and write it back to byte 24. */
35914      change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
35915      change_counter++;
35916      put32bits(((char*)pPgHdr->pData)+24, change_counter);
35917
35918      /* If running in direct mode, write the contents of page 1 to the file. */
35919      if( DIRECT_MODE ){
35920        const void *zBuf = pPgHdr->pData;
35921        assert( pPager->dbFileSize>0 );
35922        rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
35923        if( rc==SQLITE_OK ){
35924          pPager->changeCountDone = 1;
35925        }
35926      }else{
35927        pPager->changeCountDone = 1;
35928      }
35929    }
35930
35931    /* Release the page reference. */
35932    sqlite3PagerUnref(pPgHdr);
35933  }
35934  return rc;
35935}
35936
35937/*
35938** Sync the pager file to disk. This is a no-op for in-memory files
35939** or pages with the Pager.noSync flag set.
35940**
35941** If successful, or called on a pager for which it is a no-op, this
35942** function returns SQLITE_OK. Otherwise, an IO error code is returned.
35943*/
35944SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
35945  int rc;                              /* Return code */
35946  assert( !MEMDB );
35947  if( pPager->noSync ){
35948    rc = SQLITE_OK;
35949  }else{
35950    rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
35951  }
35952  return rc;
35953}
35954
35955/*
35956** Sync the database file for the pager pPager. zMaster points to the name
35957** of a master journal file that should be written into the individual
35958** journal file. zMaster may be NULL, which is interpreted as no master
35959** journal (a single database transaction).
35960**
35961** This routine ensures that:
35962**
35963**   * The database file change-counter is updated,
35964**   * the journal is synced (unless the atomic-write optimization is used),
35965**   * all dirty pages are written to the database file,
35966**   * the database file is truncated (if required), and
35967**   * the database file synced.
35968**
35969** The only thing that remains to commit the transaction is to finalize
35970** (delete, truncate or zero the first part of) the journal file (or
35971** delete the master journal file if specified).
35972**
35973** Note that if zMaster==NULL, this does not overwrite a previous value
35974** passed to an sqlite3PagerCommitPhaseOne() call.
35975**
35976** If the final parameter - noSync - is true, then the database file itself
35977** is not synced. The caller must call sqlite3PagerSync() directly to
35978** sync the database file before calling CommitPhaseTwo() to delete the
35979** journal file in this case.
35980*/
35981SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
35982  Pager *pPager,                  /* Pager object */
35983  const char *zMaster,            /* If not NULL, the master journal name */
35984  int noSync                      /* True to omit the xSync on the db file */
35985){
35986  int rc = SQLITE_OK;             /* Return code */
35987
35988  /* The dbOrigSize is never set if journal_mode=OFF */
35989  assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF || pPager->dbOrigSize==0 );
35990
35991  /* If a prior error occurred, this routine should not be called.  ROLLBACK
35992  ** is the appropriate response to an error, not COMMIT.  Guard against
35993  ** coding errors by repeating the prior error. */
35994  if( NEVER(pPager->errCode) ) return pPager->errCode;
35995
35996  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
35997      pPager->zFilename, zMaster, pPager->dbSize));
35998
35999  if( MEMDB && pPager->dbModified ){
36000    /* If this is an in-memory db, or no pages have been written to, or this
36001    ** function has already been called, it is mostly a no-op.  However, any
36002    ** backup in progress needs to be restarted.
36003    */
36004    sqlite3BackupRestart(pPager->pBackup);
36005  }else if( pPager->state!=PAGER_SYNCED && pPager->dbModified ){
36006
36007    /* The following block updates the change-counter. Exactly how it
36008    ** does this depends on whether or not the atomic-update optimization
36009    ** was enabled at compile time, and if this transaction meets the
36010    ** runtime criteria to use the operation:
36011    **
36012    **    * The file-system supports the atomic-write property for
36013    **      blocks of size page-size, and
36014    **    * This commit is not part of a multi-file transaction, and
36015    **    * Exactly one page has been modified and store in the journal file.
36016    **
36017    ** If the optimization was not enabled at compile time, then the
36018    ** pager_incr_changecounter() function is called to update the change
36019    ** counter in 'indirect-mode'. If the optimization is compiled in but
36020    ** is not applicable to this transaction, call sqlite3JournalCreate()
36021    ** to make sure the journal file has actually been created, then call
36022    ** pager_incr_changecounter() to update the change-counter in indirect
36023    ** mode.
36024    **
36025    ** Otherwise, if the optimization is both enabled and applicable,
36026    ** then call pager_incr_changecounter() to update the change-counter
36027    ** in 'direct' mode. In this case the journal file will never be
36028    ** created for this transaction.
36029    */
36030#ifdef SQLITE_ENABLE_ATOMIC_WRITE
36031    PgHdr *pPg;
36032    assert( isOpen(pPager->jfd) || pPager->journalMode==PAGER_JOURNALMODE_OFF );
36033    if( !zMaster && isOpen(pPager->jfd)
36034     && pPager->journalOff==jrnlBufferSize(pPager)
36035     && pPager->dbSize>=pPager->dbFileSize
36036     && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
36037    ){
36038      /* Update the db file change counter via the direct-write method. The
36039      ** following call will modify the in-memory representation of page 1
36040      ** to include the updated change counter and then write page 1
36041      ** directly to the database file. Because of the atomic-write
36042      ** property of the host file-system, this is safe.
36043      */
36044      rc = pager_incr_changecounter(pPager, 1);
36045    }else{
36046      rc = sqlite3JournalCreate(pPager->jfd);
36047      if( rc==SQLITE_OK ){
36048        rc = pager_incr_changecounter(pPager, 0);
36049      }
36050    }
36051#else
36052    rc = pager_incr_changecounter(pPager, 0);
36053#endif
36054    if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
36055
36056    /* If this transaction has made the database smaller, then all pages
36057    ** being discarded by the truncation must be written to the journal
36058    ** file. This can only happen in auto-vacuum mode.
36059    **
36060    ** Before reading the pages with page numbers larger than the
36061    ** current value of Pager.dbSize, set dbSize back to the value
36062    ** that it took at the start of the transaction. Otherwise, the
36063    ** calls to sqlite3PagerGet() return zeroed pages instead of
36064    ** reading data from the database file.
36065    **
36066    ** When journal_mode==OFF the dbOrigSize is always zero, so this
36067    ** block never runs if journal_mode=OFF.
36068    */
36069#ifndef SQLITE_OMIT_AUTOVACUUM
36070    if( pPager->dbSize<pPager->dbOrigSize
36071     && ALWAYS(pPager->journalMode!=PAGER_JOURNALMODE_OFF)
36072    ){
36073      Pgno i;                                   /* Iterator variable */
36074      const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
36075      const Pgno dbSize = pPager->dbSize;       /* Database image size */
36076      pPager->dbSize = pPager->dbOrigSize;
36077      for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
36078        if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
36079          PgHdr *pPage;             /* Page to journal */
36080          rc = sqlite3PagerGet(pPager, i, &pPage);
36081          if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
36082          rc = sqlite3PagerWrite(pPage);
36083          sqlite3PagerUnref(pPage);
36084          if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
36085        }
36086      }
36087      pPager->dbSize = dbSize;
36088    }
36089#endif
36090
36091    /* Write the master journal name into the journal file. If a master
36092    ** journal file name has already been written to the journal file,
36093    ** or if zMaster is NULL (no master journal), then this call is a no-op.
36094    */
36095    rc = writeMasterJournal(pPager, zMaster);
36096    if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
36097
36098    /* Sync the journal file. If the atomic-update optimization is being
36099    ** used, this call will not create the journal file or perform any
36100    ** real IO.
36101    */
36102    rc = syncJournal(pPager);
36103    if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
36104
36105    /* Write all dirty pages to the database file. */
36106    rc = pager_write_pagelist(sqlite3PcacheDirtyList(pPager->pPCache));
36107    if( rc!=SQLITE_OK ){
36108      assert( rc!=SQLITE_IOERR_BLOCKED );
36109      goto commit_phase_one_exit;
36110    }
36111    sqlite3PcacheCleanAll(pPager->pPCache);
36112
36113    /* If the file on disk is not the same size as the database image,
36114    ** then use pager_truncate to grow or shrink the file here.
36115    */
36116    if( pPager->dbSize!=pPager->dbFileSize ){
36117      Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
36118      assert( pPager->state>=PAGER_EXCLUSIVE );
36119      rc = pager_truncate(pPager, nNew);
36120      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
36121    }
36122
36123    /* Finally, sync the database file. */
36124    if( !pPager->noSync && !noSync ){
36125      rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
36126    }
36127    IOTRACE(("DBSYNC %p\n", pPager))
36128
36129    pPager->state = PAGER_SYNCED;
36130  }
36131
36132commit_phase_one_exit:
36133  return rc;
36134}
36135
36136
36137/*
36138** When this function is called, the database file has been completely
36139** updated to reflect the changes made by the current transaction and
36140** synced to disk. The journal file still exists in the file-system
36141** though, and if a failure occurs at this point it will eventually
36142** be used as a hot-journal and the current transaction rolled back.
36143**
36144** This function finalizes the journal file, either by deleting,
36145** truncating or partially zeroing it, so that it cannot be used
36146** for hot-journal rollback. Once this is done the transaction is
36147** irrevocably committed.
36148**
36149** If an error occurs, an IO error code is returned and the pager
36150** moves into the error state. Otherwise, SQLITE_OK is returned.
36151*/
36152SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
36153  int rc = SQLITE_OK;                  /* Return code */
36154
36155  /* This routine should not be called if a prior error has occurred.
36156  ** But if (due to a coding error elsewhere in the system) it does get
36157  ** called, just return the same error code without doing anything. */
36158  if( NEVER(pPager->errCode) ) return pPager->errCode;
36159
36160  /* This function should not be called if the pager is not in at least
36161  ** PAGER_RESERVED state. And indeed SQLite never does this. But it is
36162  ** nice to have this defensive test here anyway.
36163  */
36164  if( NEVER(pPager->state<PAGER_RESERVED) ) return SQLITE_ERROR;
36165
36166  /* An optimization. If the database was not actually modified during
36167  ** this transaction, the pager is running in exclusive-mode and is
36168  ** using persistent journals, then this function is a no-op.
36169  **
36170  ** The start of the journal file currently contains a single journal
36171  ** header with the nRec field set to 0. If such a journal is used as
36172  ** a hot-journal during hot-journal rollback, 0 changes will be made
36173  ** to the database file. So there is no need to zero the journal
36174  ** header. Since the pager is in exclusive mode, there is no need
36175  ** to drop any locks either.
36176  */
36177  if( pPager->dbModified==0 && pPager->exclusiveMode
36178   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
36179  ){
36180    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
36181    return SQLITE_OK;
36182  }
36183
36184  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
36185  assert( pPager->state==PAGER_SYNCED || MEMDB || !pPager->dbModified );
36186  rc = pager_end_transaction(pPager, pPager->setMaster);
36187  return pager_error(pPager, rc);
36188}
36189
36190/*
36191** Rollback all changes. The database falls back to PAGER_SHARED mode.
36192**
36193** This function performs two tasks:
36194**
36195**   1) It rolls back the journal file, restoring all database file and
36196**      in-memory cache pages to the state they were in when the transaction
36197**      was opened, and
36198**   2) It finalizes the journal file, so that it is not used for hot
36199**      rollback at any point in the future.
36200**
36201** subject to the following qualifications:
36202**
36203** * If the journal file is not yet open when this function is called,
36204**   then only (2) is performed. In this case there is no journal file
36205**   to roll back.
36206**
36207** * If in an error state other than SQLITE_FULL, then task (1) is
36208**   performed. If successful, task (2). Regardless of the outcome
36209**   of either, the error state error code is returned to the caller
36210**   (i.e. either SQLITE_IOERR or SQLITE_CORRUPT).
36211**
36212** * If the pager is in PAGER_RESERVED state, then attempt (1). Whether
36213**   or not (1) is succussful, also attempt (2). If successful, return
36214**   SQLITE_OK. Otherwise, enter the error state and return the first
36215**   error code encountered.
36216**
36217**   In this case there is no chance that the database was written to.
36218**   So is safe to finalize the journal file even if the playback
36219**   (operation 1) failed. However the pager must enter the error state
36220**   as the contents of the in-memory cache are now suspect.
36221**
36222** * Finally, if in PAGER_EXCLUSIVE state, then attempt (1). Only
36223**   attempt (2) if (1) is successful. Return SQLITE_OK if successful,
36224**   otherwise enter the error state and return the error code from the
36225**   failing operation.
36226**
36227**   In this case the database file may have been written to. So if the
36228**   playback operation did not succeed it would not be safe to finalize
36229**   the journal file. It needs to be left in the file-system so that
36230**   some other process can use it to restore the database state (by
36231**   hot-journal rollback).
36232*/
36233SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
36234  int rc = SQLITE_OK;                  /* Return code */
36235  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
36236  if( !pPager->dbModified || !isOpen(pPager->jfd) ){
36237    rc = pager_end_transaction(pPager, pPager->setMaster);
36238  }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
36239    if( pPager->state>=PAGER_EXCLUSIVE ){
36240      pager_playback(pPager, 0);
36241    }
36242    rc = pPager->errCode;
36243  }else{
36244    if( pPager->state==PAGER_RESERVED ){
36245      int rc2;
36246      rc = pager_playback(pPager, 0);
36247      rc2 = pager_end_transaction(pPager, pPager->setMaster);
36248      if( rc==SQLITE_OK ){
36249        rc = rc2;
36250      }
36251    }else{
36252      rc = pager_playback(pPager, 0);
36253    }
36254
36255    if( !MEMDB ){
36256      pPager->dbSizeValid = 0;
36257    }
36258
36259    /* If an error occurs during a ROLLBACK, we can no longer trust the pager
36260    ** cache. So call pager_error() on the way out to make any error
36261    ** persistent.
36262    */
36263    rc = pager_error(pPager, rc);
36264  }
36265  return rc;
36266}
36267
36268/*
36269** Return TRUE if the database file is opened read-only.  Return FALSE
36270** if the database is (in theory) writable.
36271*/
36272SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
36273  return pPager->readOnly;
36274}
36275
36276/*
36277** Return the number of references to the pager.
36278*/
36279SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
36280  return sqlite3PcacheRefCount(pPager->pPCache);
36281}
36282
36283/*
36284** Return the number of references to the specified page.
36285*/
36286SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
36287  return sqlite3PcachePageRefcount(pPage);
36288}
36289
36290#ifdef SQLITE_TEST
36291/*
36292** This routine is used for testing and analysis only.
36293*/
36294SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
36295  static int a[11];
36296  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
36297  a[1] = sqlite3PcachePagecount(pPager->pPCache);
36298  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
36299  a[3] = pPager->dbSizeValid ? (int) pPager->dbSize : -1;
36300  a[4] = pPager->state;
36301  a[5] = pPager->errCode;
36302  a[6] = pPager->nHit;
36303  a[7] = pPager->nMiss;
36304  a[8] = 0;  /* Used to be pPager->nOvfl */
36305  a[9] = pPager->nRead;
36306  a[10] = pPager->nWrite;
36307  return a;
36308}
36309#endif
36310
36311/*
36312** Return true if this is an in-memory pager.
36313*/
36314SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
36315  return MEMDB;
36316}
36317
36318/*
36319** Check that there are at least nSavepoint savepoints open. If there are
36320** currently less than nSavepoints open, then open one or more savepoints
36321** to make up the difference. If the number of savepoints is already
36322** equal to nSavepoint, then this function is a no-op.
36323**
36324** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
36325** occurs while opening the sub-journal file, then an IO error code is
36326** returned. Otherwise, SQLITE_OK.
36327*/
36328SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
36329  int rc = SQLITE_OK;                       /* Return code */
36330  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
36331
36332  if( nSavepoint>nCurrent && pPager->useJournal ){
36333    int ii;                                 /* Iterator variable */
36334    PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
36335
36336    /* Either there is no active journal or the sub-journal is open or
36337    ** the journal is always stored in memory */
36338    assert( pPager->nSavepoint==0 || isOpen(pPager->sjfd) ||
36339            pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
36340
36341    /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
36342    ** if the allocation fails. Otherwise, zero the new portion in case a
36343    ** malloc failure occurs while populating it in the for(...) loop below.
36344    */
36345    aNew = (PagerSavepoint *)sqlite3Realloc(
36346        pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
36347    );
36348    if( !aNew ){
36349      return SQLITE_NOMEM;
36350    }
36351    memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
36352    pPager->aSavepoint = aNew;
36353    pPager->nSavepoint = nSavepoint;
36354
36355    /* Populate the PagerSavepoint structures just allocated. */
36356    for(ii=nCurrent; ii<nSavepoint; ii++){
36357      assert( pPager->dbSizeValid );
36358      aNew[ii].nOrig = pPager->dbSize;
36359      if( isOpen(pPager->jfd) && ALWAYS(pPager->journalOff>0) ){
36360        aNew[ii].iOffset = pPager->journalOff;
36361      }else{
36362        aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
36363      }
36364      aNew[ii].iSubRec = pPager->nSubRec;
36365      aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
36366      if( !aNew[ii].pInSavepoint ){
36367        return SQLITE_NOMEM;
36368      }
36369    }
36370
36371    /* Open the sub-journal, if it is not already opened. */
36372    rc = openSubJournal(pPager);
36373    assertTruncateConstraint(pPager);
36374  }
36375
36376  return rc;
36377}
36378
36379/*
36380** This function is called to rollback or release (commit) a savepoint.
36381** The savepoint to release or rollback need not be the most recently
36382** created savepoint.
36383**
36384** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
36385** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
36386** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
36387** that have occurred since the specified savepoint was created.
36388**
36389** The savepoint to rollback or release is identified by parameter
36390** iSavepoint. A value of 0 means to operate on the outermost savepoint
36391** (the first created). A value of (Pager.nSavepoint-1) means operate
36392** on the most recently created savepoint. If iSavepoint is greater than
36393** (Pager.nSavepoint-1), then this function is a no-op.
36394**
36395** If a negative value is passed to this function, then the current
36396** transaction is rolled back. This is different to calling
36397** sqlite3PagerRollback() because this function does not terminate
36398** the transaction or unlock the database, it just restores the
36399** contents of the database to its original state.
36400**
36401** In any case, all savepoints with an index greater than iSavepoint
36402** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
36403** then savepoint iSavepoint is also destroyed.
36404**
36405** This function may return SQLITE_NOMEM if a memory allocation fails,
36406** or an IO error code if an IO error occurs while rolling back a
36407** savepoint. If no errors occur, SQLITE_OK is returned.
36408*/
36409SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
36410  int rc = SQLITE_OK;
36411
36412  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
36413  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
36414
36415  if( iSavepoint<pPager->nSavepoint ){
36416    int ii;            /* Iterator variable */
36417    int nNew;          /* Number of remaining savepoints after this op. */
36418
36419    /* Figure out how many savepoints will still be active after this
36420    ** operation. Store this value in nNew. Then free resources associated
36421    ** with any savepoints that are destroyed by this operation.
36422    */
36423    nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
36424    for(ii=nNew; ii<pPager->nSavepoint; ii++){
36425      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
36426    }
36427    pPager->nSavepoint = nNew;
36428
36429    /* If this is a release of the outermost savepoint, truncate
36430    ** the sub-journal to zero bytes in size. */
36431    if( op==SAVEPOINT_RELEASE ){
36432      if( nNew==0 && isOpen(pPager->sjfd) ){
36433        /* Only truncate if it is an in-memory sub-journal. */
36434        if( sqlite3IsMemJournal(pPager->sjfd) ){
36435          rc = sqlite3OsTruncate(pPager->sjfd, 0);
36436        }
36437        pPager->nSubRec = 0;
36438      }
36439    }
36440    /* Else this is a rollback operation, playback the specified savepoint.
36441    ** If this is a temp-file, it is possible that the journal file has
36442    ** not yet been opened. In this case there have been no changes to
36443    ** the database file, so the playback operation can be skipped.
36444    */
36445    else if( isOpen(pPager->jfd) ){
36446      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
36447      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
36448      assert(rc!=SQLITE_DONE);
36449    }
36450
36451  }
36452  return rc;
36453}
36454
36455/*
36456** Return the full pathname of the database file.
36457*/
36458SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
36459  return pPager->zFilename;
36460}
36461
36462/*
36463** Return the VFS structure for the pager.
36464*/
36465SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
36466  return pPager->pVfs;
36467}
36468
36469/*
36470** Return the file handle for the database file associated
36471** with the pager.  This might return NULL if the file has
36472** not yet been opened.
36473*/
36474SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
36475  return pPager->fd;
36476}
36477
36478/*
36479** Return the full pathname of the journal file.
36480*/
36481SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
36482  return pPager->zJournal;
36483}
36484
36485/*
36486** Return true if fsync() calls are disabled for this pager.  Return FALSE
36487** if fsync()s are executed normally.
36488*/
36489SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
36490  return pPager->noSync;
36491}
36492
36493#ifdef SQLITE_HAS_CODEC
36494/*
36495** Set or retrieve the codec for this pager
36496*/
36497static void sqlite3PagerSetCodec(
36498  Pager *pPager,
36499  void *(*xCodec)(void*,void*,Pgno,int),
36500  void (*xCodecSizeChng)(void*,int,int),
36501  void (*xCodecFree)(void*),
36502  void *pCodec
36503){
36504  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
36505  pPager->xCodec = pPager->memDb ? 0 : xCodec;
36506  pPager->xCodecSizeChng = xCodecSizeChng;
36507  pPager->xCodecFree = xCodecFree;
36508  pPager->pCodec = pCodec;
36509  pagerReportSize(pPager);
36510}
36511static void *sqlite3PagerGetCodec(Pager *pPager){
36512  return pPager->pCodec;
36513}
36514#endif
36515
36516#ifndef SQLITE_OMIT_AUTOVACUUM
36517/*
36518** Move the page pPg to location pgno in the file.
36519**
36520** There must be no references to the page previously located at
36521** pgno (which we call pPgOld) though that page is allowed to be
36522** in cache.  If the page previously located at pgno is not already
36523** in the rollback journal, it is not put there by by this routine.
36524**
36525** References to the page pPg remain valid. Updating any
36526** meta-data associated with pPg (i.e. data stored in the nExtra bytes
36527** allocated along with the page) is the responsibility of the caller.
36528**
36529** A transaction must be active when this routine is called. It used to be
36530** required that a statement transaction was not active, but this restriction
36531** has been removed (CREATE INDEX needs to move a page when a statement
36532** transaction is active).
36533**
36534** If the fourth argument, isCommit, is non-zero, then this page is being
36535** moved as part of a database reorganization just before the transaction
36536** is being committed. In this case, it is guaranteed that the database page
36537** pPg refers to will not be written to again within this transaction.
36538**
36539** This function may return SQLITE_NOMEM or an IO error code if an error
36540** occurs. Otherwise, it returns SQLITE_OK.
36541*/
36542SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
36543  PgHdr *pPgOld;               /* The page being overwritten. */
36544  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
36545  int rc;                      /* Return code */
36546  Pgno origPgno;               /* The original page number */
36547
36548  assert( pPg->nRef>0 );
36549
36550  /* In order to be able to rollback, an in-memory database must journal
36551  ** the page we are moving from.
36552  */
36553  if( MEMDB ){
36554    rc = sqlite3PagerWrite(pPg);
36555    if( rc ) return rc;
36556  }
36557
36558  /* If the page being moved is dirty and has not been saved by the latest
36559  ** savepoint, then save the current contents of the page into the
36560  ** sub-journal now. This is required to handle the following scenario:
36561  **
36562  **   BEGIN;
36563  **     <journal page X, then modify it in memory>
36564  **     SAVEPOINT one;
36565  **       <Move page X to location Y>
36566  **     ROLLBACK TO one;
36567  **
36568  ** If page X were not written to the sub-journal here, it would not
36569  ** be possible to restore its contents when the "ROLLBACK TO one"
36570  ** statement were is processed.
36571  **
36572  ** subjournalPage() may need to allocate space to store pPg->pgno into
36573  ** one or more savepoint bitvecs. This is the reason this function
36574  ** may return SQLITE_NOMEM.
36575  */
36576  if( pPg->flags&PGHDR_DIRTY
36577   && subjRequiresPage(pPg)
36578   && SQLITE_OK!=(rc = subjournalPage(pPg))
36579  ){
36580    return rc;
36581  }
36582
36583  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
36584      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
36585  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
36586
36587  /* If the journal needs to be sync()ed before page pPg->pgno can
36588  ** be written to, store pPg->pgno in local variable needSyncPgno.
36589  **
36590  ** If the isCommit flag is set, there is no need to remember that
36591  ** the journal needs to be sync()ed before database page pPg->pgno
36592  ** can be written to. The caller has already promised not to write to it.
36593  */
36594  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
36595    needSyncPgno = pPg->pgno;
36596    assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
36597    assert( pPg->flags&PGHDR_DIRTY );
36598    assert( pPager->needSync );
36599  }
36600
36601  /* If the cache contains a page with page-number pgno, remove it
36602  ** from its hash chain. Also, if the PgHdr.needSync was set for
36603  ** page pgno before the 'move' operation, it needs to be retained
36604  ** for the page moved there.
36605  */
36606  pPg->flags &= ~PGHDR_NEED_SYNC;
36607  pPgOld = pager_lookup(pPager, pgno);
36608  assert( !pPgOld || pPgOld->nRef==1 );
36609  if( pPgOld ){
36610    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
36611    if( MEMDB ){
36612      /* Do not discard pages from an in-memory database since we might
36613      ** need to rollback later.  Just move the page out of the way. */
36614      assert( pPager->dbSizeValid );
36615      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
36616    }else{
36617      sqlite3PcacheDrop(pPgOld);
36618    }
36619  }
36620
36621  origPgno = pPg->pgno;
36622  sqlite3PcacheMove(pPg, pgno);
36623  sqlite3PcacheMakeDirty(pPg);
36624  pPager->dbModified = 1;
36625
36626  if( needSyncPgno ){
36627    /* If needSyncPgno is non-zero, then the journal file needs to be
36628    ** sync()ed before any data is written to database file page needSyncPgno.
36629    ** Currently, no such page exists in the page-cache and the
36630    ** "is journaled" bitvec flag has been set. This needs to be remedied by
36631    ** loading the page into the pager-cache and setting the PgHdr.needSync
36632    ** flag.
36633    **
36634    ** If the attempt to load the page into the page-cache fails, (due
36635    ** to a malloc() or IO failure), clear the bit in the pInJournal[]
36636    ** array. Otherwise, if the page is loaded and written again in
36637    ** this transaction, it may be written to the database file before
36638    ** it is synced into the journal file. This way, it may end up in
36639    ** the journal file twice, but that is not a problem.
36640    **
36641    ** The sqlite3PagerGet() call may cause the journal to sync. So make
36642    ** sure the Pager.needSync flag is set too.
36643    */
36644    PgHdr *pPgHdr;
36645    assert( pPager->needSync );
36646    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
36647    if( rc!=SQLITE_OK ){
36648      if( needSyncPgno<=pPager->dbOrigSize ){
36649        assert( pPager->pTmpSpace!=0 );
36650        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
36651      }
36652      return rc;
36653    }
36654    pPager->needSync = 1;
36655    assert( pPager->noSync==0 && !MEMDB );
36656    pPgHdr->flags |= PGHDR_NEED_SYNC;
36657    sqlite3PcacheMakeDirty(pPgHdr);
36658    sqlite3PagerUnref(pPgHdr);
36659  }
36660
36661  /*
36662  ** For an in-memory database, make sure the original page continues
36663  ** to exist, in case the transaction needs to roll back.  Use pPgOld
36664  ** as the original page since it has already been allocated.
36665  */
36666  if( MEMDB ){
36667    sqlite3PcacheMove(pPgOld, origPgno);
36668    sqlite3PagerUnref(pPgOld);
36669  }
36670
36671  return SQLITE_OK;
36672}
36673#endif
36674
36675/*
36676** Return a pointer to the data for the specified page.
36677*/
36678SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
36679  assert( pPg->nRef>0 || pPg->pPager->memDb );
36680  return pPg->pData;
36681}
36682
36683/*
36684** Return a pointer to the Pager.nExtra bytes of "extra" space
36685** allocated along with the specified page.
36686*/
36687SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
36688  return pPg->pExtra;
36689}
36690
36691/*
36692** Get/set the locking-mode for this pager. Parameter eMode must be one
36693** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
36694** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
36695** the locking-mode is set to the value specified.
36696**
36697** The returned value is either PAGER_LOCKINGMODE_NORMAL or
36698** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
36699** locking-mode.
36700*/
36701SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
36702  assert( eMode==PAGER_LOCKINGMODE_QUERY
36703            || eMode==PAGER_LOCKINGMODE_NORMAL
36704            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
36705  assert( PAGER_LOCKINGMODE_QUERY<0 );
36706  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
36707  if( eMode>=0 && !pPager->tempFile ){
36708    pPager->exclusiveMode = (u8)eMode;
36709  }
36710  return (int)pPager->exclusiveMode;
36711}
36712
36713/*
36714** Get/set the journal-mode for this pager. Parameter eMode must be one of:
36715**
36716**    PAGER_JOURNALMODE_QUERY
36717**    PAGER_JOURNALMODE_DELETE
36718**    PAGER_JOURNALMODE_TRUNCATE
36719**    PAGER_JOURNALMODE_PERSIST
36720**    PAGER_JOURNALMODE_OFF
36721**    PAGER_JOURNALMODE_MEMORY
36722**
36723** If the parameter is not _QUERY, then the journal_mode is set to the
36724** value specified if the change is allowed.  The change is disallowed
36725** for the following reasons:
36726**
36727**   *  An in-memory database can only have its journal_mode set to _OFF
36728**      or _MEMORY.
36729**
36730**   *  The journal mode may not be changed while a transaction is active.
36731**
36732** The returned indicate the current (possibly updated) journal-mode.
36733*/
36734SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *pPager, int eMode){
36735  assert( eMode==PAGER_JOURNALMODE_QUERY
36736            || eMode==PAGER_JOURNALMODE_DELETE
36737            || eMode==PAGER_JOURNALMODE_TRUNCATE
36738            || eMode==PAGER_JOURNALMODE_PERSIST
36739            || eMode==PAGER_JOURNALMODE_OFF
36740            || eMode==PAGER_JOURNALMODE_MEMORY );
36741  assert( PAGER_JOURNALMODE_QUERY<0 );
36742  if( eMode>=0
36743   && (!MEMDB || eMode==PAGER_JOURNALMODE_MEMORY
36744              || eMode==PAGER_JOURNALMODE_OFF)
36745   && !pPager->dbModified
36746   && (!isOpen(pPager->jfd) || 0==pPager->journalOff)
36747  ){
36748    if( isOpen(pPager->jfd) ){
36749      sqlite3OsClose(pPager->jfd);
36750    }
36751    pPager->journalMode = (u8)eMode;
36752  }
36753  return (int)pPager->journalMode;
36754}
36755
36756/*
36757** Get/set the size-limit used for persistent journal files.
36758**
36759** Setting the size limit to -1 means no limit is enforced.
36760** An attempt to set a limit smaller than -1 is a no-op.
36761*/
36762SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
36763  if( iLimit>=-1 ){
36764    pPager->journalSizeLimit = iLimit;
36765  }
36766  return pPager->journalSizeLimit;
36767}
36768
36769/*
36770** Return a pointer to the pPager->pBackup variable. The backup module
36771** in backup.c maintains the content of this variable. This module
36772** uses it opaquely as an argument to sqlite3BackupRestart() and
36773** sqlite3BackupUpdate() only.
36774*/
36775SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
36776  return &pPager->pBackup;
36777}
36778
36779#endif /* SQLITE_OMIT_DISKIO */
36780
36781/************** End of pager.c ***********************************************/
36782/************** Begin file btmutex.c *****************************************/
36783/*
36784** 2007 August 27
36785**
36786** The author disclaims copyright to this source code.  In place of
36787** a legal notice, here is a blessing:
36788**
36789**    May you do good and not evil.
36790**    May you find forgiveness for yourself and forgive others.
36791**    May you share freely, never taking more than you give.
36792**
36793*************************************************************************
36794**
36795** This file contains code used to implement mutexes on Btree objects.
36796** This code really belongs in btree.c.  But btree.c is getting too
36797** big and we want to break it down some.  This packaged seemed like
36798** a good breakout.
36799*/
36800/************** Include btreeInt.h in the middle of btmutex.c ****************/
36801/************** Begin file btreeInt.h ****************************************/
36802/*
36803** 2004 April 6
36804**
36805** The author disclaims copyright to this source code.  In place of
36806** a legal notice, here is a blessing:
36807**
36808**    May you do good and not evil.
36809**    May you find forgiveness for yourself and forgive others.
36810**    May you share freely, never taking more than you give.
36811**
36812*************************************************************************
36813** This file implements a external (disk-based) database using BTrees.
36814** For a detailed discussion of BTrees, refer to
36815**
36816**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
36817**     "Sorting And Searching", pages 473-480. Addison-Wesley
36818**     Publishing Company, Reading, Massachusetts.
36819**
36820** The basic idea is that each page of the file contains N database
36821** entries and N+1 pointers to subpages.
36822**
36823**   ----------------------------------------------------------------
36824**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
36825**   ----------------------------------------------------------------
36826**
36827** All of the keys on the page that Ptr(0) points to have values less
36828** than Key(0).  All of the keys on page Ptr(1) and its subpages have
36829** values greater than Key(0) and less than Key(1).  All of the keys
36830** on Ptr(N) and its subpages have values greater than Key(N-1).  And
36831** so forth.
36832**
36833** Finding a particular key requires reading O(log(M)) pages from the
36834** disk where M is the number of entries in the tree.
36835**
36836** In this implementation, a single file can hold one or more separate
36837** BTrees.  Each BTree is identified by the index of its root page.  The
36838** key and data for any entry are combined to form the "payload".  A
36839** fixed amount of payload can be carried directly on the database
36840** page.  If the payload is larger than the preset amount then surplus
36841** bytes are stored on overflow pages.  The payload for an entry
36842** and the preceding pointer are combined to form a "Cell".  Each
36843** page has a small header which contains the Ptr(N) pointer and other
36844** information such as the size of key and data.
36845**
36846** FORMAT DETAILS
36847**
36848** The file is divided into pages.  The first page is called page 1,
36849** the second is page 2, and so forth.  A page number of zero indicates
36850** "no such page".  The page size can be any power of 2 between 512 and 32768.
36851** Each page can be either a btree page, a freelist page, an overflow
36852** page, or a pointer-map page.
36853**
36854** The first page is always a btree page.  The first 100 bytes of the first
36855** page contain a special header (the "file header") that describes the file.
36856** The format of the file header is as follows:
36857**
36858**   OFFSET   SIZE    DESCRIPTION
36859**      0      16     Header string: "SQLite format 3\000"
36860**     16       2     Page size in bytes.
36861**     18       1     File format write version
36862**     19       1     File format read version
36863**     20       1     Bytes of unused space at the end of each page
36864**     21       1     Max embedded payload fraction
36865**     22       1     Min embedded payload fraction
36866**     23       1     Min leaf payload fraction
36867**     24       4     File change counter
36868**     28       4     Reserved for future use
36869**     32       4     First freelist page
36870**     36       4     Number of freelist pages in the file
36871**     40      60     15 4-byte meta values passed to higher layers
36872**
36873**     40       4     Schema cookie
36874**     44       4     File format of schema layer
36875**     48       4     Size of page cache
36876**     52       4     Largest root-page (auto/incr_vacuum)
36877**     56       4     1=UTF-8 2=UTF16le 3=UTF16be
36878**     60       4     User version
36879**     64       4     Incremental vacuum mode
36880**     68       4     unused
36881**     72       4     unused
36882**     76       4     unused
36883**
36884** All of the integer values are big-endian (most significant byte first).
36885**
36886** The file change counter is incremented when the database is changed
36887** This counter allows other processes to know when the file has changed
36888** and thus when they need to flush their cache.
36889**
36890** The max embedded payload fraction is the amount of the total usable
36891** space in a page that can be consumed by a single cell for standard
36892** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
36893** is to limit the maximum cell size so that at least 4 cells will fit
36894** on one page.  Thus the default max embedded payload fraction is 64.
36895**
36896** If the payload for a cell is larger than the max payload, then extra
36897** payload is spilled to overflow pages.  Once an overflow page is allocated,
36898** as many bytes as possible are moved into the overflow pages without letting
36899** the cell size drop below the min embedded payload fraction.
36900**
36901** The min leaf payload fraction is like the min embedded payload fraction
36902** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
36903** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
36904** not specified in the header.
36905**
36906** Each btree pages is divided into three sections:  The header, the
36907** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
36908** file header that occurs before the page header.
36909**
36910**      |----------------|
36911**      | file header    |   100 bytes.  Page 1 only.
36912**      |----------------|
36913**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
36914**      |----------------|
36915**      | cell pointer   |   |  2 bytes per cell.  Sorted order.
36916**      | array          |   |  Grows downward
36917**      |                |   v
36918**      |----------------|
36919**      | unallocated    |
36920**      | space          |
36921**      |----------------|   ^  Grows upwards
36922**      | cell content   |   |  Arbitrary order interspersed with freeblocks.
36923**      | area           |   |  and free space fragments.
36924**      |----------------|
36925**
36926** The page headers looks like this:
36927**
36928**   OFFSET   SIZE     DESCRIPTION
36929**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
36930**      1       2      byte offset to the first freeblock
36931**      3       2      number of cells on this page
36932**      5       2      first byte of the cell content area
36933**      7       1      number of fragmented free bytes
36934**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
36935**
36936** The flags define the format of this btree page.  The leaf flag means that
36937** this page has no children.  The zerodata flag means that this page carries
36938** only keys and no data.  The intkey flag means that the key is a integer
36939** which is stored in the key size entry of the cell header rather than in
36940** the payload area.
36941**
36942** The cell pointer array begins on the first byte after the page header.
36943** The cell pointer array contains zero or more 2-byte numbers which are
36944** offsets from the beginning of the page to the cell content in the cell
36945** content area.  The cell pointers occur in sorted order.  The system strives
36946** to keep free space after the last cell pointer so that new cells can
36947** be easily added without having to defragment the page.
36948**
36949** Cell content is stored at the very end of the page and grows toward the
36950** beginning of the page.
36951**
36952** Unused space within the cell content area is collected into a linked list of
36953** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
36954** to the first freeblock is given in the header.  Freeblocks occur in
36955** increasing order.  Because a freeblock must be at least 4 bytes in size,
36956** any group of 3 or fewer unused bytes in the cell content area cannot
36957** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
36958** a fragment.  The total number of bytes in all fragments is recorded.
36959** in the page header at offset 7.
36960**
36961**    SIZE    DESCRIPTION
36962**      2     Byte offset of the next freeblock
36963**      2     Bytes in this freeblock
36964**
36965** Cells are of variable length.  Cells are stored in the cell content area at
36966** the end of the page.  Pointers to the cells are in the cell pointer array
36967** that immediately follows the page header.  Cells is not necessarily
36968** contiguous or in order, but cell pointers are contiguous and in order.
36969**
36970** Cell content makes use of variable length integers.  A variable
36971** length integer is 1 to 9 bytes where the lower 7 bits of each
36972** byte are used.  The integer consists of all bytes that have bit 8 set and
36973** the first byte with bit 8 clear.  The most significant byte of the integer
36974** appears first.  A variable-length integer may not be more than 9 bytes long.
36975** As a special case, all 8 bytes of the 9th byte are used as data.  This
36976** allows a 64-bit integer to be encoded in 9 bytes.
36977**
36978**    0x00                      becomes  0x00000000
36979**    0x7f                      becomes  0x0000007f
36980**    0x81 0x00                 becomes  0x00000080
36981**    0x82 0x00                 becomes  0x00000100
36982**    0x80 0x7f                 becomes  0x0000007f
36983**    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
36984**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
36985**
36986** Variable length integers are used for rowids and to hold the number of
36987** bytes of key and data in a btree cell.
36988**
36989** The content of a cell looks like this:
36990**
36991**    SIZE    DESCRIPTION
36992**      4     Page number of the left child. Omitted if leaf flag is set.
36993**     var    Number of bytes of data. Omitted if the zerodata flag is set.
36994**     var    Number of bytes of key. Or the key itself if intkey flag is set.
36995**      *     Payload
36996**      4     First page of the overflow chain.  Omitted if no overflow
36997**
36998** Overflow pages form a linked list.  Each page except the last is completely
36999** filled with data (pagesize - 4 bytes).  The last page can have as little
37000** as 1 byte of data.
37001**
37002**    SIZE    DESCRIPTION
37003**      4     Page number of next overflow page
37004**      *     Data
37005**
37006** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
37007** file header points to the first in a linked list of trunk page.  Each trunk
37008** page points to multiple leaf pages.  The content of a leaf page is
37009** unspecified.  A trunk page looks like this:
37010**
37011**    SIZE    DESCRIPTION
37012**      4     Page number of next trunk page
37013**      4     Number of leaf pointers on this page
37014**      *     zero or more pages numbers of leaves
37015*/
37016
37017
37018/* The following value is the maximum cell size assuming a maximum page
37019** size give above.
37020*/
37021#define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
37022
37023/* The maximum number of cells on a single page of the database.  This
37024** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
37025** plus 2 bytes for the index to the cell in the page header).  Such
37026** small cells will be rare, but they are possible.
37027*/
37028#define MX_CELL(pBt) ((pBt->pageSize-8)/6)
37029
37030/* Forward declarations */
37031typedef struct MemPage MemPage;
37032typedef struct BtLock BtLock;
37033
37034/*
37035** This is a magic string that appears at the beginning of every
37036** SQLite database in order to identify the file as a real database.
37037**
37038** You can change this value at compile-time by specifying a
37039** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
37040** header must be exactly 16 bytes including the zero-terminator so
37041** the string itself should be 15 characters long.  If you change
37042** the header, then your custom library will not be able to read
37043** databases generated by the standard tools and the standard tools
37044** will not be able to read databases created by your custom library.
37045*/
37046#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
37047#  define SQLITE_FILE_HEADER "SQLite format 3"
37048#endif
37049
37050/*
37051** Page type flags.  An ORed combination of these flags appear as the
37052** first byte of on-disk image of every BTree page.
37053*/
37054#define PTF_INTKEY    0x01
37055#define PTF_ZERODATA  0x02
37056#define PTF_LEAFDATA  0x04
37057#define PTF_LEAF      0x08
37058
37059/*
37060** As each page of the file is loaded into memory, an instance of the following
37061** structure is appended and initialized to zero.  This structure stores
37062** information about the page that is decoded from the raw file page.
37063**
37064** The pParent field points back to the parent page.  This allows us to
37065** walk up the BTree from any leaf to the root.  Care must be taken to
37066** unref() the parent page pointer when this page is no longer referenced.
37067** The pageDestructor() routine handles that chore.
37068**
37069** Access to all fields of this structure is controlled by the mutex
37070** stored in MemPage.pBt->mutex.
37071*/
37072struct MemPage {
37073  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
37074  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
37075  u8 intKey;           /* True if intkey flag is set */
37076  u8 leaf;             /* True if leaf flag is set */
37077  u8 hasData;          /* True if this page stores data */
37078  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
37079  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
37080  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
37081  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
37082  u16 cellOffset;      /* Index in aData of first cell pointer */
37083  u16 nFree;           /* Number of free bytes on the page */
37084  u16 nCell;           /* Number of cells on this page, local and ovfl */
37085  u16 maskPage;        /* Mask for page offset */
37086  struct _OvflCell {   /* Cells that will not fit on aData[] */
37087    u8 *pCell;          /* Pointers to the body of the overflow cell */
37088    u16 idx;            /* Insert this cell before idx-th non-overflow cell */
37089  } aOvfl[5];
37090  BtShared *pBt;       /* Pointer to BtShared that this page is part of */
37091  u8 *aData;           /* Pointer to disk image of the page data */
37092  DbPage *pDbPage;     /* Pager page handle */
37093  Pgno pgno;           /* Page number for this page */
37094};
37095
37096/*
37097** The in-memory image of a disk page has the auxiliary information appended
37098** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
37099** that extra information.
37100*/
37101#define EXTRA_SIZE sizeof(MemPage)
37102
37103/*
37104** A linked list of the following structures is stored at BtShared.pLock.
37105** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
37106** is opened on the table with root page BtShared.iTable. Locks are removed
37107** from this list when a transaction is committed or rolled back, or when
37108** a btree handle is closed.
37109*/
37110struct BtLock {
37111  Btree *pBtree;        /* Btree handle holding this lock */
37112  Pgno iTable;          /* Root page of table */
37113  u8 eLock;             /* READ_LOCK or WRITE_LOCK */
37114  BtLock *pNext;        /* Next in BtShared.pLock list */
37115};
37116
37117/* Candidate values for BtLock.eLock */
37118#define READ_LOCK     1
37119#define WRITE_LOCK    2
37120
37121/* A Btree handle
37122**
37123** A database connection contains a pointer to an instance of
37124** this object for every database file that it has open.  This structure
37125** is opaque to the database connection.  The database connection cannot
37126** see the internals of this structure and only deals with pointers to
37127** this structure.
37128**
37129** For some database files, the same underlying database cache might be
37130** shared between multiple connections.  In that case, each connection
37131** has it own instance of this object.  But each instance of this object
37132** points to the same BtShared object.  The database cache and the
37133** schema associated with the database file are all contained within
37134** the BtShared object.
37135**
37136** All fields in this structure are accessed under sqlite3.mutex.
37137** The pBt pointer itself may not be changed while there exists cursors
37138** in the referenced BtShared that point back to this Btree since those
37139** cursors have to do go through this Btree to find their BtShared and
37140** they often do so without holding sqlite3.mutex.
37141*/
37142struct Btree {
37143  sqlite3 *db;       /* The database connection holding this btree */
37144  BtShared *pBt;     /* Sharable content of this btree */
37145  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
37146  u8 sharable;       /* True if we can share pBt with another db */
37147  u8 locked;         /* True if db currently has pBt locked */
37148  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
37149  int nBackup;       /* Number of backup operations reading this btree */
37150  Btree *pNext;      /* List of other sharable Btrees from the same db */
37151  Btree *pPrev;      /* Back pointer of the same list */
37152#ifndef SQLITE_OMIT_SHARED_CACHE
37153  BtLock lock;       /* Object used to lock page 1 */
37154#endif
37155};
37156
37157/*
37158** Btree.inTrans may take one of the following values.
37159**
37160** If the shared-data extension is enabled, there may be multiple users
37161** of the Btree structure. At most one of these may open a write transaction,
37162** but any number may have active read transactions.
37163*/
37164#define TRANS_NONE  0
37165#define TRANS_READ  1
37166#define TRANS_WRITE 2
37167
37168/*
37169** An instance of this object represents a single database file.
37170**
37171** A single database file can be in use as the same time by two
37172** or more database connections.  When two or more connections are
37173** sharing the same database file, each connection has it own
37174** private Btree object for the file and each of those Btrees points
37175** to this one BtShared object.  BtShared.nRef is the number of
37176** connections currently sharing this database file.
37177**
37178** Fields in this structure are accessed under the BtShared.mutex
37179** mutex, except for nRef and pNext which are accessed under the
37180** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
37181** may not be modified once it is initially set as long as nRef>0.
37182** The pSchema field may be set once under BtShared.mutex and
37183** thereafter is unchanged as long as nRef>0.
37184**
37185** isPending:
37186**
37187**   If a BtShared client fails to obtain a write-lock on a database
37188**   table (because there exists one or more read-locks on the table),
37189**   the shared-cache enters 'pending-lock' state and isPending is
37190**   set to true.
37191**
37192**   The shared-cache leaves the 'pending lock' state when either of
37193**   the following occur:
37194**
37195**     1) The current writer (BtShared.pWriter) concludes its transaction, OR
37196**     2) The number of locks held by other connections drops to zero.
37197**
37198**   while in the 'pending-lock' state, no connection may start a new
37199**   transaction.
37200**
37201**   This feature is included to help prevent writer-starvation.
37202*/
37203struct BtShared {
37204  Pager *pPager;        /* The page cache */
37205  sqlite3 *db;          /* Database connection currently using this Btree */
37206  BtCursor *pCursor;    /* A list of all open cursors */
37207  MemPage *pPage1;      /* First page of the database */
37208  u8 readOnly;          /* True if the underlying file is readonly */
37209  u8 pageSizeFixed;     /* True if the page size can no longer be changed */
37210#ifndef SQLITE_OMIT_AUTOVACUUM
37211  u8 autoVacuum;        /* True if auto-vacuum is enabled */
37212  u8 incrVacuum;        /* True if incr-vacuum is enabled */
37213#endif
37214  u16 pageSize;         /* Total number of bytes on a page */
37215  u16 usableSize;       /* Number of usable bytes on each page */
37216  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
37217  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
37218  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
37219  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
37220  u8 inTransaction;     /* Transaction state */
37221  int nTransaction;     /* Number of open transactions (read + write) */
37222  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
37223  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
37224  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
37225  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
37226#ifndef SQLITE_OMIT_SHARED_CACHE
37227  int nRef;             /* Number of references to this structure */
37228  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
37229  BtLock *pLock;        /* List of locks held on this shared-btree struct */
37230  Btree *pWriter;       /* Btree with currently open write transaction */
37231  u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
37232  u8 isPending;         /* If waiting for read-locks to clear */
37233#endif
37234  u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
37235};
37236
37237/*
37238** An instance of the following structure is used to hold information
37239** about a cell.  The parseCellPtr() function fills in this structure
37240** based on information extract from the raw disk page.
37241*/
37242typedef struct CellInfo CellInfo;
37243struct CellInfo {
37244  u8 *pCell;     /* Pointer to the start of cell content */
37245  i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
37246  u32 nData;     /* Number of bytes of data */
37247  u32 nPayload;  /* Total amount of payload */
37248  u16 nHeader;   /* Size of the cell content header in bytes */
37249  u16 nLocal;    /* Amount of payload held locally */
37250  u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
37251  u16 nSize;     /* Size of the cell content on the main b-tree page */
37252};
37253
37254/*
37255** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
37256** this will be declared corrupt. This value is calculated based on a
37257** maximum database size of 2^31 pages a minimum fanout of 2 for a
37258** root-node and 3 for all other internal nodes.
37259**
37260** If a tree that appears to be taller than this is encountered, it is
37261** assumed that the database is corrupt.
37262*/
37263#define BTCURSOR_MAX_DEPTH 20
37264
37265/*
37266** A cursor is a pointer to a particular entry within a particular
37267** b-tree within a database file.
37268**
37269** The entry is identified by its MemPage and the index in
37270** MemPage.aCell[] of the entry.
37271**
37272** A single database file can shared by two more database connections,
37273** but cursors cannot be shared.  Each cursor is associated with a
37274** particular database connection identified BtCursor.pBtree.db.
37275**
37276** Fields in this structure are accessed under the BtShared.mutex
37277** found at self->pBt->mutex.
37278*/
37279struct BtCursor {
37280  Btree *pBtree;            /* The Btree to which this cursor belongs */
37281  BtShared *pBt;            /* The BtShared this cursor points to */
37282  BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
37283  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
37284  Pgno pgnoRoot;            /* The root page of this tree */
37285  sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
37286  CellInfo info;            /* A parse of the cell we are pointing at */
37287  u8 wrFlag;                /* True if writable */
37288  u8 atLast;                /* Cursor pointing to the last entry */
37289  u8 validNKey;             /* True if info.nKey is valid */
37290  u8 eState;                /* One of the CURSOR_XXX constants (see below) */
37291  void *pKey;      /* Saved key that was cursor's last known position */
37292  i64 nKey;        /* Size of pKey, or last integer key */
37293  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
37294#ifndef SQLITE_OMIT_INCRBLOB
37295  u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
37296  Pgno *aOverflow;          /* Cache of overflow page locations */
37297#endif
37298  i16 iPage;                            /* Index of current page in apPage */
37299  MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
37300  u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
37301};
37302
37303/*
37304** Potential values for BtCursor.eState.
37305**
37306** CURSOR_VALID:
37307**   Cursor points to a valid entry. getPayload() etc. may be called.
37308**
37309** CURSOR_INVALID:
37310**   Cursor does not point to a valid entry. This can happen (for example)
37311**   because the table is empty or because BtreeCursorFirst() has not been
37312**   called.
37313**
37314** CURSOR_REQUIRESEEK:
37315**   The table that this cursor was opened on still exists, but has been
37316**   modified since the cursor was last used. The cursor position is saved
37317**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
37318**   this state, restoreCursorPosition() can be called to attempt to
37319**   seek the cursor to the saved position.
37320**
37321** CURSOR_FAULT:
37322**   A unrecoverable error (an I/O error or a malloc failure) has occurred
37323**   on a different connection that shares the BtShared cache with this
37324**   cursor.  The error has left the cache in an inconsistent state.
37325**   Do nothing else with this cursor.  Any attempt to use the cursor
37326**   should return the error code stored in BtCursor.skip
37327*/
37328#define CURSOR_INVALID           0
37329#define CURSOR_VALID             1
37330#define CURSOR_REQUIRESEEK       2
37331#define CURSOR_FAULT             3
37332
37333/*
37334** The database page the PENDING_BYTE occupies. This page is never used.
37335*/
37336# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
37337
37338/*
37339** These macros define the location of the pointer-map entry for a
37340** database page. The first argument to each is the number of usable
37341** bytes on each page of the database (often 1024). The second is the
37342** page number to look up in the pointer map.
37343**
37344** PTRMAP_PAGENO returns the database page number of the pointer-map
37345** page that stores the required pointer. PTRMAP_PTROFFSET returns
37346** the offset of the requested map entry.
37347**
37348** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
37349** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
37350** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
37351** this test.
37352*/
37353#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
37354#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
37355#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
37356
37357/*
37358** The pointer map is a lookup table that identifies the parent page for
37359** each child page in the database file.  The parent page is the page that
37360** contains a pointer to the child.  Every page in the database contains
37361** 0 or 1 parent pages.  (In this context 'database page' refers
37362** to any page that is not part of the pointer map itself.)  Each pointer map
37363** entry consists of a single byte 'type' and a 4 byte parent page number.
37364** The PTRMAP_XXX identifiers below are the valid types.
37365**
37366** The purpose of the pointer map is to facility moving pages from one
37367** position in the file to another as part of autovacuum.  When a page
37368** is moved, the pointer in its parent must be updated to point to the
37369** new location.  The pointer map is used to locate the parent page quickly.
37370**
37371** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
37372**                  used in this case.
37373**
37374** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
37375**                  is not used in this case.
37376**
37377** PTRMAP_OVERFLOW1: The database page is the first page in a list of
37378**                   overflow pages. The page number identifies the page that
37379**                   contains the cell with a pointer to this overflow page.
37380**
37381** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
37382**                   overflow pages. The page-number identifies the previous
37383**                   page in the overflow page list.
37384**
37385** PTRMAP_BTREE: The database page is a non-root btree page. The page number
37386**               identifies the parent page in the btree.
37387*/
37388#define PTRMAP_ROOTPAGE 1
37389#define PTRMAP_FREEPAGE 2
37390#define PTRMAP_OVERFLOW1 3
37391#define PTRMAP_OVERFLOW2 4
37392#define PTRMAP_BTREE 5
37393
37394/* A bunch of assert() statements to check the transaction state variables
37395** of handle p (type Btree*) are internally consistent.
37396*/
37397#define btreeIntegrity(p) \
37398  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
37399  assert( p->pBt->inTransaction>=p->inTrans );
37400
37401
37402/*
37403** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
37404** if the database supports auto-vacuum or not. Because it is used
37405** within an expression that is an argument to another macro
37406** (sqliteMallocRaw), it is not possible to use conditional compilation.
37407** So, this macro is defined instead.
37408*/
37409#ifndef SQLITE_OMIT_AUTOVACUUM
37410#define ISAUTOVACUUM (pBt->autoVacuum)
37411#else
37412#define ISAUTOVACUUM 0
37413#endif
37414
37415
37416/*
37417** This structure is passed around through all the sanity checking routines
37418** in order to keep track of some global state information.
37419*/
37420typedef struct IntegrityCk IntegrityCk;
37421struct IntegrityCk {
37422  BtShared *pBt;    /* The tree being checked out */
37423  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
37424  Pgno nPage;       /* Number of pages in the database */
37425  int *anRef;       /* Number of times each page is referenced */
37426  int mxErr;        /* Stop accumulating errors when this reaches zero */
37427  int nErr;         /* Number of messages written to zErrMsg so far */
37428  int mallocFailed; /* A memory allocation error has occurred */
37429  StrAccum errMsg;  /* Accumulate the error message text here */
37430};
37431
37432/*
37433** Read or write a two- and four-byte big-endian integer values.
37434*/
37435#define get2byte(x)   ((x)[0]<<8 | (x)[1])
37436#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
37437#define get4byte sqlite3Get4byte
37438#define put4byte sqlite3Put4byte
37439
37440/************** End of btreeInt.h ********************************************/
37441/************** Continuing where we left off in btmutex.c ********************/
37442#ifndef SQLITE_OMIT_SHARED_CACHE
37443#if SQLITE_THREADSAFE
37444
37445/*
37446** Obtain the BtShared mutex associated with B-Tree handle p. Also,
37447** set BtShared.db to the database handle associated with p and the
37448** p->locked boolean to true.
37449*/
37450static void lockBtreeMutex(Btree *p){
37451  assert( p->locked==0 );
37452  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
37453  assert( sqlite3_mutex_held(p->db->mutex) );
37454
37455  sqlite3_mutex_enter(p->pBt->mutex);
37456  p->pBt->db = p->db;
37457  p->locked = 1;
37458}
37459
37460/*
37461** Release the BtShared mutex associated with B-Tree handle p and
37462** clear the p->locked boolean.
37463*/
37464static void unlockBtreeMutex(Btree *p){
37465  assert( p->locked==1 );
37466  assert( sqlite3_mutex_held(p->pBt->mutex) );
37467  assert( sqlite3_mutex_held(p->db->mutex) );
37468  assert( p->db==p->pBt->db );
37469
37470  sqlite3_mutex_leave(p->pBt->mutex);
37471  p->locked = 0;
37472}
37473
37474/*
37475** Enter a mutex on the given BTree object.
37476**
37477** If the object is not sharable, then no mutex is ever required
37478** and this routine is a no-op.  The underlying mutex is non-recursive.
37479** But we keep a reference count in Btree.wantToLock so the behavior
37480** of this interface is recursive.
37481**
37482** To avoid deadlocks, multiple Btrees are locked in the same order
37483** by all database connections.  The p->pNext is a list of other
37484** Btrees belonging to the same database connection as the p Btree
37485** which need to be locked after p.  If we cannot get a lock on
37486** p, then first unlock all of the others on p->pNext, then wait
37487** for the lock to become available on p, then relock all of the
37488** subsequent Btrees that desire a lock.
37489*/
37490SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
37491  Btree *pLater;
37492
37493  /* Some basic sanity checking on the Btree.  The list of Btrees
37494  ** connected by pNext and pPrev should be in sorted order by
37495  ** Btree.pBt value. All elements of the list should belong to
37496  ** the same connection. Only shared Btrees are on the list. */
37497  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
37498  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
37499  assert( p->pNext==0 || p->pNext->db==p->db );
37500  assert( p->pPrev==0 || p->pPrev->db==p->db );
37501  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
37502
37503  /* Check for locking consistency */
37504  assert( !p->locked || p->wantToLock>0 );
37505  assert( p->sharable || p->wantToLock==0 );
37506
37507  /* We should already hold a lock on the database connection */
37508  assert( sqlite3_mutex_held(p->db->mutex) );
37509
37510  /* Unless the database is sharable and unlocked, then BtShared.db
37511  ** should already be set correctly. */
37512  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
37513
37514  if( !p->sharable ) return;
37515  p->wantToLock++;
37516  if( p->locked ) return;
37517
37518  /* In most cases, we should be able to acquire the lock we
37519  ** want without having to go throught the ascending lock
37520  ** procedure that follows.  Just be sure not to block.
37521  */
37522  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
37523    p->pBt->db = p->db;
37524    p->locked = 1;
37525    return;
37526  }
37527
37528  /* To avoid deadlock, first release all locks with a larger
37529  ** BtShared address.  Then acquire our lock.  Then reacquire
37530  ** the other BtShared locks that we used to hold in ascending
37531  ** order.
37532  */
37533  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
37534    assert( pLater->sharable );
37535    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
37536    assert( !pLater->locked || pLater->wantToLock>0 );
37537    if( pLater->locked ){
37538      unlockBtreeMutex(pLater);
37539    }
37540  }
37541  lockBtreeMutex(p);
37542  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
37543    if( pLater->wantToLock ){
37544      lockBtreeMutex(pLater);
37545    }
37546  }
37547}
37548
37549/*
37550** Exit the recursive mutex on a Btree.
37551*/
37552SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
37553  if( p->sharable ){
37554    assert( p->wantToLock>0 );
37555    p->wantToLock--;
37556    if( p->wantToLock==0 ){
37557      unlockBtreeMutex(p);
37558    }
37559  }
37560}
37561
37562#ifndef NDEBUG
37563/*
37564** Return true if the BtShared mutex is held on the btree, or if the
37565** B-Tree is not marked as sharable.
37566**
37567** This routine is used only from within assert() statements.
37568*/
37569SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
37570  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
37571  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
37572  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
37573  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
37574
37575  return (p->sharable==0 || p->locked);
37576}
37577#endif
37578
37579
37580#ifndef SQLITE_OMIT_INCRBLOB
37581/*
37582** Enter and leave a mutex on a Btree given a cursor owned by that
37583** Btree.  These entry points are used by incremental I/O and can be
37584** omitted if that module is not used.
37585*/
37586SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
37587  sqlite3BtreeEnter(pCur->pBtree);
37588}
37589SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
37590  sqlite3BtreeLeave(pCur->pBtree);
37591}
37592#endif /* SQLITE_OMIT_INCRBLOB */
37593
37594
37595/*
37596** Enter the mutex on every Btree associated with a database
37597** connection.  This is needed (for example) prior to parsing
37598** a statement since we will be comparing table and column names
37599** against all schemas and we do not want those schemas being
37600** reset out from under us.
37601**
37602** There is a corresponding leave-all procedures.
37603**
37604** Enter the mutexes in accending order by BtShared pointer address
37605** to avoid the possibility of deadlock when two threads with
37606** two or more btrees in common both try to lock all their btrees
37607** at the same instant.
37608*/
37609SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
37610  int i;
37611  Btree *p, *pLater;
37612  assert( sqlite3_mutex_held(db->mutex) );
37613  for(i=0; i<db->nDb; i++){
37614    p = db->aDb[i].pBt;
37615    assert( !p || (p->locked==0 && p->sharable) || p->pBt->db==p->db );
37616    if( p && p->sharable ){
37617      p->wantToLock++;
37618      if( !p->locked ){
37619        assert( p->wantToLock==1 );
37620        while( p->pPrev ) p = p->pPrev;
37621        /* Reason for ALWAYS:  There must be at least on unlocked Btree in
37622        ** the chain.  Otherwise the !p->locked test above would have failed */
37623        while( p->locked && ALWAYS(p->pNext) ) p = p->pNext;
37624        for(pLater = p->pNext; pLater; pLater=pLater->pNext){
37625          if( pLater->locked ){
37626            unlockBtreeMutex(pLater);
37627          }
37628        }
37629        while( p ){
37630          lockBtreeMutex(p);
37631          p = p->pNext;
37632        }
37633      }
37634    }
37635  }
37636}
37637SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
37638  int i;
37639  Btree *p;
37640  assert( sqlite3_mutex_held(db->mutex) );
37641  for(i=0; i<db->nDb; i++){
37642    p = db->aDb[i].pBt;
37643    if( p && p->sharable ){
37644      assert( p->wantToLock>0 );
37645      p->wantToLock--;
37646      if( p->wantToLock==0 ){
37647        unlockBtreeMutex(p);
37648      }
37649    }
37650  }
37651}
37652
37653#ifndef NDEBUG
37654/*
37655** Return true if the current thread holds the database connection
37656** mutex and all required BtShared mutexes.
37657**
37658** This routine is used inside assert() statements only.
37659*/
37660SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
37661  int i;
37662  if( !sqlite3_mutex_held(db->mutex) ){
37663    return 0;
37664  }
37665  for(i=0; i<db->nDb; i++){
37666    Btree *p;
37667    p = db->aDb[i].pBt;
37668    if( p && p->sharable &&
37669         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
37670      return 0;
37671    }
37672  }
37673  return 1;
37674}
37675#endif /* NDEBUG */
37676
37677/*
37678** Add a new Btree pointer to a BtreeMutexArray.
37679** if the pointer can possibly be shared with
37680** another database connection.
37681**
37682** The pointers are kept in sorted order by pBtree->pBt.  That
37683** way when we go to enter all the mutexes, we can enter them
37684** in order without every having to backup and retry and without
37685** worrying about deadlock.
37686**
37687** The number of shared btrees will always be small (usually 0 or 1)
37688** so an insertion sort is an adequate algorithm here.
37689*/
37690SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
37691  int i, j;
37692  BtShared *pBt;
37693  if( pBtree==0 || pBtree->sharable==0 ) return;
37694#ifndef NDEBUG
37695  {
37696    for(i=0; i<pArray->nMutex; i++){
37697      assert( pArray->aBtree[i]!=pBtree );
37698    }
37699  }
37700#endif
37701  assert( pArray->nMutex>=0 );
37702  assert( pArray->nMutex<ArraySize(pArray->aBtree)-1 );
37703  pBt = pBtree->pBt;
37704  for(i=0; i<pArray->nMutex; i++){
37705    assert( pArray->aBtree[i]!=pBtree );
37706    if( pArray->aBtree[i]->pBt>pBt ){
37707      for(j=pArray->nMutex; j>i; j--){
37708        pArray->aBtree[j] = pArray->aBtree[j-1];
37709      }
37710      pArray->aBtree[i] = pBtree;
37711      pArray->nMutex++;
37712      return;
37713    }
37714  }
37715  pArray->aBtree[pArray->nMutex++] = pBtree;
37716}
37717
37718/*
37719** Enter the mutex of every btree in the array.  This routine is
37720** called at the beginning of sqlite3VdbeExec().  The mutexes are
37721** exited at the end of the same function.
37722*/
37723SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
37724  int i;
37725  for(i=0; i<pArray->nMutex; i++){
37726    Btree *p = pArray->aBtree[i];
37727    /* Some basic sanity checking */
37728    assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
37729    assert( !p->locked || p->wantToLock>0 );
37730
37731    /* We should already hold a lock on the database connection */
37732    assert( sqlite3_mutex_held(p->db->mutex) );
37733
37734    /* The Btree is sharable because only sharable Btrees are entered
37735    ** into the array in the first place. */
37736    assert( p->sharable );
37737
37738    p->wantToLock++;
37739    if( !p->locked ){
37740      lockBtreeMutex(p);
37741    }
37742  }
37743}
37744
37745/*
37746** Leave the mutex of every btree in the group.
37747*/
37748SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
37749  int i;
37750  for(i=0; i<pArray->nMutex; i++){
37751    Btree *p = pArray->aBtree[i];
37752    /* Some basic sanity checking */
37753    assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
37754    assert( p->locked );
37755    assert( p->wantToLock>0 );
37756
37757    /* We should already hold a lock on the database connection */
37758    assert( sqlite3_mutex_held(p->db->mutex) );
37759
37760    p->wantToLock--;
37761    if( p->wantToLock==0 ){
37762      unlockBtreeMutex(p);
37763    }
37764  }
37765}
37766
37767#else
37768SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
37769  p->pBt->db = p->db;
37770}
37771SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
37772  int i;
37773  for(i=0; i<db->nDb; i++){
37774    Btree *p = db->aDb[i].pBt;
37775    if( p ){
37776      p->pBt->db = p->db;
37777    }
37778  }
37779}
37780#endif /* if SQLITE_THREADSAFE */
37781#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
37782
37783/************** End of btmutex.c *********************************************/
37784/************** Begin file btree.c *******************************************/
37785/*
37786** 2004 April 6
37787**
37788** The author disclaims copyright to this source code.  In place of
37789** a legal notice, here is a blessing:
37790**
37791**    May you do good and not evil.
37792**    May you find forgiveness for yourself and forgive others.
37793**    May you share freely, never taking more than you give.
37794**
37795*************************************************************************
37796** This file implements a external (disk-based) database using BTrees.
37797** See the header comment on "btreeInt.h" for additional information.
37798** Including a description of file format and an overview of operation.
37799*/
37800
37801/*
37802** The header string that appears at the beginning of every
37803** SQLite database.
37804*/
37805static const char zMagicHeader[] = SQLITE_FILE_HEADER;
37806
37807/*
37808** Set this global variable to 1 to enable tracing using the TRACE
37809** macro.
37810*/
37811#if 0
37812int sqlite3BtreeTrace=1;  /* True to enable tracing */
37813# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
37814#else
37815# define TRACE(X)
37816#endif
37817
37818
37819
37820#ifndef SQLITE_OMIT_SHARED_CACHE
37821/*
37822** A list of BtShared objects that are eligible for participation
37823** in shared cache.  This variable has file scope during normal builds,
37824** but the test harness needs to access it so we make it global for
37825** test builds.
37826**
37827** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
37828*/
37829#ifdef SQLITE_TEST
37830SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
37831#else
37832static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
37833#endif
37834#endif /* SQLITE_OMIT_SHARED_CACHE */
37835
37836#ifndef SQLITE_OMIT_SHARED_CACHE
37837/*
37838** Enable or disable the shared pager and schema features.
37839**
37840** This routine has no effect on existing database connections.
37841** The shared cache setting effects only future calls to
37842** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
37843*/
37844SQLITE_API int sqlite3_enable_shared_cache(int enable){
37845  sqlite3GlobalConfig.sharedCacheEnabled = enable;
37846  return SQLITE_OK;
37847}
37848#endif
37849
37850
37851
37852#ifdef SQLITE_OMIT_SHARED_CACHE
37853  /*
37854  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
37855  ** and clearAllSharedCacheTableLocks()
37856  ** manipulate entries in the BtShared.pLock linked list used to store
37857  ** shared-cache table level locks. If the library is compiled with the
37858  ** shared-cache feature disabled, then there is only ever one user
37859  ** of each BtShared structure and so this locking is not necessary.
37860  ** So define the lock related functions as no-ops.
37861  */
37862  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
37863  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
37864  #define clearAllSharedCacheTableLocks(a)
37865  #define downgradeAllSharedCacheTableLocks(a)
37866  #define hasSharedCacheTableLock(a,b,c,d) 1
37867  #define hasReadConflicts(a, b) 0
37868#endif
37869
37870#ifndef SQLITE_OMIT_SHARED_CACHE
37871
37872#ifdef SQLITE_DEBUG
37873/*
37874**** This function is only used as part of an assert() statement. ***
37875**
37876** Check to see if pBtree holds the required locks to read or write to the
37877** table with root page iRoot.   Return 1 if it does and 0 if not.
37878**
37879** For example, when writing to a table with root-page iRoot via
37880** Btree connection pBtree:
37881**
37882**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
37883**
37884** When writing to an index that resides in a sharable database, the
37885** caller should have first obtained a lock specifying the root page of
37886** the corresponding table. This makes things a bit more complicated,
37887** as this module treats each table as a separate structure. To determine
37888** the table corresponding to the index being written, this
37889** function has to search through the database schema.
37890**
37891** Instead of a lock on the table/index rooted at page iRoot, the caller may
37892** hold a write-lock on the schema table (root page 1). This is also
37893** acceptable.
37894*/
37895static int hasSharedCacheTableLock(
37896  Btree *pBtree,         /* Handle that must hold lock */
37897  Pgno iRoot,            /* Root page of b-tree */
37898  int isIndex,           /* True if iRoot is the root of an index b-tree */
37899  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
37900){
37901  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
37902  Pgno iTab = 0;
37903  BtLock *pLock;
37904
37905  /* If this database is not shareable, or if the client is reading
37906  ** and has the read-uncommitted flag set, then no lock is required.
37907  ** Return true immediately.
37908  */
37909  if( (pBtree->sharable==0)
37910   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
37911  ){
37912    return 1;
37913  }
37914
37915  /* If the client is reading  or writing an index and the schema is
37916  ** not loaded, then it is too difficult to actually check to see if
37917  ** the correct locks are held.  So do not bother - just return true.
37918  ** This case does not come up very often anyhow.
37919  */
37920  if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
37921    return 1;
37922  }
37923
37924  /* Figure out the root-page that the lock should be held on. For table
37925  ** b-trees, this is just the root page of the b-tree being read or
37926  ** written. For index b-trees, it is the root page of the associated
37927  ** table.  */
37928  if( isIndex ){
37929    HashElem *p;
37930    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
37931      Index *pIdx = (Index *)sqliteHashData(p);
37932      if( pIdx->tnum==(int)iRoot ){
37933        iTab = pIdx->pTable->tnum;
37934      }
37935    }
37936  }else{
37937    iTab = iRoot;
37938  }
37939
37940  /* Search for the required lock. Either a write-lock on root-page iTab, a
37941  ** write-lock on the schema table, or (if the client is reading) a
37942  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
37943  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
37944    if( pLock->pBtree==pBtree
37945     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
37946     && pLock->eLock>=eLockType
37947    ){
37948      return 1;
37949    }
37950  }
37951
37952  /* Failed to find the required lock. */
37953  return 0;
37954}
37955#endif /* SQLITE_DEBUG */
37956
37957#ifdef SQLITE_DEBUG
37958/*
37959**** This function may be used as part of assert() statements only. ****
37960**
37961** Return true if it would be illegal for pBtree to write into the
37962** table or index rooted at iRoot because other shared connections are
37963** simultaneously reading that same table or index.
37964**
37965** It is illegal for pBtree to write if some other Btree object that
37966** shares the same BtShared object is currently reading or writing
37967** the iRoot table.  Except, if the other Btree object has the
37968** read-uncommitted flag set, then it is OK for the other object to
37969** have a read cursor.
37970**
37971** For example, before writing to any part of the table or index
37972** rooted at page iRoot, one should call:
37973**
37974**    assert( !hasReadConflicts(pBtree, iRoot) );
37975*/
37976static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
37977  BtCursor *p;
37978  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
37979    if( p->pgnoRoot==iRoot
37980     && p->pBtree!=pBtree
37981     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
37982    ){
37983      return 1;
37984    }
37985  }
37986  return 0;
37987}
37988#endif    /* #ifdef SQLITE_DEBUG */
37989
37990/*
37991** Query to see if Btree handle p may obtain a lock of type eLock
37992** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
37993** SQLITE_OK if the lock may be obtained (by calling
37994** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
37995*/
37996static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
37997  BtShared *pBt = p->pBt;
37998  BtLock *pIter;
37999
38000  assert( sqlite3BtreeHoldsMutex(p) );
38001  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
38002  assert( p->db!=0 );
38003  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
38004
38005  /* If requesting a write-lock, then the Btree must have an open write
38006  ** transaction on this file. And, obviously, for this to be so there
38007  ** must be an open write transaction on the file itself.
38008  */
38009  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
38010  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
38011
38012  /* This routine is a no-op if the shared-cache is not enabled */
38013  if( !p->sharable ){
38014    return SQLITE_OK;
38015  }
38016
38017  /* If some other connection is holding an exclusive lock, the
38018  ** requested lock may not be obtained.
38019  */
38020  if( pBt->pWriter!=p && pBt->isExclusive ){
38021    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
38022    return SQLITE_LOCKED_SHAREDCACHE;
38023  }
38024
38025  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
38026    /* The condition (pIter->eLock!=eLock) in the following if(...)
38027    ** statement is a simplification of:
38028    **
38029    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
38030    **
38031    ** since we know that if eLock==WRITE_LOCK, then no other connection
38032    ** may hold a WRITE_LOCK on any table in this file (since there can
38033    ** only be a single writer).
38034    */
38035    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
38036    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
38037    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
38038      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
38039      if( eLock==WRITE_LOCK ){
38040        assert( p==pBt->pWriter );
38041        pBt->isPending = 1;
38042      }
38043      return SQLITE_LOCKED_SHAREDCACHE;
38044    }
38045  }
38046  return SQLITE_OK;
38047}
38048#endif /* !SQLITE_OMIT_SHARED_CACHE */
38049
38050#ifndef SQLITE_OMIT_SHARED_CACHE
38051/*
38052** Add a lock on the table with root-page iTable to the shared-btree used
38053** by Btree handle p. Parameter eLock must be either READ_LOCK or
38054** WRITE_LOCK.
38055**
38056** This function assumes the following:
38057**
38058**   (a) The specified Btree object p is connected to a sharable
38059**       database (one with the BtShared.sharable flag set), and
38060**
38061**   (b) No other Btree objects hold a lock that conflicts
38062**       with the requested lock (i.e. querySharedCacheTableLock() has
38063**       already been called and returned SQLITE_OK).
38064**
38065** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
38066** is returned if a malloc attempt fails.
38067*/
38068static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
38069  BtShared *pBt = p->pBt;
38070  BtLock *pLock = 0;
38071  BtLock *pIter;
38072
38073  assert( sqlite3BtreeHoldsMutex(p) );
38074  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
38075  assert( p->db!=0 );
38076
38077  /* A connection with the read-uncommitted flag set will never try to
38078  ** obtain a read-lock using this function. The only read-lock obtained
38079  ** by a connection in read-uncommitted mode is on the sqlite_master
38080  ** table, and that lock is obtained in BtreeBeginTrans().  */
38081  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
38082
38083  /* This function should only be called on a sharable b-tree after it
38084  ** has been determined that no other b-tree holds a conflicting lock.  */
38085  assert( p->sharable );
38086  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
38087
38088  /* First search the list for an existing lock on this table. */
38089  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
38090    if( pIter->iTable==iTable && pIter->pBtree==p ){
38091      pLock = pIter;
38092      break;
38093    }
38094  }
38095
38096  /* If the above search did not find a BtLock struct associating Btree p
38097  ** with table iTable, allocate one and link it into the list.
38098  */
38099  if( !pLock ){
38100    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
38101    if( !pLock ){
38102      return SQLITE_NOMEM;
38103    }
38104    pLock->iTable = iTable;
38105    pLock->pBtree = p;
38106    pLock->pNext = pBt->pLock;
38107    pBt->pLock = pLock;
38108  }
38109
38110  /* Set the BtLock.eLock variable to the maximum of the current lock
38111  ** and the requested lock. This means if a write-lock was already held
38112  ** and a read-lock requested, we don't incorrectly downgrade the lock.
38113  */
38114  assert( WRITE_LOCK>READ_LOCK );
38115  if( eLock>pLock->eLock ){
38116    pLock->eLock = eLock;
38117  }
38118
38119  return SQLITE_OK;
38120}
38121#endif /* !SQLITE_OMIT_SHARED_CACHE */
38122
38123#ifndef SQLITE_OMIT_SHARED_CACHE
38124/*
38125** Release all the table locks (locks obtained via calls to
38126** the setSharedCacheTableLock() procedure) held by Btree object p.
38127**
38128** This function assumes that Btree p has an open read or write
38129** transaction. If it does not, then the BtShared.isPending variable
38130** may be incorrectly cleared.
38131*/
38132static void clearAllSharedCacheTableLocks(Btree *p){
38133  BtShared *pBt = p->pBt;
38134  BtLock **ppIter = &pBt->pLock;
38135
38136  assert( sqlite3BtreeHoldsMutex(p) );
38137  assert( p->sharable || 0==*ppIter );
38138  assert( p->inTrans>0 );
38139
38140  while( *ppIter ){
38141    BtLock *pLock = *ppIter;
38142    assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
38143    assert( pLock->pBtree->inTrans>=pLock->eLock );
38144    if( pLock->pBtree==p ){
38145      *ppIter = pLock->pNext;
38146      assert( pLock->iTable!=1 || pLock==&p->lock );
38147      if( pLock->iTable!=1 ){
38148        sqlite3_free(pLock);
38149      }
38150    }else{
38151      ppIter = &pLock->pNext;
38152    }
38153  }
38154
38155  assert( pBt->isPending==0 || pBt->pWriter );
38156  if( pBt->pWriter==p ){
38157    pBt->pWriter = 0;
38158    pBt->isExclusive = 0;
38159    pBt->isPending = 0;
38160  }else if( pBt->nTransaction==2 ){
38161    /* This function is called when Btree p is concluding its
38162    ** transaction. If there currently exists a writer, and p is not
38163    ** that writer, then the number of locks held by connections other
38164    ** than the writer must be about to drop to zero. In this case
38165    ** set the isPending flag to 0.
38166    **
38167    ** If there is not currently a writer, then BtShared.isPending must
38168    ** be zero already. So this next line is harmless in that case.
38169    */
38170    pBt->isPending = 0;
38171  }
38172}
38173
38174/*
38175** This function changes all write-locks held by Btree p into read-locks.
38176*/
38177static void downgradeAllSharedCacheTableLocks(Btree *p){
38178  BtShared *pBt = p->pBt;
38179  if( pBt->pWriter==p ){
38180    BtLock *pLock;
38181    pBt->pWriter = 0;
38182    pBt->isExclusive = 0;
38183    pBt->isPending = 0;
38184    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
38185      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
38186      pLock->eLock = READ_LOCK;
38187    }
38188  }
38189}
38190
38191#endif /* SQLITE_OMIT_SHARED_CACHE */
38192
38193static void releasePage(MemPage *pPage);  /* Forward reference */
38194
38195/*
38196***** This routine is used inside of assert() only ****
38197**
38198** Verify that the cursor holds the mutex on its BtShared
38199*/
38200#ifdef SQLITE_DEBUG
38201static int cursorHoldsMutex(BtCursor *p){
38202  return sqlite3_mutex_held(p->pBt->mutex);
38203}
38204#endif
38205
38206
38207#ifndef SQLITE_OMIT_INCRBLOB
38208/*
38209** Invalidate the overflow page-list cache for cursor pCur, if any.
38210*/
38211static void invalidateOverflowCache(BtCursor *pCur){
38212  assert( cursorHoldsMutex(pCur) );
38213  sqlite3_free(pCur->aOverflow);
38214  pCur->aOverflow = 0;
38215}
38216
38217/*
38218** Invalidate the overflow page-list cache for all cursors opened
38219** on the shared btree structure pBt.
38220*/
38221static void invalidateAllOverflowCache(BtShared *pBt){
38222  BtCursor *p;
38223  assert( sqlite3_mutex_held(pBt->mutex) );
38224  for(p=pBt->pCursor; p; p=p->pNext){
38225    invalidateOverflowCache(p);
38226  }
38227}
38228
38229/*
38230** This function is called before modifying the contents of a table
38231** to invalidate any incrblob cursors that are open on the
38232** row or one of the rows being modified.
38233**
38234** If argument isClearTable is true, then the entire contents of the
38235** table is about to be deleted. In this case invalidate all incrblob
38236** cursors open on any row within the table with root-page pgnoRoot.
38237**
38238** Otherwise, if argument isClearTable is false, then the row with
38239** rowid iRow is being replaced or deleted. In this case invalidate
38240** only those incrblob cursors open on that specific row.
38241*/
38242static void invalidateIncrblobCursors(
38243  Btree *pBtree,          /* The database file to check */
38244  i64 iRow,               /* The rowid that might be changing */
38245  int isClearTable        /* True if all rows are being deleted */
38246){
38247  BtCursor *p;
38248  BtShared *pBt = pBtree->pBt;
38249  assert( sqlite3BtreeHoldsMutex(pBtree) );
38250  for(p=pBt->pCursor; p; p=p->pNext){
38251    if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
38252      p->eState = CURSOR_INVALID;
38253    }
38254  }
38255}
38256
38257#else
38258  /* Stub functions when INCRBLOB is omitted */
38259  #define invalidateOverflowCache(x)
38260  #define invalidateAllOverflowCache(x)
38261  #define invalidateIncrblobCursors(x,y,z)
38262#endif /* SQLITE_OMIT_INCRBLOB */
38263
38264/*
38265** Set bit pgno of the BtShared.pHasContent bitvec. This is called
38266** when a page that previously contained data becomes a free-list leaf
38267** page.
38268**
38269** The BtShared.pHasContent bitvec exists to work around an obscure
38270** bug caused by the interaction of two useful IO optimizations surrounding
38271** free-list leaf pages:
38272**
38273**   1) When all data is deleted from a page and the page becomes
38274**      a free-list leaf page, the page is not written to the database
38275**      (as free-list leaf pages contain no meaningful data). Sometimes
38276**      such a page is not even journalled (as it will not be modified,
38277**      why bother journalling it?).
38278**
38279**   2) When a free-list leaf page is reused, its content is not read
38280**      from the database or written to the journal file (why should it
38281**      be, if it is not at all meaningful?).
38282**
38283** By themselves, these optimizations work fine and provide a handy
38284** performance boost to bulk delete or insert operations. However, if
38285** a page is moved to the free-list and then reused within the same
38286** transaction, a problem comes up. If the page is not journalled when
38287** it is moved to the free-list and it is also not journalled when it
38288** is extracted from the free-list and reused, then the original data
38289** may be lost. In the event of a rollback, it may not be possible
38290** to restore the database to its original configuration.
38291**
38292** The solution is the BtShared.pHasContent bitvec. Whenever a page is
38293** moved to become a free-list leaf page, the corresponding bit is
38294** set in the bitvec. Whenever a leaf page is extracted from the free-list,
38295** optimization 2 above is omitted if the corresponding bit is already
38296** set in BtShared.pHasContent. The contents of the bitvec are cleared
38297** at the end of every transaction.
38298*/
38299static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
38300  int rc = SQLITE_OK;
38301  if( !pBt->pHasContent ){
38302    int nPage = 100;
38303    sqlite3PagerPagecount(pBt->pPager, &nPage);
38304    /* If sqlite3PagerPagecount() fails there is no harm because the
38305    ** nPage variable is unchanged from its default value of 100 */
38306    pBt->pHasContent = sqlite3BitvecCreate((u32)nPage);
38307    if( !pBt->pHasContent ){
38308      rc = SQLITE_NOMEM;
38309    }
38310  }
38311  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
38312    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
38313  }
38314  return rc;
38315}
38316
38317/*
38318** Query the BtShared.pHasContent vector.
38319**
38320** This function is called when a free-list leaf page is removed from the
38321** free-list for reuse. It returns false if it is safe to retrieve the
38322** page from the pager layer with the 'no-content' flag set. True otherwise.
38323*/
38324static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
38325  Bitvec *p = pBt->pHasContent;
38326  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
38327}
38328
38329/*
38330** Clear (destroy) the BtShared.pHasContent bitvec. This should be
38331** invoked at the conclusion of each write-transaction.
38332*/
38333static void btreeClearHasContent(BtShared *pBt){
38334  sqlite3BitvecDestroy(pBt->pHasContent);
38335  pBt->pHasContent = 0;
38336}
38337
38338/*
38339** Save the current cursor position in the variables BtCursor.nKey
38340** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
38341**
38342** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
38343** prior to calling this routine.
38344*/
38345static int saveCursorPosition(BtCursor *pCur){
38346  int rc;
38347
38348  assert( CURSOR_VALID==pCur->eState );
38349  assert( 0==pCur->pKey );
38350  assert( cursorHoldsMutex(pCur) );
38351
38352  rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
38353  assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
38354
38355  /* If this is an intKey table, then the above call to BtreeKeySize()
38356  ** stores the integer key in pCur->nKey. In this case this value is
38357  ** all that is required. Otherwise, if pCur is not open on an intKey
38358  ** table, then malloc space for and store the pCur->nKey bytes of key
38359  ** data.
38360  */
38361  if( 0==pCur->apPage[0]->intKey ){
38362    void *pKey = sqlite3Malloc( (int)pCur->nKey );
38363    if( pKey ){
38364      rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
38365      if( rc==SQLITE_OK ){
38366        pCur->pKey = pKey;
38367      }else{
38368        sqlite3_free(pKey);
38369      }
38370    }else{
38371      rc = SQLITE_NOMEM;
38372    }
38373  }
38374  assert( !pCur->apPage[0]->intKey || !pCur->pKey );
38375
38376  if( rc==SQLITE_OK ){
38377    int i;
38378    for(i=0; i<=pCur->iPage; i++){
38379      releasePage(pCur->apPage[i]);
38380      pCur->apPage[i] = 0;
38381    }
38382    pCur->iPage = -1;
38383    pCur->eState = CURSOR_REQUIRESEEK;
38384  }
38385
38386  invalidateOverflowCache(pCur);
38387  return rc;
38388}
38389
38390/*
38391** Save the positions of all cursors (except pExcept) that are open on
38392** the table  with root-page iRoot. Usually, this is called just before cursor
38393** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
38394*/
38395static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
38396  BtCursor *p;
38397  assert( sqlite3_mutex_held(pBt->mutex) );
38398  assert( pExcept==0 || pExcept->pBt==pBt );
38399  for(p=pBt->pCursor; p; p=p->pNext){
38400    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
38401        p->eState==CURSOR_VALID ){
38402      int rc = saveCursorPosition(p);
38403      if( SQLITE_OK!=rc ){
38404        return rc;
38405      }
38406    }
38407  }
38408  return SQLITE_OK;
38409}
38410
38411/*
38412** Clear the current cursor position.
38413*/
38414SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
38415  assert( cursorHoldsMutex(pCur) );
38416  sqlite3_free(pCur->pKey);
38417  pCur->pKey = 0;
38418  pCur->eState = CURSOR_INVALID;
38419}
38420
38421/*
38422** In this version of BtreeMoveto, pKey is a packed index record
38423** such as is generated by the OP_MakeRecord opcode.  Unpack the
38424** record and then call BtreeMovetoUnpacked() to do the work.
38425*/
38426static int btreeMoveto(
38427  BtCursor *pCur,     /* Cursor open on the btree to be searched */
38428  const void *pKey,   /* Packed key if the btree is an index */
38429  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
38430  int bias,           /* Bias search to the high end */
38431  int *pRes           /* Write search results here */
38432){
38433  int rc;                    /* Status code */
38434  UnpackedRecord *pIdxKey;   /* Unpacked index key */
38435  char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
38436
38437  if( pKey ){
38438    assert( nKey==(i64)(int)nKey );
38439    pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
38440                                      aSpace, sizeof(aSpace));
38441    if( pIdxKey==0 ) return SQLITE_NOMEM;
38442  }else{
38443    pIdxKey = 0;
38444  }
38445  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
38446  if( pKey ){
38447    sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
38448  }
38449  return rc;
38450}
38451
38452/*
38453** Restore the cursor to the position it was in (or as close to as possible)
38454** when saveCursorPosition() was called. Note that this call deletes the
38455** saved position info stored by saveCursorPosition(), so there can be
38456** at most one effective restoreCursorPosition() call after each
38457** saveCursorPosition().
38458*/
38459static int btreeRestoreCursorPosition(BtCursor *pCur){
38460  int rc;
38461  assert( cursorHoldsMutex(pCur) );
38462  assert( pCur->eState>=CURSOR_REQUIRESEEK );
38463  if( pCur->eState==CURSOR_FAULT ){
38464    return pCur->skipNext;
38465  }
38466  pCur->eState = CURSOR_INVALID;
38467  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
38468  if( rc==SQLITE_OK ){
38469    sqlite3_free(pCur->pKey);
38470    pCur->pKey = 0;
38471    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
38472  }
38473  return rc;
38474}
38475
38476#define restoreCursorPosition(p) \
38477  (p->eState>=CURSOR_REQUIRESEEK ? \
38478         btreeRestoreCursorPosition(p) : \
38479         SQLITE_OK)
38480
38481/*
38482** Determine whether or not a cursor has moved from the position it
38483** was last placed at.  Cursors can move when the row they are pointing
38484** at is deleted out from under them.
38485**
38486** This routine returns an error code if something goes wrong.  The
38487** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
38488*/
38489SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
38490  int rc;
38491
38492  rc = restoreCursorPosition(pCur);
38493  if( rc ){
38494    *pHasMoved = 1;
38495    return rc;
38496  }
38497  if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
38498    *pHasMoved = 1;
38499  }else{
38500    *pHasMoved = 0;
38501  }
38502  return SQLITE_OK;
38503}
38504
38505#ifndef SQLITE_OMIT_AUTOVACUUM
38506/*
38507** Given a page number of a regular database page, return the page
38508** number for the pointer-map page that contains the entry for the
38509** input page number.
38510*/
38511static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
38512  int nPagesPerMapPage;
38513  Pgno iPtrMap, ret;
38514  assert( sqlite3_mutex_held(pBt->mutex) );
38515  nPagesPerMapPage = (pBt->usableSize/5)+1;
38516  iPtrMap = (pgno-2)/nPagesPerMapPage;
38517  ret = (iPtrMap*nPagesPerMapPage) + 2;
38518  if( ret==PENDING_BYTE_PAGE(pBt) ){
38519    ret++;
38520  }
38521  return ret;
38522}
38523
38524/*
38525** Write an entry into the pointer map.
38526**
38527** This routine updates the pointer map entry for page number 'key'
38528** so that it maps to type 'eType' and parent page number 'pgno'.
38529**
38530** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
38531** a no-op.  If an error occurs, the appropriate error code is written
38532** into *pRC.
38533*/
38534static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
38535  DbPage *pDbPage;  /* The pointer map page */
38536  u8 *pPtrmap;      /* The pointer map data */
38537  Pgno iPtrmap;     /* The pointer map page number */
38538  int offset;       /* Offset in pointer map page */
38539  int rc;           /* Return code from subfunctions */
38540
38541  if( *pRC ) return;
38542
38543  assert( sqlite3_mutex_held(pBt->mutex) );
38544  /* The master-journal page number must never be used as a pointer map page */
38545  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
38546
38547  assert( pBt->autoVacuum );
38548  if( key==0 ){
38549    *pRC = SQLITE_CORRUPT_BKPT;
38550    return;
38551  }
38552  iPtrmap = PTRMAP_PAGENO(pBt, key);
38553  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
38554  if( rc!=SQLITE_OK ){
38555    *pRC = rc;
38556    return;
38557  }
38558  offset = PTRMAP_PTROFFSET(iPtrmap, key);
38559  if( offset<0 ){
38560    *pRC = SQLITE_CORRUPT_BKPT;
38561    goto ptrmap_exit;
38562  }
38563  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
38564
38565  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
38566    TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
38567    *pRC= rc = sqlite3PagerWrite(pDbPage);
38568    if( rc==SQLITE_OK ){
38569      pPtrmap[offset] = eType;
38570      put4byte(&pPtrmap[offset+1], parent);
38571    }
38572  }
38573
38574ptrmap_exit:
38575  sqlite3PagerUnref(pDbPage);
38576}
38577
38578/*
38579** Read an entry from the pointer map.
38580**
38581** This routine retrieves the pointer map entry for page 'key', writing
38582** the type and parent page number to *pEType and *pPgno respectively.
38583** An error code is returned if something goes wrong, otherwise SQLITE_OK.
38584*/
38585static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
38586  DbPage *pDbPage;   /* The pointer map page */
38587  int iPtrmap;       /* Pointer map page index */
38588  u8 *pPtrmap;       /* Pointer map page data */
38589  int offset;        /* Offset of entry in pointer map */
38590  int rc;
38591
38592  assert( sqlite3_mutex_held(pBt->mutex) );
38593
38594  iPtrmap = PTRMAP_PAGENO(pBt, key);
38595  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
38596  if( rc!=0 ){
38597    return rc;
38598  }
38599  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
38600
38601  offset = PTRMAP_PTROFFSET(iPtrmap, key);
38602  assert( pEType!=0 );
38603  *pEType = pPtrmap[offset];
38604  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
38605
38606  sqlite3PagerUnref(pDbPage);
38607  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
38608  return SQLITE_OK;
38609}
38610
38611#else /* if defined SQLITE_OMIT_AUTOVACUUM */
38612  #define ptrmapPut(w,x,y,z,rc)
38613  #define ptrmapGet(w,x,y,z) SQLITE_OK
38614  #define ptrmapPutOvflPtr(x, y, rc)
38615#endif
38616
38617/*
38618** Given a btree page and a cell index (0 means the first cell on
38619** the page, 1 means the second cell, and so forth) return a pointer
38620** to the cell content.
38621**
38622** This routine works only for pages that do not contain overflow cells.
38623*/
38624#define findCell(P,I) \
38625  ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
38626
38627/*
38628** This a more complex version of findCell() that works for
38629** pages that do contain overflow cells.
38630*/
38631static u8 *findOverflowCell(MemPage *pPage, int iCell){
38632  int i;
38633  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38634  for(i=pPage->nOverflow-1; i>=0; i--){
38635    int k;
38636    struct _OvflCell *pOvfl;
38637    pOvfl = &pPage->aOvfl[i];
38638    k = pOvfl->idx;
38639    if( k<=iCell ){
38640      if( k==iCell ){
38641        return pOvfl->pCell;
38642      }
38643      iCell--;
38644    }
38645  }
38646  return findCell(pPage, iCell);
38647}
38648
38649/*
38650** Parse a cell content block and fill in the CellInfo structure.  There
38651** are two versions of this function.  btreeParseCell() takes a
38652** cell index as the second argument and btreeParseCellPtr()
38653** takes a pointer to the body of the cell as its second argument.
38654**
38655** Within this file, the parseCell() macro can be called instead of
38656** btreeParseCellPtr(). Using some compilers, this will be faster.
38657*/
38658static void btreeParseCellPtr(
38659  MemPage *pPage,         /* Page containing the cell */
38660  u8 *pCell,              /* Pointer to the cell text. */
38661  CellInfo *pInfo         /* Fill in this structure */
38662){
38663  u16 n;                  /* Number bytes in cell content header */
38664  u32 nPayload;           /* Number of bytes of cell payload */
38665
38666  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38667
38668  pInfo->pCell = pCell;
38669  assert( pPage->leaf==0 || pPage->leaf==1 );
38670  n = pPage->childPtrSize;
38671  assert( n==4-4*pPage->leaf );
38672  if( pPage->intKey ){
38673    if( pPage->hasData ){
38674      n += getVarint32(&pCell[n], nPayload);
38675    }else{
38676      nPayload = 0;
38677    }
38678    n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
38679    pInfo->nData = nPayload;
38680  }else{
38681    pInfo->nData = 0;
38682    n += getVarint32(&pCell[n], nPayload);
38683    pInfo->nKey = nPayload;
38684  }
38685  pInfo->nPayload = nPayload;
38686  pInfo->nHeader = n;
38687  testcase( nPayload==pPage->maxLocal );
38688  testcase( nPayload==pPage->maxLocal+1 );
38689  if( likely(nPayload<=pPage->maxLocal) ){
38690    /* This is the (easy) common case where the entire payload fits
38691    ** on the local page.  No overflow is required.
38692    */
38693    int nSize;          /* Total size of cell content in bytes */
38694    nSize = nPayload + n;
38695    pInfo->nLocal = (u16)nPayload;
38696    pInfo->iOverflow = 0;
38697    if( (nSize & ~3)==0 ){
38698      nSize = 4;        /* Minimum cell size is 4 */
38699    }
38700    pInfo->nSize = (u16)nSize;
38701  }else{
38702    /* If the payload will not fit completely on the local page, we have
38703    ** to decide how much to store locally and how much to spill onto
38704    ** overflow pages.  The strategy is to minimize the amount of unused
38705    ** space on overflow pages while keeping the amount of local storage
38706    ** in between minLocal and maxLocal.
38707    **
38708    ** Warning:  changing the way overflow payload is distributed in any
38709    ** way will result in an incompatible file format.
38710    */
38711    int minLocal;  /* Minimum amount of payload held locally */
38712    int maxLocal;  /* Maximum amount of payload held locally */
38713    int surplus;   /* Overflow payload available for local storage */
38714
38715    minLocal = pPage->minLocal;
38716    maxLocal = pPage->maxLocal;
38717    surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
38718    testcase( surplus==maxLocal );
38719    testcase( surplus==maxLocal+1 );
38720    if( surplus <= maxLocal ){
38721      pInfo->nLocal = (u16)surplus;
38722    }else{
38723      pInfo->nLocal = (u16)minLocal;
38724    }
38725    pInfo->iOverflow = (u16)(pInfo->nLocal + n);
38726    pInfo->nSize = pInfo->iOverflow + 4;
38727  }
38728}
38729#define parseCell(pPage, iCell, pInfo) \
38730  btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
38731static void btreeParseCell(
38732  MemPage *pPage,         /* Page containing the cell */
38733  int iCell,              /* The cell index.  First cell is 0 */
38734  CellInfo *pInfo         /* Fill in this structure */
38735){
38736  parseCell(pPage, iCell, pInfo);
38737}
38738
38739/*
38740** Compute the total number of bytes that a Cell needs in the cell
38741** data area of the btree-page.  The return number includes the cell
38742** data header and the local payload, but not any overflow page or
38743** the space used by the cell pointer.
38744*/
38745static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
38746  u8 *pIter = &pCell[pPage->childPtrSize];
38747  u32 nSize;
38748
38749#ifdef SQLITE_DEBUG
38750  /* The value returned by this function should always be the same as
38751  ** the (CellInfo.nSize) value found by doing a full parse of the
38752  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
38753  ** this function verifies that this invariant is not violated. */
38754  CellInfo debuginfo;
38755  btreeParseCellPtr(pPage, pCell, &debuginfo);
38756#endif
38757
38758  if( pPage->intKey ){
38759    u8 *pEnd;
38760    if( pPage->hasData ){
38761      pIter += getVarint32(pIter, nSize);
38762    }else{
38763      nSize = 0;
38764    }
38765
38766    /* pIter now points at the 64-bit integer key value, a variable length
38767    ** integer. The following block moves pIter to point at the first byte
38768    ** past the end of the key value. */
38769    pEnd = &pIter[9];
38770    while( (*pIter++)&0x80 && pIter<pEnd );
38771  }else{
38772    pIter += getVarint32(pIter, nSize);
38773  }
38774
38775  testcase( nSize==pPage->maxLocal );
38776  testcase( nSize==pPage->maxLocal+1 );
38777  if( nSize>pPage->maxLocal ){
38778    int minLocal = pPage->minLocal;
38779    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
38780    testcase( nSize==pPage->maxLocal );
38781    testcase( nSize==pPage->maxLocal+1 );
38782    if( nSize>pPage->maxLocal ){
38783      nSize = minLocal;
38784    }
38785    nSize += 4;
38786  }
38787  nSize += (u32)(pIter - pCell);
38788
38789  /* The minimum size of any cell is 4 bytes. */
38790  if( nSize<4 ){
38791    nSize = 4;
38792  }
38793
38794  assert( nSize==debuginfo.nSize );
38795  return (u16)nSize;
38796}
38797
38798#ifdef SQLITE_DEBUG
38799/* This variation on cellSizePtr() is used inside of assert() statements
38800** only. */
38801static u16 cellSize(MemPage *pPage, int iCell){
38802  return cellSizePtr(pPage, findCell(pPage, iCell));
38803}
38804#endif
38805
38806#ifndef SQLITE_OMIT_AUTOVACUUM
38807/*
38808** If the cell pCell, part of page pPage contains a pointer
38809** to an overflow page, insert an entry into the pointer-map
38810** for the overflow page.
38811*/
38812static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
38813  CellInfo info;
38814  if( *pRC ) return;
38815  assert( pCell!=0 );
38816  btreeParseCellPtr(pPage, pCell, &info);
38817  assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
38818  if( info.iOverflow ){
38819    Pgno ovfl = get4byte(&pCell[info.iOverflow]);
38820    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
38821  }
38822}
38823#endif
38824
38825
38826/*
38827** Defragment the page given.  All Cells are moved to the
38828** end of the page and all free space is collected into one
38829** big FreeBlk that occurs in between the header and cell
38830** pointer array and the cell content area.
38831*/
38832static int defragmentPage(MemPage *pPage){
38833  int i;                     /* Loop counter */
38834  int pc;                    /* Address of a i-th cell */
38835  int hdr;                   /* Offset to the page header */
38836  int size;                  /* Size of a cell */
38837  int usableSize;            /* Number of usable bytes on a page */
38838  int cellOffset;            /* Offset to the cell pointer array */
38839  int cbrk;                  /* Offset to the cell content area */
38840  int nCell;                 /* Number of cells on the page */
38841  unsigned char *data;       /* The page data */
38842  unsigned char *temp;       /* Temp area for cell content */
38843  int iCellFirst;            /* First allowable cell index */
38844  int iCellLast;             /* Last possible cell index */
38845
38846
38847  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38848  assert( pPage->pBt!=0 );
38849  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
38850  assert( pPage->nOverflow==0 );
38851  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38852  temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
38853  data = pPage->aData;
38854  hdr = pPage->hdrOffset;
38855  cellOffset = pPage->cellOffset;
38856  nCell = pPage->nCell;
38857  assert( nCell==get2byte(&data[hdr+3]) );
38858  usableSize = pPage->pBt->usableSize;
38859  cbrk = get2byte(&data[hdr+5]);
38860  memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
38861  cbrk = usableSize;
38862  iCellFirst = cellOffset + 2*nCell;
38863  iCellLast = usableSize - 4;
38864  for(i=0; i<nCell; i++){
38865    u8 *pAddr;     /* The i-th cell pointer */
38866    pAddr = &data[cellOffset + i*2];
38867    pc = get2byte(pAddr);
38868    testcase( pc==iCellFirst );
38869    testcase( pc==iCellLast );
38870#if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
38871    /* These conditions have already been verified in btreeInitPage()
38872    ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
38873    */
38874    if( pc<iCellFirst || pc>iCellLast ){
38875      return SQLITE_CORRUPT_BKPT;
38876    }
38877#endif
38878    assert( pc>=iCellFirst && pc<=iCellLast );
38879    size = cellSizePtr(pPage, &temp[pc]);
38880    cbrk -= size;
38881#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
38882    if( cbrk<iCellFirst ){
38883      return SQLITE_CORRUPT_BKPT;
38884    }
38885#else
38886    if( cbrk<iCellFirst || pc+size>usableSize ){
38887      return SQLITE_CORRUPT_BKPT;
38888    }
38889#endif
38890    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
38891    testcase( cbrk+size==usableSize );
38892    testcase( pc+size==usableSize );
38893    memcpy(&data[cbrk], &temp[pc], size);
38894    put2byte(pAddr, cbrk);
38895  }
38896  assert( cbrk>=iCellFirst );
38897  put2byte(&data[hdr+5], cbrk);
38898  data[hdr+1] = 0;
38899  data[hdr+2] = 0;
38900  data[hdr+7] = 0;
38901  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
38902  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38903  if( cbrk-iCellFirst!=pPage->nFree ){
38904    return SQLITE_CORRUPT_BKPT;
38905  }
38906  return SQLITE_OK;
38907}
38908
38909/*
38910** Allocate nByte bytes of space from within the B-Tree page passed
38911** as the first argument. Write into *pIdx the index into pPage->aData[]
38912** of the first byte of allocated space. Return either SQLITE_OK or
38913** an error code (usually SQLITE_CORRUPT).
38914**
38915** The caller guarantees that there is sufficient space to make the
38916** allocation.  This routine might need to defragment in order to bring
38917** all the space together, however.  This routine will avoid using
38918** the first two bytes past the cell pointer area since presumably this
38919** allocation is being made in order to insert a new cell, so we will
38920** also end up needing a new cell pointer.
38921*/
38922static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
38923  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
38924  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
38925  int nFrag;                           /* Number of fragmented bytes on pPage */
38926  int top;                             /* First byte of cell content area */
38927  int gap;        /* First byte of gap between cell pointers and cell content */
38928  int rc;         /* Integer return code */
38929  int usableSize; /* Usable size of the page */
38930
38931  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38932  assert( pPage->pBt );
38933  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38934  assert( nByte>=0 );  /* Minimum cell size is 4 */
38935  assert( pPage->nFree>=nByte );
38936  assert( pPage->nOverflow==0 );
38937  usableSize = pPage->pBt->usableSize;
38938  assert( nByte < usableSize-8 );
38939
38940  nFrag = data[hdr+7];
38941  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
38942  gap = pPage->cellOffset + 2*pPage->nCell;
38943  top = get2byte(&data[hdr+5]);
38944  if( gap>top ) return SQLITE_CORRUPT_BKPT;
38945  testcase( gap+2==top );
38946  testcase( gap+1==top );
38947  testcase( gap==top );
38948
38949  if( nFrag>=60 ){
38950    /* Always defragment highly fragmented pages */
38951    rc = defragmentPage(pPage);
38952    if( rc ) return rc;
38953    top = get2byte(&data[hdr+5]);
38954  }else if( gap+2<=top ){
38955    /* Search the freelist looking for a free slot big enough to satisfy
38956    ** the request. The allocation is made from the first free slot in
38957    ** the list that is large enough to accomadate it.
38958    */
38959    int pc, addr;
38960    for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
38961      int size;            /* Size of the free slot */
38962      if( pc>usableSize-4 || pc<addr+4 ){
38963        return SQLITE_CORRUPT_BKPT;
38964      }
38965      size = get2byte(&data[pc+2]);
38966      if( size>=nByte ){
38967        int x = size - nByte;
38968        testcase( x==4 );
38969        testcase( x==3 );
38970        if( x<4 ){
38971          /* Remove the slot from the free-list. Update the number of
38972          ** fragmented bytes within the page. */
38973          memcpy(&data[addr], &data[pc], 2);
38974          data[hdr+7] = (u8)(nFrag + x);
38975        }else if( size+pc > usableSize ){
38976          return SQLITE_CORRUPT_BKPT;
38977        }else{
38978          /* The slot remains on the free-list. Reduce its size to account
38979          ** for the portion used by the new allocation. */
38980          put2byte(&data[pc+2], x);
38981        }
38982        *pIdx = pc + x;
38983        return SQLITE_OK;
38984      }
38985    }
38986  }
38987
38988  /* Check to make sure there is enough space in the gap to satisfy
38989  ** the allocation.  If not, defragment.
38990  */
38991  testcase( gap+2+nByte==top );
38992  if( gap+2+nByte>top ){
38993    rc = defragmentPage(pPage);
38994    if( rc ) return rc;
38995    top = get2byte(&data[hdr+5]);
38996    assert( gap+nByte<=top );
38997  }
38998
38999
39000  /* Allocate memory from the gap in between the cell pointer array
39001  ** and the cell content area.  The btreeInitPage() call has already
39002  ** validated the freelist.  Given that the freelist is valid, there
39003  ** is no way that the allocation can extend off the end of the page.
39004  ** The assert() below verifies the previous sentence.
39005  */
39006  top -= nByte;
39007  put2byte(&data[hdr+5], top);
39008  assert( top+nByte <= pPage->pBt->usableSize );
39009  *pIdx = top;
39010  return SQLITE_OK;
39011}
39012
39013/*
39014** Return a section of the pPage->aData to the freelist.
39015** The first byte of the new free block is pPage->aDisk[start]
39016** and the size of the block is "size" bytes.
39017**
39018** Most of the effort here is involved in coalesing adjacent
39019** free blocks into a single big free block.
39020*/
39021static int freeSpace(MemPage *pPage, int start, int size){
39022  int addr, pbegin, hdr;
39023  int iLast;                        /* Largest possible freeblock offset */
39024  unsigned char *data = pPage->aData;
39025
39026  assert( pPage->pBt!=0 );
39027  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
39028  assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
39029  assert( (start + size)<=pPage->pBt->usableSize );
39030  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39031  assert( size>=0 );   /* Minimum cell size is 4 */
39032
39033#ifdef SQLITE_SECURE_DELETE
39034  /* Overwrite deleted information with zeros when the SECURE_DELETE
39035  ** option is enabled at compile-time */
39036  memset(&data[start], 0, size);
39037#endif
39038
39039  /* Add the space back into the linked list of freeblocks.  Note that
39040  ** even though the freeblock list was checked by btreeInitPage(),
39041  ** btreeInitPage() did not detect overlapping cells or
39042  ** freeblocks that overlapped cells.   Nor does it detect when the
39043  ** cell content area exceeds the value in the page header.  If these
39044  ** situations arise, then subsequent insert operations might corrupt
39045  ** the freelist.  So we do need to check for corruption while scanning
39046  ** the freelist.
39047  */
39048  hdr = pPage->hdrOffset;
39049  addr = hdr + 1;
39050  iLast = pPage->pBt->usableSize - 4;
39051  assert( start<=iLast );
39052  while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
39053    if( pbegin<addr+4 ){
39054      return SQLITE_CORRUPT_BKPT;
39055    }
39056    addr = pbegin;
39057  }
39058  if( pbegin>iLast ){
39059    return SQLITE_CORRUPT_BKPT;
39060  }
39061  assert( pbegin>addr || pbegin==0 );
39062  put2byte(&data[addr], start);
39063  put2byte(&data[start], pbegin);
39064  put2byte(&data[start+2], size);
39065  pPage->nFree = pPage->nFree + (u16)size;
39066
39067  /* Coalesce adjacent free blocks */
39068  addr = hdr + 1;
39069  while( (pbegin = get2byte(&data[addr]))>0 ){
39070    int pnext, psize, x;
39071    assert( pbegin>addr );
39072    assert( pbegin<=pPage->pBt->usableSize-4 );
39073    pnext = get2byte(&data[pbegin]);
39074    psize = get2byte(&data[pbegin+2]);
39075    if( pbegin + psize + 3 >= pnext && pnext>0 ){
39076      int frag = pnext - (pbegin+psize);
39077      if( (frag<0) || (frag>(int)data[hdr+7]) ){
39078        return SQLITE_CORRUPT_BKPT;
39079      }
39080      data[hdr+7] -= (u8)frag;
39081      x = get2byte(&data[pnext]);
39082      put2byte(&data[pbegin], x);
39083      x = pnext + get2byte(&data[pnext+2]) - pbegin;
39084      put2byte(&data[pbegin+2], x);
39085    }else{
39086      addr = pbegin;
39087    }
39088  }
39089
39090  /* If the cell content area begins with a freeblock, remove it. */
39091  if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
39092    int top;
39093    pbegin = get2byte(&data[hdr+1]);
39094    memcpy(&data[hdr+1], &data[pbegin], 2);
39095    top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
39096    put2byte(&data[hdr+5], top);
39097  }
39098  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
39099  return SQLITE_OK;
39100}
39101
39102/*
39103** Decode the flags byte (the first byte of the header) for a page
39104** and initialize fields of the MemPage structure accordingly.
39105**
39106** Only the following combinations are supported.  Anything different
39107** indicates a corrupt database files:
39108**
39109**         PTF_ZERODATA
39110**         PTF_ZERODATA | PTF_LEAF
39111**         PTF_LEAFDATA | PTF_INTKEY
39112**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
39113*/
39114static int decodeFlags(MemPage *pPage, int flagByte){
39115  BtShared *pBt;     /* A copy of pPage->pBt */
39116
39117  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
39118  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39119  pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
39120  flagByte &= ~PTF_LEAF;
39121  pPage->childPtrSize = 4-4*pPage->leaf;
39122  pBt = pPage->pBt;
39123  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
39124    pPage->intKey = 1;
39125    pPage->hasData = pPage->leaf;
39126    pPage->maxLocal = pBt->maxLeaf;
39127    pPage->minLocal = pBt->minLeaf;
39128  }else if( flagByte==PTF_ZERODATA ){
39129    pPage->intKey = 0;
39130    pPage->hasData = 0;
39131    pPage->maxLocal = pBt->maxLocal;
39132    pPage->minLocal = pBt->minLocal;
39133  }else{
39134    return SQLITE_CORRUPT_BKPT;
39135  }
39136  return SQLITE_OK;
39137}
39138
39139/*
39140** Initialize the auxiliary information for a disk block.
39141**
39142** Return SQLITE_OK on success.  If we see that the page does
39143** not contain a well-formed database page, then return
39144** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
39145** guarantee that the page is well-formed.  It only shows that
39146** we failed to detect any corruption.
39147*/
39148static int btreeInitPage(MemPage *pPage){
39149
39150  assert( pPage->pBt!=0 );
39151  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39152  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
39153  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
39154  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
39155
39156  if( !pPage->isInit ){
39157    u16 pc;            /* Address of a freeblock within pPage->aData[] */
39158    u8 hdr;            /* Offset to beginning of page header */
39159    u8 *data;          /* Equal to pPage->aData */
39160    BtShared *pBt;        /* The main btree structure */
39161    u16 usableSize;    /* Amount of usable space on each page */
39162    u16 cellOffset;    /* Offset from start of page to first cell pointer */
39163    u16 nFree;         /* Number of unused bytes on the page */
39164    u16 top;           /* First byte of the cell content area */
39165    int iCellFirst;    /* First allowable cell or freeblock offset */
39166    int iCellLast;     /* Last possible cell or freeblock offset */
39167
39168    pBt = pPage->pBt;
39169
39170    hdr = pPage->hdrOffset;
39171    data = pPage->aData;
39172    if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
39173    assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
39174    pPage->maskPage = pBt->pageSize - 1;
39175    pPage->nOverflow = 0;
39176    usableSize = pBt->usableSize;
39177    pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
39178    top = get2byte(&data[hdr+5]);
39179    pPage->nCell = get2byte(&data[hdr+3]);
39180    if( pPage->nCell>MX_CELL(pBt) ){
39181      /* To many cells for a single page.  The page must be corrupt */
39182      return SQLITE_CORRUPT_BKPT;
39183    }
39184    testcase( pPage->nCell==MX_CELL(pBt) );
39185
39186    /* A malformed database page might cause us to read past the end
39187    ** of page when parsing a cell.
39188    **
39189    ** The following block of code checks early to see if a cell extends
39190    ** past the end of a page boundary and causes SQLITE_CORRUPT to be
39191    ** returned if it does.
39192    */
39193    iCellFirst = cellOffset + 2*pPage->nCell;
39194    iCellLast = usableSize - 4;
39195#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
39196    {
39197      int i;            /* Index into the cell pointer array */
39198      int sz;           /* Size of a cell */
39199
39200      if( !pPage->leaf ) iCellLast--;
39201      for(i=0; i<pPage->nCell; i++){
39202        pc = get2byte(&data[cellOffset+i*2]);
39203        testcase( pc==iCellFirst );
39204        testcase( pc==iCellLast );
39205        if( pc<iCellFirst || pc>iCellLast ){
39206          return SQLITE_CORRUPT_BKPT;
39207        }
39208        sz = cellSizePtr(pPage, &data[pc]);
39209        testcase( pc+sz==usableSize );
39210        if( pc+sz>usableSize ){
39211          return SQLITE_CORRUPT_BKPT;
39212        }
39213      }
39214      if( !pPage->leaf ) iCellLast++;
39215    }
39216#endif
39217
39218    /* Compute the total free space on the page */
39219    pc = get2byte(&data[hdr+1]);
39220    nFree = data[hdr+7] + top;
39221    while( pc>0 ){
39222      u16 next, size;
39223      if( pc<iCellFirst || pc>iCellLast ){
39224        /* Start of free block is off the page */
39225        return SQLITE_CORRUPT_BKPT;
39226      }
39227      next = get2byte(&data[pc]);
39228      size = get2byte(&data[pc+2]);
39229      if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
39230        /* Free blocks must be in ascending order. And the last byte of
39231	** the free-block must lie on the database page.  */
39232        return SQLITE_CORRUPT_BKPT;
39233      }
39234      nFree = nFree + size;
39235      pc = next;
39236    }
39237
39238    /* At this point, nFree contains the sum of the offset to the start
39239    ** of the cell-content area plus the number of free bytes within
39240    ** the cell-content area. If this is greater than the usable-size
39241    ** of the page, then the page must be corrupted. This check also
39242    ** serves to verify that the offset to the start of the cell-content
39243    ** area, according to the page header, lies within the page.
39244    */
39245    if( nFree>usableSize ){
39246      return SQLITE_CORRUPT_BKPT;
39247    }
39248    pPage->nFree = (u16)(nFree - iCellFirst);
39249    pPage->isInit = 1;
39250  }
39251  return SQLITE_OK;
39252}
39253
39254/*
39255** Set up a raw page so that it looks like a database page holding
39256** no entries.
39257*/
39258static void zeroPage(MemPage *pPage, int flags){
39259  unsigned char *data = pPage->aData;
39260  BtShared *pBt = pPage->pBt;
39261  u8 hdr = pPage->hdrOffset;
39262  u16 first;
39263
39264  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
39265  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
39266  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
39267  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
39268  assert( sqlite3_mutex_held(pBt->mutex) );
39269#ifdef SQLITE_SECURE_DELETE
39270  memset(&data[hdr], 0, pBt->usableSize - hdr);
39271#endif
39272  data[hdr] = (char)flags;
39273  first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
39274  memset(&data[hdr+1], 0, 4);
39275  data[hdr+7] = 0;
39276  put2byte(&data[hdr+5], pBt->usableSize);
39277  pPage->nFree = pBt->usableSize - first;
39278  decodeFlags(pPage, flags);
39279  pPage->hdrOffset = hdr;
39280  pPage->cellOffset = first;
39281  pPage->nOverflow = 0;
39282  assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
39283  pPage->maskPage = pBt->pageSize - 1;
39284  pPage->nCell = 0;
39285  pPage->isInit = 1;
39286}
39287
39288
39289/*
39290** Convert a DbPage obtained from the pager into a MemPage used by
39291** the btree layer.
39292*/
39293static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
39294  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
39295  pPage->aData = sqlite3PagerGetData(pDbPage);
39296  pPage->pDbPage = pDbPage;
39297  pPage->pBt = pBt;
39298  pPage->pgno = pgno;
39299  pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
39300  return pPage;
39301}
39302
39303/*
39304** Get a page from the pager.  Initialize the MemPage.pBt and
39305** MemPage.aData elements if needed.
39306**
39307** If the noContent flag is set, it means that we do not care about
39308** the content of the page at this time.  So do not go to the disk
39309** to fetch the content.  Just fill in the content with zeros for now.
39310** If in the future we call sqlite3PagerWrite() on this page, that
39311** means we have started to be concerned about content and the disk
39312** read should occur at that point.
39313*/
39314static int btreeGetPage(
39315  BtShared *pBt,       /* The btree */
39316  Pgno pgno,           /* Number of the page to fetch */
39317  MemPage **ppPage,    /* Return the page in this parameter */
39318  int noContent        /* Do not load page content if true */
39319){
39320  int rc;
39321  DbPage *pDbPage;
39322
39323  assert( sqlite3_mutex_held(pBt->mutex) );
39324  rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
39325  if( rc ) return rc;
39326  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
39327  return SQLITE_OK;
39328}
39329
39330/*
39331** Retrieve a page from the pager cache. If the requested page is not
39332** already in the pager cache return NULL. Initialize the MemPage.pBt and
39333** MemPage.aData elements if needed.
39334*/
39335static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
39336  DbPage *pDbPage;
39337  assert( sqlite3_mutex_held(pBt->mutex) );
39338  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
39339  if( pDbPage ){
39340    return btreePageFromDbPage(pDbPage, pgno, pBt);
39341  }
39342  return 0;
39343}
39344
39345/*
39346** Return the size of the database file in pages. If there is any kind of
39347** error, return ((unsigned int)-1).
39348*/
39349static Pgno pagerPagecount(BtShared *pBt){
39350  int nPage = -1;
39351  int rc;
39352  assert( pBt->pPage1 );
39353  rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
39354  assert( rc==SQLITE_OK || nPage==-1 );
39355  return (Pgno)nPage;
39356}
39357
39358/*
39359** Get a page from the pager and initialize it.  This routine is just a
39360** convenience wrapper around separate calls to btreeGetPage() and
39361** btreeInitPage().
39362**
39363** If an error occurs, then the value *ppPage is set to is undefined. It
39364** may remain unchanged, or it may be set to an invalid value.
39365*/
39366static int getAndInitPage(
39367  BtShared *pBt,          /* The database file */
39368  Pgno pgno,           /* Number of the page to get */
39369  MemPage **ppPage     /* Write the page pointer here */
39370){
39371  int rc;
39372  TESTONLY( Pgno iLastPg = pagerPagecount(pBt); )
39373  assert( sqlite3_mutex_held(pBt->mutex) );
39374
39375  rc = btreeGetPage(pBt, pgno, ppPage, 0);
39376  if( rc==SQLITE_OK ){
39377    rc = btreeInitPage(*ppPage);
39378    if( rc!=SQLITE_OK ){
39379      releasePage(*ppPage);
39380    }
39381  }
39382
39383  /* If the requested page number was either 0 or greater than the page
39384  ** number of the last page in the database, this function should return
39385  ** SQLITE_CORRUPT or some other error (i.e. SQLITE_FULL). Check that this
39386  ** is the case.  */
39387  assert( (pgno>0 && pgno<=iLastPg) || rc!=SQLITE_OK );
39388  testcase( pgno==0 );
39389  testcase( pgno==iLastPg );
39390
39391  return rc;
39392}
39393
39394/*
39395** Release a MemPage.  This should be called once for each prior
39396** call to btreeGetPage.
39397*/
39398static void releasePage(MemPage *pPage){
39399  if( pPage ){
39400    assert( pPage->aData );
39401    assert( pPage->pBt );
39402    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
39403    assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
39404    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39405    sqlite3PagerUnref(pPage->pDbPage);
39406  }
39407}
39408
39409/*
39410** During a rollback, when the pager reloads information into the cache
39411** so that the cache is restored to its original state at the start of
39412** the transaction, for each page restored this routine is called.
39413**
39414** This routine needs to reset the extra data section at the end of the
39415** page to agree with the restored data.
39416*/
39417static void pageReinit(DbPage *pData){
39418  MemPage *pPage;
39419  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
39420  assert( sqlite3PagerPageRefcount(pData)>0 );
39421  if( pPage->isInit ){
39422    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39423    pPage->isInit = 0;
39424    if( sqlite3PagerPageRefcount(pData)>1 ){
39425      /* pPage might not be a btree page;  it might be an overflow page
39426      ** or ptrmap page or a free page.  In those cases, the following
39427      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
39428      ** But no harm is done by this.  And it is very important that
39429      ** btreeInitPage() be called on every btree page so we make
39430      ** the call for every page that comes in for re-initing. */
39431      btreeInitPage(pPage);
39432    }
39433  }
39434}
39435
39436/*
39437** Invoke the busy handler for a btree.
39438*/
39439static int btreeInvokeBusyHandler(void *pArg){
39440  BtShared *pBt = (BtShared*)pArg;
39441  assert( pBt->db );
39442  assert( sqlite3_mutex_held(pBt->db->mutex) );
39443  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
39444}
39445
39446/*
39447** Open a database file.
39448**
39449** zFilename is the name of the database file.  If zFilename is NULL
39450** a new database with a random name is created.  This randomly named
39451** database file will be deleted when sqlite3BtreeClose() is called.
39452** If zFilename is ":memory:" then an in-memory database is created
39453** that is automatically destroyed when it is closed.
39454**
39455** If the database is already opened in the same database connection
39456** and we are in shared cache mode, then the open will fail with an
39457** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
39458** objects in the same database connection since doing so will lead
39459** to problems with locking.
39460*/
39461SQLITE_PRIVATE int sqlite3BtreeOpen(
39462  const char *zFilename,  /* Name of the file containing the BTree database */
39463  sqlite3 *db,            /* Associated database handle */
39464  Btree **ppBtree,        /* Pointer to new Btree object written here */
39465  int flags,              /* Options */
39466  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
39467){
39468  sqlite3_vfs *pVfs;             /* The VFS to use for this btree */
39469  BtShared *pBt = 0;             /* Shared part of btree structure */
39470  Btree *p;                      /* Handle to return */
39471  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
39472  int rc = SQLITE_OK;            /* Result code from this function */
39473  u8 nReserve;                   /* Byte of unused space on each page */
39474  unsigned char zDbHeader[100];  /* Database header content */
39475
39476  /* Set the variable isMemdb to true for an in-memory database, or
39477  ** false for a file-based database. This symbol is only required if
39478  ** either of the shared-data or autovacuum features are compiled
39479  ** into the library.
39480  */
39481#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
39482  #ifdef SQLITE_OMIT_MEMORYDB
39483    const int isMemdb = 0;
39484  #else
39485    const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
39486  #endif
39487#endif
39488
39489  assert( db!=0 );
39490  assert( sqlite3_mutex_held(db->mutex) );
39491
39492  pVfs = db->pVfs;
39493  p = sqlite3MallocZero(sizeof(Btree));
39494  if( !p ){
39495    return SQLITE_NOMEM;
39496  }
39497  p->inTrans = TRANS_NONE;
39498  p->db = db;
39499#ifndef SQLITE_OMIT_SHARED_CACHE
39500  p->lock.pBtree = p;
39501  p->lock.iTable = 1;
39502#endif
39503
39504#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
39505  /*
39506  ** If this Btree is a candidate for shared cache, try to find an
39507  ** existing BtShared object that we can share with
39508  */
39509  if( isMemdb==0 && zFilename && zFilename[0] ){
39510    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
39511      int nFullPathname = pVfs->mxPathname+1;
39512      char *zFullPathname = sqlite3Malloc(nFullPathname);
39513      sqlite3_mutex *mutexShared;
39514      p->sharable = 1;
39515      if( !zFullPathname ){
39516        sqlite3_free(p);
39517        return SQLITE_NOMEM;
39518      }
39519      sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
39520      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
39521      sqlite3_mutex_enter(mutexOpen);
39522      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
39523      sqlite3_mutex_enter(mutexShared);
39524      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
39525        assert( pBt->nRef>0 );
39526        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
39527                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
39528          int iDb;
39529          for(iDb=db->nDb-1; iDb>=0; iDb--){
39530            Btree *pExisting = db->aDb[iDb].pBt;
39531            if( pExisting && pExisting->pBt==pBt ){
39532              sqlite3_mutex_leave(mutexShared);
39533              sqlite3_mutex_leave(mutexOpen);
39534              sqlite3_free(zFullPathname);
39535              sqlite3_free(p);
39536              return SQLITE_CONSTRAINT;
39537            }
39538          }
39539          p->pBt = pBt;
39540          pBt->nRef++;
39541          break;
39542        }
39543      }
39544      sqlite3_mutex_leave(mutexShared);
39545      sqlite3_free(zFullPathname);
39546    }
39547#ifdef SQLITE_DEBUG
39548    else{
39549      /* In debug mode, we mark all persistent databases as sharable
39550      ** even when they are not.  This exercises the locking code and
39551      ** gives more opportunity for asserts(sqlite3_mutex_held())
39552      ** statements to find locking problems.
39553      */
39554      p->sharable = 1;
39555    }
39556#endif
39557  }
39558#endif
39559  if( pBt==0 ){
39560    /*
39561    ** The following asserts make sure that structures used by the btree are
39562    ** the right size.  This is to guard against size changes that result
39563    ** when compiling on a different architecture.
39564    */
39565    assert( sizeof(i64)==8 || sizeof(i64)==4 );
39566    assert( sizeof(u64)==8 || sizeof(u64)==4 );
39567    assert( sizeof(u32)==4 );
39568    assert( sizeof(u16)==2 );
39569    assert( sizeof(Pgno)==4 );
39570
39571    pBt = sqlite3MallocZero( sizeof(*pBt) );
39572    if( pBt==0 ){
39573      rc = SQLITE_NOMEM;
39574      goto btree_open_out;
39575    }
39576    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
39577                          EXTRA_SIZE, flags, vfsFlags, pageReinit);
39578    if( rc==SQLITE_OK ){
39579      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
39580    }
39581    if( rc!=SQLITE_OK ){
39582      goto btree_open_out;
39583    }
39584    pBt->db = db;
39585    sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
39586    p->pBt = pBt;
39587
39588    pBt->pCursor = 0;
39589    pBt->pPage1 = 0;
39590    pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
39591    pBt->pageSize = get2byte(&zDbHeader[16]);
39592    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
39593         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
39594      pBt->pageSize = 0;
39595#ifndef SQLITE_OMIT_AUTOVACUUM
39596      /* If the magic name ":memory:" will create an in-memory database, then
39597      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
39598      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
39599      ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
39600      ** regular file-name. In this case the auto-vacuum applies as per normal.
39601      */
39602      if( zFilename && !isMemdb ){
39603        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
39604        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
39605      }
39606#endif
39607      nReserve = 0;
39608    }else{
39609      nReserve = zDbHeader[20];
39610      pBt->pageSizeFixed = 1;
39611#ifndef SQLITE_OMIT_AUTOVACUUM
39612      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
39613      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
39614#endif
39615    }
39616    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
39617    if( rc ) goto btree_open_out;
39618    pBt->usableSize = pBt->pageSize - nReserve;
39619    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
39620
39621#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
39622    /* Add the new BtShared object to the linked list sharable BtShareds.
39623    */
39624    if( p->sharable ){
39625      sqlite3_mutex *mutexShared;
39626      pBt->nRef = 1;
39627      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
39628      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
39629        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
39630        if( pBt->mutex==0 ){
39631          rc = SQLITE_NOMEM;
39632          db->mallocFailed = 0;
39633          goto btree_open_out;
39634        }
39635      }
39636      sqlite3_mutex_enter(mutexShared);
39637      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
39638      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
39639      sqlite3_mutex_leave(mutexShared);
39640    }
39641#endif
39642  }
39643
39644#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
39645  /* If the new Btree uses a sharable pBtShared, then link the new
39646  ** Btree into the list of all sharable Btrees for the same connection.
39647  ** The list is kept in ascending order by pBt address.
39648  */
39649  if( p->sharable ){
39650    int i;
39651    Btree *pSib;
39652    for(i=0; i<db->nDb; i++){
39653      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
39654        while( pSib->pPrev ){ pSib = pSib->pPrev; }
39655        if( p->pBt<pSib->pBt ){
39656          p->pNext = pSib;
39657          p->pPrev = 0;
39658          pSib->pPrev = p;
39659        }else{
39660          while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
39661            pSib = pSib->pNext;
39662          }
39663          p->pNext = pSib->pNext;
39664          p->pPrev = pSib;
39665          if( p->pNext ){
39666            p->pNext->pPrev = p;
39667          }
39668          pSib->pNext = p;
39669        }
39670        break;
39671      }
39672    }
39673  }
39674#endif
39675  *ppBtree = p;
39676
39677btree_open_out:
39678  if( rc!=SQLITE_OK ){
39679    if( pBt && pBt->pPager ){
39680      sqlite3PagerClose(pBt->pPager);
39681    }
39682    sqlite3_free(pBt);
39683    sqlite3_free(p);
39684    *ppBtree = 0;
39685  }
39686  if( mutexOpen ){
39687    assert( sqlite3_mutex_held(mutexOpen) );
39688    sqlite3_mutex_leave(mutexOpen);
39689  }
39690  return rc;
39691}
39692
39693/*
39694** Decrement the BtShared.nRef counter.  When it reaches zero,
39695** remove the BtShared structure from the sharing list.  Return
39696** true if the BtShared.nRef counter reaches zero and return
39697** false if it is still positive.
39698*/
39699static int removeFromSharingList(BtShared *pBt){
39700#ifndef SQLITE_OMIT_SHARED_CACHE
39701  sqlite3_mutex *pMaster;
39702  BtShared *pList;
39703  int removed = 0;
39704
39705  assert( sqlite3_mutex_notheld(pBt->mutex) );
39706  pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
39707  sqlite3_mutex_enter(pMaster);
39708  pBt->nRef--;
39709  if( pBt->nRef<=0 ){
39710    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
39711      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
39712    }else{
39713      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
39714      while( ALWAYS(pList) && pList->pNext!=pBt ){
39715        pList=pList->pNext;
39716      }
39717      if( ALWAYS(pList) ){
39718        pList->pNext = pBt->pNext;
39719      }
39720    }
39721    if( SQLITE_THREADSAFE ){
39722      sqlite3_mutex_free(pBt->mutex);
39723    }
39724    removed = 1;
39725  }
39726  sqlite3_mutex_leave(pMaster);
39727  return removed;
39728#else
39729  return 1;
39730#endif
39731}
39732
39733/*
39734** Make sure pBt->pTmpSpace points to an allocation of
39735** MX_CELL_SIZE(pBt) bytes.
39736*/
39737static void allocateTempSpace(BtShared *pBt){
39738  if( !pBt->pTmpSpace ){
39739    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
39740  }
39741}
39742
39743/*
39744** Free the pBt->pTmpSpace allocation
39745*/
39746static void freeTempSpace(BtShared *pBt){
39747  sqlite3PageFree( pBt->pTmpSpace);
39748  pBt->pTmpSpace = 0;
39749}
39750
39751/*
39752** Close an open database and invalidate all cursors.
39753*/
39754SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
39755  BtShared *pBt = p->pBt;
39756  BtCursor *pCur;
39757
39758  /* Close all cursors opened via this handle.  */
39759  assert( sqlite3_mutex_held(p->db->mutex) );
39760  sqlite3BtreeEnter(p);
39761  pCur = pBt->pCursor;
39762  while( pCur ){
39763    BtCursor *pTmp = pCur;
39764    pCur = pCur->pNext;
39765    if( pTmp->pBtree==p ){
39766      sqlite3BtreeCloseCursor(pTmp);
39767    }
39768  }
39769
39770  /* Rollback any active transaction and free the handle structure.
39771  ** The call to sqlite3BtreeRollback() drops any table-locks held by
39772  ** this handle.
39773  */
39774  sqlite3BtreeRollback(p);
39775  sqlite3BtreeLeave(p);
39776
39777  /* If there are still other outstanding references to the shared-btree
39778  ** structure, return now. The remainder of this procedure cleans
39779  ** up the shared-btree.
39780  */
39781  assert( p->wantToLock==0 && p->locked==0 );
39782  if( !p->sharable || removeFromSharingList(pBt) ){
39783    /* The pBt is no longer on the sharing list, so we can access
39784    ** it without having to hold the mutex.
39785    **
39786    ** Clean out and delete the BtShared object.
39787    */
39788    assert( !pBt->pCursor );
39789    sqlite3PagerClose(pBt->pPager);
39790    if( pBt->xFreeSchema && pBt->pSchema ){
39791      pBt->xFreeSchema(pBt->pSchema);
39792    }
39793    sqlite3_free(pBt->pSchema);
39794    freeTempSpace(pBt);
39795    sqlite3_free(pBt);
39796  }
39797
39798#ifndef SQLITE_OMIT_SHARED_CACHE
39799  assert( p->wantToLock==0 );
39800  assert( p->locked==0 );
39801  if( p->pPrev ) p->pPrev->pNext = p->pNext;
39802  if( p->pNext ) p->pNext->pPrev = p->pPrev;
39803#endif
39804
39805  sqlite3_free(p);
39806  return SQLITE_OK;
39807}
39808
39809/*
39810** Change the limit on the number of pages allowed in the cache.
39811**
39812** The maximum number of cache pages is set to the absolute
39813** value of mxPage.  If mxPage is negative, the pager will
39814** operate asynchronously - it will not stop to do fsync()s
39815** to insure data is written to the disk surface before
39816** continuing.  Transactions still work if synchronous is off,
39817** and the database cannot be corrupted if this program
39818** crashes.  But if the operating system crashes or there is
39819** an abrupt power failure when synchronous is off, the database
39820** could be left in an inconsistent and unrecoverable state.
39821** Synchronous is on by default so database corruption is not
39822** normally a worry.
39823*/
39824SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
39825  BtShared *pBt = p->pBt;
39826  assert( sqlite3_mutex_held(p->db->mutex) );
39827  sqlite3BtreeEnter(p);
39828  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
39829  sqlite3BtreeLeave(p);
39830  return SQLITE_OK;
39831}
39832
39833/*
39834** Change the way data is synced to disk in order to increase or decrease
39835** how well the database resists damage due to OS crashes and power
39836** failures.  Level 1 is the same as asynchronous (no syncs() occur and
39837** there is a high probability of damage)  Level 2 is the default.  There
39838** is a very low but non-zero probability of damage.  Level 3 reduces the
39839** probability of damage to near zero but with a write performance reduction.
39840*/
39841#ifndef SQLITE_OMIT_PAGER_PRAGMAS
39842SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
39843  BtShared *pBt = p->pBt;
39844  assert( sqlite3_mutex_held(p->db->mutex) );
39845  sqlite3BtreeEnter(p);
39846  sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
39847  sqlite3BtreeLeave(p);
39848  return SQLITE_OK;
39849}
39850#endif
39851
39852/*
39853** Return TRUE if the given btree is set to safety level 1.  In other
39854** words, return TRUE if no sync() occurs on the disk files.
39855*/
39856SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
39857  BtShared *pBt = p->pBt;
39858  int rc;
39859  assert( sqlite3_mutex_held(p->db->mutex) );
39860  sqlite3BtreeEnter(p);
39861  assert( pBt && pBt->pPager );
39862  rc = sqlite3PagerNosync(pBt->pPager);
39863  sqlite3BtreeLeave(p);
39864  return rc;
39865}
39866
39867#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
39868/*
39869** Change the default pages size and the number of reserved bytes per page.
39870** Or, if the page size has already been fixed, return SQLITE_READONLY
39871** without changing anything.
39872**
39873** The page size must be a power of 2 between 512 and 65536.  If the page
39874** size supplied does not meet this constraint then the page size is not
39875** changed.
39876**
39877** Page sizes are constrained to be a power of two so that the region
39878** of the database file used for locking (beginning at PENDING_BYTE,
39879** the first byte past the 1GB boundary, 0x40000000) needs to occur
39880** at the beginning of a page.
39881**
39882** If parameter nReserve is less than zero, then the number of reserved
39883** bytes per page is left unchanged.
39884**
39885** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
39886** and autovacuum mode can no longer be changed.
39887*/
39888SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
39889  int rc = SQLITE_OK;
39890  BtShared *pBt = p->pBt;
39891  assert( nReserve>=-1 && nReserve<=255 );
39892  sqlite3BtreeEnter(p);
39893  if( pBt->pageSizeFixed ){
39894    sqlite3BtreeLeave(p);
39895    return SQLITE_READONLY;
39896  }
39897  if( nReserve<0 ){
39898    nReserve = pBt->pageSize - pBt->usableSize;
39899  }
39900  assert( nReserve>=0 && nReserve<=255 );
39901  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
39902        ((pageSize-1)&pageSize)==0 ){
39903    assert( (pageSize & 7)==0 );
39904    assert( !pBt->pPage1 && !pBt->pCursor );
39905    pBt->pageSize = (u16)pageSize;
39906    freeTempSpace(pBt);
39907  }
39908  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
39909  pBt->usableSize = pBt->pageSize - (u16)nReserve;
39910  if( iFix ) pBt->pageSizeFixed = 1;
39911  sqlite3BtreeLeave(p);
39912  return rc;
39913}
39914
39915/*
39916** Return the currently defined page size
39917*/
39918SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
39919  return p->pBt->pageSize;
39920}
39921
39922/*
39923** Return the number of bytes of space at the end of every page that
39924** are intentually left unused.  This is the "reserved" space that is
39925** sometimes used by extensions.
39926*/
39927SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
39928  int n;
39929  sqlite3BtreeEnter(p);
39930  n = p->pBt->pageSize - p->pBt->usableSize;
39931  sqlite3BtreeLeave(p);
39932  return n;
39933}
39934
39935/*
39936** Set the maximum page count for a database if mxPage is positive.
39937** No changes are made if mxPage is 0 or negative.
39938** Regardless of the value of mxPage, return the maximum page count.
39939*/
39940SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
39941  int n;
39942  sqlite3BtreeEnter(p);
39943  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
39944  sqlite3BtreeLeave(p);
39945  return n;
39946}
39947#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
39948
39949/*
39950** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
39951** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
39952** is disabled. The default value for the auto-vacuum property is
39953** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
39954*/
39955SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
39956#ifdef SQLITE_OMIT_AUTOVACUUM
39957  return SQLITE_READONLY;
39958#else
39959  BtShared *pBt = p->pBt;
39960  int rc = SQLITE_OK;
39961  u8 av = (u8)autoVacuum;
39962
39963  sqlite3BtreeEnter(p);
39964  if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
39965    rc = SQLITE_READONLY;
39966  }else{
39967    pBt->autoVacuum = av ?1:0;
39968    pBt->incrVacuum = av==2 ?1:0;
39969  }
39970  sqlite3BtreeLeave(p);
39971  return rc;
39972#endif
39973}
39974
39975/*
39976** Return the value of the 'auto-vacuum' property. If auto-vacuum is
39977** enabled 1 is returned. Otherwise 0.
39978*/
39979SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
39980#ifdef SQLITE_OMIT_AUTOVACUUM
39981  return BTREE_AUTOVACUUM_NONE;
39982#else
39983  int rc;
39984  sqlite3BtreeEnter(p);
39985  rc = (
39986    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
39987    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
39988    BTREE_AUTOVACUUM_INCR
39989  );
39990  sqlite3BtreeLeave(p);
39991  return rc;
39992#endif
39993}
39994
39995
39996/*
39997** Get a reference to pPage1 of the database file.  This will
39998** also acquire a readlock on that file.
39999**
40000** SQLITE_OK is returned on success.  If the file is not a
40001** well-formed database file, then SQLITE_CORRUPT is returned.
40002** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
40003** is returned if we run out of memory.
40004*/
40005static int lockBtree(BtShared *pBt){
40006  int rc;
40007  MemPage *pPage1;
40008  int nPage;
40009
40010  assert( sqlite3_mutex_held(pBt->mutex) );
40011  assert( pBt->pPage1==0 );
40012  rc = sqlite3PagerSharedLock(pBt->pPager);
40013  if( rc!=SQLITE_OK ) return rc;
40014  rc = btreeGetPage(pBt, 1, &pPage1, 0);
40015  if( rc!=SQLITE_OK ) return rc;
40016
40017  /* Do some checking to help insure the file we opened really is
40018  ** a valid database file.
40019  */
40020  rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
40021  if( rc!=SQLITE_OK ){
40022    goto page1_init_failed;
40023  }else if( nPage>0 ){
40024    int pageSize;
40025    int usableSize;
40026    u8 *page1 = pPage1->aData;
40027    rc = SQLITE_NOTADB;
40028    if( memcmp(page1, zMagicHeader, 16)!=0 ){
40029      goto page1_init_failed;
40030    }
40031    if( page1[18]>1 ){
40032      pBt->readOnly = 1;
40033    }
40034    if( page1[19]>1 ){
40035      goto page1_init_failed;
40036    }
40037
40038    /* The maximum embedded fraction must be exactly 25%.  And the minimum
40039    ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
40040    ** The original design allowed these amounts to vary, but as of
40041    ** version 3.6.0, we require them to be fixed.
40042    */
40043    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
40044      goto page1_init_failed;
40045    }
40046    pageSize = get2byte(&page1[16]);
40047    if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
40048        (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
40049    ){
40050      goto page1_init_failed;
40051    }
40052    assert( (pageSize & 7)==0 );
40053    usableSize = pageSize - page1[20];
40054    if( pageSize!=pBt->pageSize ){
40055      /* After reading the first page of the database assuming a page size
40056      ** of BtShared.pageSize, we have discovered that the page-size is
40057      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
40058      ** zero and return SQLITE_OK. The caller will call this function
40059      ** again with the correct page-size.
40060      */
40061      releasePage(pPage1);
40062      pBt->usableSize = (u16)usableSize;
40063      pBt->pageSize = (u16)pageSize;
40064      freeTempSpace(pBt);
40065      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
40066                                   pageSize-usableSize);
40067      return rc;
40068    }
40069    if( usableSize<480 ){
40070      goto page1_init_failed;
40071    }
40072    pBt->pageSize = (u16)pageSize;
40073    pBt->usableSize = (u16)usableSize;
40074#ifndef SQLITE_OMIT_AUTOVACUUM
40075    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
40076    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
40077#endif
40078  }
40079
40080  /* maxLocal is the maximum amount of payload to store locally for
40081  ** a cell.  Make sure it is small enough so that at least minFanout
40082  ** cells can will fit on one page.  We assume a 10-byte page header.
40083  ** Besides the payload, the cell must store:
40084  **     2-byte pointer to the cell
40085  **     4-byte child pointer
40086  **     9-byte nKey value
40087  **     4-byte nData value
40088  **     4-byte overflow page pointer
40089  ** So a cell consists of a 2-byte poiner, a header which is as much as
40090  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
40091  ** page pointer.
40092  */
40093  pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
40094  pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
40095  pBt->maxLeaf = pBt->usableSize - 35;
40096  pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
40097  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
40098  pBt->pPage1 = pPage1;
40099  return SQLITE_OK;
40100
40101page1_init_failed:
40102  releasePage(pPage1);
40103  pBt->pPage1 = 0;
40104  return rc;
40105}
40106
40107/*
40108** If there are no outstanding cursors and we are not in the middle
40109** of a transaction but there is a read lock on the database, then
40110** this routine unrefs the first page of the database file which
40111** has the effect of releasing the read lock.
40112**
40113** If there is a transaction in progress, this routine is a no-op.
40114*/
40115static void unlockBtreeIfUnused(BtShared *pBt){
40116  assert( sqlite3_mutex_held(pBt->mutex) );
40117  assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
40118  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
40119    assert( pBt->pPage1->aData );
40120    assert( sqlite3PagerRefcount(pBt->pPager)==1 );
40121    assert( pBt->pPage1->aData );
40122    releasePage(pBt->pPage1);
40123    pBt->pPage1 = 0;
40124  }
40125}
40126
40127/*
40128** If pBt points to an empty file then convert that empty file
40129** into a new empty database by initializing the first page of
40130** the database.
40131*/
40132static int newDatabase(BtShared *pBt){
40133  MemPage *pP1;
40134  unsigned char *data;
40135  int rc;
40136  int nPage;
40137
40138  assert( sqlite3_mutex_held(pBt->mutex) );
40139  rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
40140  if( rc!=SQLITE_OK || nPage>0 ){
40141    return rc;
40142  }
40143  pP1 = pBt->pPage1;
40144  assert( pP1!=0 );
40145  data = pP1->aData;
40146  rc = sqlite3PagerWrite(pP1->pDbPage);
40147  if( rc ) return rc;
40148  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
40149  assert( sizeof(zMagicHeader)==16 );
40150  put2byte(&data[16], pBt->pageSize);
40151  data[18] = 1;
40152  data[19] = 1;
40153  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
40154  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
40155  data[21] = 64;
40156  data[22] = 32;
40157  data[23] = 32;
40158  memset(&data[24], 0, 100-24);
40159  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
40160  pBt->pageSizeFixed = 1;
40161#ifndef SQLITE_OMIT_AUTOVACUUM
40162  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
40163  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
40164  put4byte(&data[36 + 4*4], pBt->autoVacuum);
40165  put4byte(&data[36 + 7*4], pBt->incrVacuum);
40166#endif
40167  return SQLITE_OK;
40168}
40169
40170/*
40171** Attempt to start a new transaction. A write-transaction
40172** is started if the second argument is nonzero, otherwise a read-
40173** transaction.  If the second argument is 2 or more and exclusive
40174** transaction is started, meaning that no other process is allowed
40175** to access the database.  A preexisting transaction may not be
40176** upgraded to exclusive by calling this routine a second time - the
40177** exclusivity flag only works for a new transaction.
40178**
40179** A write-transaction must be started before attempting any
40180** changes to the database.  None of the following routines
40181** will work unless a transaction is started first:
40182**
40183**      sqlite3BtreeCreateTable()
40184**      sqlite3BtreeCreateIndex()
40185**      sqlite3BtreeClearTable()
40186**      sqlite3BtreeDropTable()
40187**      sqlite3BtreeInsert()
40188**      sqlite3BtreeDelete()
40189**      sqlite3BtreeUpdateMeta()
40190**
40191** If an initial attempt to acquire the lock fails because of lock contention
40192** and the database was previously unlocked, then invoke the busy handler
40193** if there is one.  But if there was previously a read-lock, do not
40194** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
40195** returned when there is already a read-lock in order to avoid a deadlock.
40196**
40197** Suppose there are two processes A and B.  A has a read lock and B has
40198** a reserved lock.  B tries to promote to exclusive but is blocked because
40199** of A's read lock.  A tries to promote to reserved but is blocked by B.
40200** One or the other of the two processes must give way or there can be
40201** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
40202** when A already has a read lock, we encourage A to give up and let B
40203** proceed.
40204*/
40205SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
40206  sqlite3 *pBlock = 0;
40207  BtShared *pBt = p->pBt;
40208  int rc = SQLITE_OK;
40209
40210  sqlite3BtreeEnter(p);
40211  btreeIntegrity(p);
40212
40213  /* If the btree is already in a write-transaction, or it
40214  ** is already in a read-transaction and a read-transaction
40215  ** is requested, this is a no-op.
40216  */
40217  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
40218    goto trans_begun;
40219  }
40220
40221  /* Write transactions are not possible on a read-only database */
40222  if( pBt->readOnly && wrflag ){
40223    rc = SQLITE_READONLY;
40224    goto trans_begun;
40225  }
40226
40227#ifndef SQLITE_OMIT_SHARED_CACHE
40228  /* If another database handle has already opened a write transaction
40229  ** on this shared-btree structure and a second write transaction is
40230  ** requested, return SQLITE_LOCKED.
40231  */
40232  if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
40233    pBlock = pBt->pWriter->db;
40234  }else if( wrflag>1 ){
40235    BtLock *pIter;
40236    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
40237      if( pIter->pBtree!=p ){
40238        pBlock = pIter->pBtree->db;
40239        break;
40240      }
40241    }
40242  }
40243  if( pBlock ){
40244    sqlite3ConnectionBlocked(p->db, pBlock);
40245    rc = SQLITE_LOCKED_SHAREDCACHE;
40246    goto trans_begun;
40247  }
40248#endif
40249
40250  /* Any read-only or read-write transaction implies a read-lock on
40251  ** page 1. So if some other shared-cache client already has a write-lock
40252  ** on page 1, the transaction cannot be opened. */
40253  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
40254  if( SQLITE_OK!=rc ) goto trans_begun;
40255
40256  do {
40257    /* Call lockBtree() until either pBt->pPage1 is populated or
40258    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
40259    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
40260    ** reading page 1 it discovers that the page-size of the database
40261    ** file is not pBt->pageSize. In this case lockBtree() will update
40262    ** pBt->pageSize to the page-size of the file on disk.
40263    */
40264    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
40265
40266    if( rc==SQLITE_OK && wrflag ){
40267      if( pBt->readOnly ){
40268        rc = SQLITE_READONLY;
40269      }else{
40270        rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
40271        if( rc==SQLITE_OK ){
40272          rc = newDatabase(pBt);
40273        }
40274      }
40275    }
40276
40277    if( rc!=SQLITE_OK ){
40278      unlockBtreeIfUnused(pBt);
40279    }
40280  }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
40281          btreeInvokeBusyHandler(pBt) );
40282
40283  if( rc==SQLITE_OK ){
40284    if( p->inTrans==TRANS_NONE ){
40285      pBt->nTransaction++;
40286#ifndef SQLITE_OMIT_SHARED_CACHE
40287      if( p->sharable ){
40288	assert( p->lock.pBtree==p && p->lock.iTable==1 );
40289        p->lock.eLock = READ_LOCK;
40290        p->lock.pNext = pBt->pLock;
40291        pBt->pLock = &p->lock;
40292      }
40293#endif
40294    }
40295    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
40296    if( p->inTrans>pBt->inTransaction ){
40297      pBt->inTransaction = p->inTrans;
40298    }
40299#ifndef SQLITE_OMIT_SHARED_CACHE
40300    if( wrflag ){
40301      assert( !pBt->pWriter );
40302      pBt->pWriter = p;
40303      pBt->isExclusive = (u8)(wrflag>1);
40304    }
40305#endif
40306  }
40307
40308
40309trans_begun:
40310  if( rc==SQLITE_OK && wrflag ){
40311    /* This call makes sure that the pager has the correct number of
40312    ** open savepoints. If the second parameter is greater than 0 and
40313    ** the sub-journal is not already open, then it will be opened here.
40314    */
40315    rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
40316  }
40317
40318  btreeIntegrity(p);
40319  sqlite3BtreeLeave(p);
40320  return rc;
40321}
40322
40323#ifndef SQLITE_OMIT_AUTOVACUUM
40324
40325/*
40326** Set the pointer-map entries for all children of page pPage. Also, if
40327** pPage contains cells that point to overflow pages, set the pointer
40328** map entries for the overflow pages as well.
40329*/
40330static int setChildPtrmaps(MemPage *pPage){
40331  int i;                             /* Counter variable */
40332  int nCell;                         /* Number of cells in page pPage */
40333  int rc;                            /* Return code */
40334  BtShared *pBt = pPage->pBt;
40335  u8 isInitOrig = pPage->isInit;
40336  Pgno pgno = pPage->pgno;
40337
40338  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
40339  rc = btreeInitPage(pPage);
40340  if( rc!=SQLITE_OK ){
40341    goto set_child_ptrmaps_out;
40342  }
40343  nCell = pPage->nCell;
40344
40345  for(i=0; i<nCell; i++){
40346    u8 *pCell = findCell(pPage, i);
40347
40348    ptrmapPutOvflPtr(pPage, pCell, &rc);
40349
40350    if( !pPage->leaf ){
40351      Pgno childPgno = get4byte(pCell);
40352      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
40353    }
40354  }
40355
40356  if( !pPage->leaf ){
40357    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
40358    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
40359  }
40360
40361set_child_ptrmaps_out:
40362  pPage->isInit = isInitOrig;
40363  return rc;
40364}
40365
40366/*
40367** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
40368** that it points to iTo. Parameter eType describes the type of pointer to
40369** be modified, as  follows:
40370**
40371** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
40372**                   page of pPage.
40373**
40374** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
40375**                   page pointed to by one of the cells on pPage.
40376**
40377** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
40378**                   overflow page in the list.
40379*/
40380static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
40381  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
40382  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
40383  if( eType==PTRMAP_OVERFLOW2 ){
40384    /* The pointer is always the first 4 bytes of the page in this case.  */
40385    if( get4byte(pPage->aData)!=iFrom ){
40386      return SQLITE_CORRUPT_BKPT;
40387    }
40388    put4byte(pPage->aData, iTo);
40389  }else{
40390    u8 isInitOrig = pPage->isInit;
40391    int i;
40392    int nCell;
40393
40394    btreeInitPage(pPage);
40395    nCell = pPage->nCell;
40396
40397    for(i=0; i<nCell; i++){
40398      u8 *pCell = findCell(pPage, i);
40399      if( eType==PTRMAP_OVERFLOW1 ){
40400        CellInfo info;
40401        btreeParseCellPtr(pPage, pCell, &info);
40402        if( info.iOverflow ){
40403          if( iFrom==get4byte(&pCell[info.iOverflow]) ){
40404            put4byte(&pCell[info.iOverflow], iTo);
40405            break;
40406          }
40407        }
40408      }else{
40409        if( get4byte(pCell)==iFrom ){
40410          put4byte(pCell, iTo);
40411          break;
40412        }
40413      }
40414    }
40415
40416    if( i==nCell ){
40417      if( eType!=PTRMAP_BTREE ||
40418          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
40419        return SQLITE_CORRUPT_BKPT;
40420      }
40421      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
40422    }
40423
40424    pPage->isInit = isInitOrig;
40425  }
40426  return SQLITE_OK;
40427}
40428
40429
40430/*
40431** Move the open database page pDbPage to location iFreePage in the
40432** database. The pDbPage reference remains valid.
40433**
40434** The isCommit flag indicates that there is no need to remember that
40435** the journal needs to be sync()ed before database page pDbPage->pgno
40436** can be written to. The caller has already promised not to write to that
40437** page.
40438*/
40439static int relocatePage(
40440  BtShared *pBt,           /* Btree */
40441  MemPage *pDbPage,        /* Open page to move */
40442  u8 eType,                /* Pointer map 'type' entry for pDbPage */
40443  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
40444  Pgno iFreePage,          /* The location to move pDbPage to */
40445  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
40446){
40447  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
40448  Pgno iDbPage = pDbPage->pgno;
40449  Pager *pPager = pBt->pPager;
40450  int rc;
40451
40452  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
40453      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
40454  assert( sqlite3_mutex_held(pBt->mutex) );
40455  assert( pDbPage->pBt==pBt );
40456
40457  /* Move page iDbPage from its current location to page number iFreePage */
40458  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
40459      iDbPage, iFreePage, iPtrPage, eType));
40460  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
40461  if( rc!=SQLITE_OK ){
40462    return rc;
40463  }
40464  pDbPage->pgno = iFreePage;
40465
40466  /* If pDbPage was a btree-page, then it may have child pages and/or cells
40467  ** that point to overflow pages. The pointer map entries for all these
40468  ** pages need to be changed.
40469  **
40470  ** If pDbPage is an overflow page, then the first 4 bytes may store a
40471  ** pointer to a subsequent overflow page. If this is the case, then
40472  ** the pointer map needs to be updated for the subsequent overflow page.
40473  */
40474  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
40475    rc = setChildPtrmaps(pDbPage);
40476    if( rc!=SQLITE_OK ){
40477      return rc;
40478    }
40479  }else{
40480    Pgno nextOvfl = get4byte(pDbPage->aData);
40481    if( nextOvfl!=0 ){
40482      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
40483      if( rc!=SQLITE_OK ){
40484        return rc;
40485      }
40486    }
40487  }
40488
40489  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
40490  ** that it points at iFreePage. Also fix the pointer map entry for
40491  ** iPtrPage.
40492  */
40493  if( eType!=PTRMAP_ROOTPAGE ){
40494    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
40495    if( rc!=SQLITE_OK ){
40496      return rc;
40497    }
40498    rc = sqlite3PagerWrite(pPtrPage->pDbPage);
40499    if( rc!=SQLITE_OK ){
40500      releasePage(pPtrPage);
40501      return rc;
40502    }
40503    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
40504    releasePage(pPtrPage);
40505    if( rc==SQLITE_OK ){
40506      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
40507    }
40508  }
40509  return rc;
40510}
40511
40512/* Forward declaration required by incrVacuumStep(). */
40513static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
40514
40515/*
40516** Perform a single step of an incremental-vacuum. If successful,
40517** return SQLITE_OK. If there is no work to do (and therefore no
40518** point in calling this function again), return SQLITE_DONE.
40519**
40520** More specificly, this function attempts to re-organize the
40521** database so that the last page of the file currently in use
40522** is no longer in use.
40523**
40524** If the nFin parameter is non-zero, this function assumes
40525** that the caller will keep calling incrVacuumStep() until
40526** it returns SQLITE_DONE or an error, and that nFin is the
40527** number of pages the database file will contain after this
40528** process is complete.  If nFin is zero, it is assumed that
40529** incrVacuumStep() will be called a finite amount of times
40530** which may or may not empty the freelist.  A full autovacuum
40531** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
40532*/
40533static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
40534  Pgno nFreeList;           /* Number of pages still on the free-list */
40535
40536  assert( sqlite3_mutex_held(pBt->mutex) );
40537  assert( iLastPg>nFin );
40538
40539  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
40540    int rc;
40541    u8 eType;
40542    Pgno iPtrPage;
40543
40544    nFreeList = get4byte(&pBt->pPage1->aData[36]);
40545    if( nFreeList==0 ){
40546      return SQLITE_DONE;
40547    }
40548
40549    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
40550    if( rc!=SQLITE_OK ){
40551      return rc;
40552    }
40553    if( eType==PTRMAP_ROOTPAGE ){
40554      return SQLITE_CORRUPT_BKPT;
40555    }
40556
40557    if( eType==PTRMAP_FREEPAGE ){
40558      if( nFin==0 ){
40559        /* Remove the page from the files free-list. This is not required
40560        ** if nFin is non-zero. In that case, the free-list will be
40561        ** truncated to zero after this function returns, so it doesn't
40562        ** matter if it still contains some garbage entries.
40563        */
40564        Pgno iFreePg;
40565        MemPage *pFreePg;
40566        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
40567        if( rc!=SQLITE_OK ){
40568          return rc;
40569        }
40570        assert( iFreePg==iLastPg );
40571        releasePage(pFreePg);
40572      }
40573    } else {
40574      Pgno iFreePg;             /* Index of free page to move pLastPg to */
40575      MemPage *pLastPg;
40576
40577      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
40578      if( rc!=SQLITE_OK ){
40579        return rc;
40580      }
40581
40582      /* If nFin is zero, this loop runs exactly once and page pLastPg
40583      ** is swapped with the first free page pulled off the free list.
40584      **
40585      ** On the other hand, if nFin is greater than zero, then keep
40586      ** looping until a free-page located within the first nFin pages
40587      ** of the file is found.
40588      */
40589      do {
40590        MemPage *pFreePg;
40591        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
40592        if( rc!=SQLITE_OK ){
40593          releasePage(pLastPg);
40594          return rc;
40595        }
40596        releasePage(pFreePg);
40597      }while( nFin!=0 && iFreePg>nFin );
40598      assert( iFreePg<iLastPg );
40599
40600      rc = sqlite3PagerWrite(pLastPg->pDbPage);
40601      if( rc==SQLITE_OK ){
40602        rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
40603      }
40604      releasePage(pLastPg);
40605      if( rc!=SQLITE_OK ){
40606        return rc;
40607      }
40608    }
40609  }
40610
40611  if( nFin==0 ){
40612    iLastPg--;
40613    while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
40614      if( PTRMAP_ISPAGE(pBt, iLastPg) ){
40615        MemPage *pPg;
40616        int rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
40617        if( rc!=SQLITE_OK ){
40618          return rc;
40619        }
40620        rc = sqlite3PagerWrite(pPg->pDbPage);
40621        releasePage(pPg);
40622        if( rc!=SQLITE_OK ){
40623          return rc;
40624        }
40625      }
40626      iLastPg--;
40627    }
40628    sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
40629  }
40630  return SQLITE_OK;
40631}
40632
40633/*
40634** A write-transaction must be opened before calling this function.
40635** It performs a single unit of work towards an incremental vacuum.
40636**
40637** If the incremental vacuum is finished after this function has run,
40638** SQLITE_DONE is returned. If it is not finished, but no error occurred,
40639** SQLITE_OK is returned. Otherwise an SQLite error code.
40640*/
40641SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
40642  int rc;
40643  BtShared *pBt = p->pBt;
40644
40645  sqlite3BtreeEnter(p);
40646  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
40647  if( !pBt->autoVacuum ){
40648    rc = SQLITE_DONE;
40649  }else{
40650    invalidateAllOverflowCache(pBt);
40651    rc = incrVacuumStep(pBt, 0, pagerPagecount(pBt));
40652  }
40653  sqlite3BtreeLeave(p);
40654  return rc;
40655}
40656
40657/*
40658** This routine is called prior to sqlite3PagerCommit when a transaction
40659** is commited for an auto-vacuum database.
40660**
40661** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
40662** the database file should be truncated to during the commit process.
40663** i.e. the database has been reorganized so that only the first *pnTrunc
40664** pages are in use.
40665*/
40666static int autoVacuumCommit(BtShared *pBt){
40667  int rc = SQLITE_OK;
40668  Pager *pPager = pBt->pPager;
40669  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
40670
40671  assert( sqlite3_mutex_held(pBt->mutex) );
40672  invalidateAllOverflowCache(pBt);
40673  assert(pBt->autoVacuum);
40674  if( !pBt->incrVacuum ){
40675    Pgno nFin;         /* Number of pages in database after autovacuuming */
40676    Pgno nFree;        /* Number of pages on the freelist initially */
40677    Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
40678    Pgno iFree;        /* The next page to be freed */
40679    int nEntry;        /* Number of entries on one ptrmap page */
40680    Pgno nOrig;        /* Database size before freeing */
40681
40682    nOrig = pagerPagecount(pBt);
40683    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
40684      /* It is not possible to create a database for which the final page
40685      ** is either a pointer-map page or the pending-byte page. If one
40686      ** is encountered, this indicates corruption.
40687      */
40688      return SQLITE_CORRUPT_BKPT;
40689    }
40690
40691    nFree = get4byte(&pBt->pPage1->aData[36]);
40692    nEntry = pBt->usableSize/5;
40693    nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
40694    nFin = nOrig - nFree - nPtrmap;
40695    if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
40696      nFin--;
40697    }
40698    while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
40699      nFin--;
40700    }
40701    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
40702
40703    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
40704      rc = incrVacuumStep(pBt, nFin, iFree);
40705    }
40706    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
40707      rc = SQLITE_OK;
40708      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
40709      put4byte(&pBt->pPage1->aData[32], 0);
40710      put4byte(&pBt->pPage1->aData[36], 0);
40711      sqlite3PagerTruncateImage(pBt->pPager, nFin);
40712    }
40713    if( rc!=SQLITE_OK ){
40714      sqlite3PagerRollback(pPager);
40715    }
40716  }
40717
40718  assert( nRef==sqlite3PagerRefcount(pPager) );
40719  return rc;
40720}
40721
40722#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
40723# define setChildPtrmaps(x) SQLITE_OK
40724#endif
40725
40726/*
40727** This routine does the first phase of a two-phase commit.  This routine
40728** causes a rollback journal to be created (if it does not already exist)
40729** and populated with enough information so that if a power loss occurs
40730** the database can be restored to its original state by playing back
40731** the journal.  Then the contents of the journal are flushed out to
40732** the disk.  After the journal is safely on oxide, the changes to the
40733** database are written into the database file and flushed to oxide.
40734** At the end of this call, the rollback journal still exists on the
40735** disk and we are still holding all locks, so the transaction has not
40736** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
40737** commit process.
40738**
40739** This call is a no-op if no write-transaction is currently active on pBt.
40740**
40741** Otherwise, sync the database file for the btree pBt. zMaster points to
40742** the name of a master journal file that should be written into the
40743** individual journal file, or is NULL, indicating no master journal file
40744** (single database transaction).
40745**
40746** When this is called, the master journal should already have been
40747** created, populated with this journal pointer and synced to disk.
40748**
40749** Once this is routine has returned, the only thing required to commit
40750** the write-transaction for this database file is to delete the journal.
40751*/
40752SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
40753  int rc = SQLITE_OK;
40754  if( p->inTrans==TRANS_WRITE ){
40755    BtShared *pBt = p->pBt;
40756    sqlite3BtreeEnter(p);
40757#ifndef SQLITE_OMIT_AUTOVACUUM
40758    if( pBt->autoVacuum ){
40759      rc = autoVacuumCommit(pBt);
40760      if( rc!=SQLITE_OK ){
40761        sqlite3BtreeLeave(p);
40762        return rc;
40763      }
40764    }
40765#endif
40766    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
40767    sqlite3BtreeLeave(p);
40768  }
40769  return rc;
40770}
40771
40772/*
40773** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
40774** at the conclusion of a transaction.
40775*/
40776static void btreeEndTransaction(Btree *p){
40777  BtShared *pBt = p->pBt;
40778  assert( sqlite3BtreeHoldsMutex(p) );
40779
40780  btreeClearHasContent(pBt);
40781  if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
40782    /* If there are other active statements that belong to this database
40783    ** handle, downgrade to a read-only transaction. The other statements
40784    ** may still be reading from the database.  */
40785    downgradeAllSharedCacheTableLocks(p);
40786    p->inTrans = TRANS_READ;
40787  }else{
40788    /* If the handle had any kind of transaction open, decrement the
40789    ** transaction count of the shared btree. If the transaction count
40790    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
40791    ** call below will unlock the pager.  */
40792    if( p->inTrans!=TRANS_NONE ){
40793      clearAllSharedCacheTableLocks(p);
40794      pBt->nTransaction--;
40795      if( 0==pBt->nTransaction ){
40796        pBt->inTransaction = TRANS_NONE;
40797      }
40798    }
40799
40800    /* Set the current transaction state to TRANS_NONE and unlock the
40801    ** pager if this call closed the only read or write transaction.  */
40802    p->inTrans = TRANS_NONE;
40803    unlockBtreeIfUnused(pBt);
40804  }
40805
40806  btreeIntegrity(p);
40807}
40808
40809/*
40810** Commit the transaction currently in progress.
40811**
40812** This routine implements the second phase of a 2-phase commit.  The
40813** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
40814** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
40815** routine did all the work of writing information out to disk and flushing the
40816** contents so that they are written onto the disk platter.  All this
40817** routine has to do is delete or truncate or zero the header in the
40818** the rollback journal (which causes the transaction to commit) and
40819** drop locks.
40820**
40821** This will release the write lock on the database file.  If there
40822** are no active cursors, it also releases the read lock.
40823*/
40824SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
40825  BtShared *pBt = p->pBt;
40826
40827  sqlite3BtreeEnter(p);
40828  btreeIntegrity(p);
40829
40830  /* If the handle has a write-transaction open, commit the shared-btrees
40831  ** transaction and set the shared state to TRANS_READ.
40832  */
40833  if( p->inTrans==TRANS_WRITE ){
40834    int rc;
40835    assert( pBt->inTransaction==TRANS_WRITE );
40836    assert( pBt->nTransaction>0 );
40837    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
40838    if( rc!=SQLITE_OK ){
40839      sqlite3BtreeLeave(p);
40840      return rc;
40841    }
40842    pBt->inTransaction = TRANS_READ;
40843  }
40844
40845  btreeEndTransaction(p);
40846  sqlite3BtreeLeave(p);
40847  return SQLITE_OK;
40848}
40849
40850/*
40851** Do both phases of a commit.
40852*/
40853SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
40854  int rc;
40855  sqlite3BtreeEnter(p);
40856  rc = sqlite3BtreeCommitPhaseOne(p, 0);
40857  if( rc==SQLITE_OK ){
40858    rc = sqlite3BtreeCommitPhaseTwo(p);
40859  }
40860  sqlite3BtreeLeave(p);
40861  return rc;
40862}
40863
40864#ifndef NDEBUG
40865/*
40866** Return the number of write-cursors open on this handle. This is for use
40867** in assert() expressions, so it is only compiled if NDEBUG is not
40868** defined.
40869**
40870** For the purposes of this routine, a write-cursor is any cursor that
40871** is capable of writing to the databse.  That means the cursor was
40872** originally opened for writing and the cursor has not be disabled
40873** by having its state changed to CURSOR_FAULT.
40874*/
40875static int countWriteCursors(BtShared *pBt){
40876  BtCursor *pCur;
40877  int r = 0;
40878  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
40879    if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
40880  }
40881  return r;
40882}
40883#endif
40884
40885/*
40886** This routine sets the state to CURSOR_FAULT and the error
40887** code to errCode for every cursor on BtShared that pBtree
40888** references.
40889**
40890** Every cursor is tripped, including cursors that belong
40891** to other database connections that happen to be sharing
40892** the cache with pBtree.
40893**
40894** This routine gets called when a rollback occurs.
40895** All cursors using the same cache must be tripped
40896** to prevent them from trying to use the btree after
40897** the rollback.  The rollback may have deleted tables
40898** or moved root pages, so it is not sufficient to
40899** save the state of the cursor.  The cursor must be
40900** invalidated.
40901*/
40902SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
40903  BtCursor *p;
40904  sqlite3BtreeEnter(pBtree);
40905  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
40906    int i;
40907    sqlite3BtreeClearCursor(p);
40908    p->eState = CURSOR_FAULT;
40909    p->skipNext = errCode;
40910    for(i=0; i<=p->iPage; i++){
40911      releasePage(p->apPage[i]);
40912      p->apPage[i] = 0;
40913    }
40914  }
40915  sqlite3BtreeLeave(pBtree);
40916}
40917
40918/*
40919** Rollback the transaction in progress.  All cursors will be
40920** invalided by this operation.  Any attempt to use a cursor
40921** that was open at the beginning of this operation will result
40922** in an error.
40923**
40924** This will release the write lock on the database file.  If there
40925** are no active cursors, it also releases the read lock.
40926*/
40927SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
40928  int rc;
40929  BtShared *pBt = p->pBt;
40930  MemPage *pPage1;
40931
40932  sqlite3BtreeEnter(p);
40933  rc = saveAllCursors(pBt, 0, 0);
40934#ifndef SQLITE_OMIT_SHARED_CACHE
40935  if( rc!=SQLITE_OK ){
40936    /* This is a horrible situation. An IO or malloc() error occurred whilst
40937    ** trying to save cursor positions. If this is an automatic rollback (as
40938    ** the result of a constraint, malloc() failure or IO error) then
40939    ** the cache may be internally inconsistent (not contain valid trees) so
40940    ** we cannot simply return the error to the caller. Instead, abort
40941    ** all queries that may be using any of the cursors that failed to save.
40942    */
40943    sqlite3BtreeTripAllCursors(p, rc);
40944  }
40945#endif
40946  btreeIntegrity(p);
40947
40948  if( p->inTrans==TRANS_WRITE ){
40949    int rc2;
40950
40951    assert( TRANS_WRITE==pBt->inTransaction );
40952    rc2 = sqlite3PagerRollback(pBt->pPager);
40953    if( rc2!=SQLITE_OK ){
40954      rc = rc2;
40955    }
40956
40957    /* The rollback may have destroyed the pPage1->aData value.  So
40958    ** call btreeGetPage() on page 1 again to make
40959    ** sure pPage1->aData is set correctly. */
40960    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
40961      releasePage(pPage1);
40962    }
40963    assert( countWriteCursors(pBt)==0 );
40964    pBt->inTransaction = TRANS_READ;
40965  }
40966
40967  btreeEndTransaction(p);
40968  sqlite3BtreeLeave(p);
40969  return rc;
40970}
40971
40972/*
40973** Start a statement subtransaction. The subtransaction can can be rolled
40974** back independently of the main transaction. You must start a transaction
40975** before starting a subtransaction. The subtransaction is ended automatically
40976** if the main transaction commits or rolls back.
40977**
40978** Statement subtransactions are used around individual SQL statements
40979** that are contained within a BEGIN...COMMIT block.  If a constraint
40980** error occurs within the statement, the effect of that one statement
40981** can be rolled back without having to rollback the entire transaction.
40982**
40983** A statement sub-transaction is implemented as an anonymous savepoint. The
40984** value passed as the second parameter is the total number of savepoints,
40985** including the new anonymous savepoint, open on the B-Tree. i.e. if there
40986** are no active savepoints and no other statement-transactions open,
40987** iStatement is 1. This anonymous savepoint can be released or rolled back
40988** using the sqlite3BtreeSavepoint() function.
40989*/
40990SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
40991  int rc;
40992  BtShared *pBt = p->pBt;
40993  sqlite3BtreeEnter(p);
40994  assert( p->inTrans==TRANS_WRITE );
40995  assert( pBt->readOnly==0 );
40996  assert( iStatement>0 );
40997  assert( iStatement>p->db->nSavepoint );
40998  if( NEVER(p->inTrans!=TRANS_WRITE || pBt->readOnly) ){
40999    rc = SQLITE_INTERNAL;
41000  }else{
41001    assert( pBt->inTransaction==TRANS_WRITE );
41002    /* At the pager level, a statement transaction is a savepoint with
41003    ** an index greater than all savepoints created explicitly using
41004    ** SQL statements. It is illegal to open, release or rollback any
41005    ** such savepoints while the statement transaction savepoint is active.
41006    */
41007    rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
41008  }
41009  sqlite3BtreeLeave(p);
41010  return rc;
41011}
41012
41013/*
41014** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
41015** or SAVEPOINT_RELEASE. This function either releases or rolls back the
41016** savepoint identified by parameter iSavepoint, depending on the value
41017** of op.
41018**
41019** Normally, iSavepoint is greater than or equal to zero. However, if op is
41020** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
41021** contents of the entire transaction are rolled back. This is different
41022** from a normal transaction rollback, as no locks are released and the
41023** transaction remains open.
41024*/
41025SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
41026  int rc = SQLITE_OK;
41027  if( p && p->inTrans==TRANS_WRITE ){
41028    BtShared *pBt = p->pBt;
41029    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
41030    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
41031    sqlite3BtreeEnter(p);
41032    rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
41033    if( rc==SQLITE_OK ){
41034      rc = newDatabase(pBt);
41035    }
41036    sqlite3BtreeLeave(p);
41037  }
41038  return rc;
41039}
41040
41041/*
41042** Create a new cursor for the BTree whose root is on the page
41043** iTable. If a read-only cursor is requested, it is assumed that
41044** the caller already has at least a read-only transaction open
41045** on the database already. If a write-cursor is requested, then
41046** the caller is assumed to have an open write transaction.
41047**
41048** If wrFlag==0, then the cursor can only be used for reading.
41049** If wrFlag==1, then the cursor can be used for reading or for
41050** writing if other conditions for writing are also met.  These
41051** are the conditions that must be met in order for writing to
41052** be allowed:
41053**
41054** 1:  The cursor must have been opened with wrFlag==1
41055**
41056** 2:  Other database connections that share the same pager cache
41057**     but which are not in the READ_UNCOMMITTED state may not have
41058**     cursors open with wrFlag==0 on the same table.  Otherwise
41059**     the changes made by this write cursor would be visible to
41060**     the read cursors in the other database connection.
41061**
41062** 3:  The database must be writable (not on read-only media)
41063**
41064** 4:  There must be an active transaction.
41065**
41066** No checking is done to make sure that page iTable really is the
41067** root page of a b-tree.  If it is not, then the cursor acquired
41068** will not work correctly.
41069**
41070** It is assumed that the sqlite3BtreeCursorZero() has been called
41071** on pCur to initialize the memory space prior to invoking this routine.
41072*/
41073static int btreeCursor(
41074  Btree *p,                              /* The btree */
41075  int iTable,                            /* Root page of table to open */
41076  int wrFlag,                            /* 1 to write. 0 read-only */
41077  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
41078  BtCursor *pCur                         /* Space for new cursor */
41079){
41080  BtShared *pBt = p->pBt;                /* Shared b-tree handle */
41081
41082  assert( sqlite3BtreeHoldsMutex(p) );
41083  assert( wrFlag==0 || wrFlag==1 );
41084
41085  /* The following assert statements verify that if this is a sharable
41086  ** b-tree database, the connection is holding the required table locks,
41087  ** and that no other connection has any open cursor that conflicts with
41088  ** this lock.  */
41089  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
41090  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
41091
41092  /* Assert that the caller has opened the required transaction. */
41093  assert( p->inTrans>TRANS_NONE );
41094  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
41095  assert( pBt->pPage1 && pBt->pPage1->aData );
41096
41097  if( NEVER(wrFlag && pBt->readOnly) ){
41098    return SQLITE_READONLY;
41099  }
41100  if( iTable==1 && pagerPagecount(pBt)==0 ){
41101    return SQLITE_EMPTY;
41102  }
41103
41104  /* Now that no other errors can occur, finish filling in the BtCursor
41105  ** variables and link the cursor into the BtShared list.  */
41106  pCur->pgnoRoot = (Pgno)iTable;
41107  pCur->iPage = -1;
41108  pCur->pKeyInfo = pKeyInfo;
41109  pCur->pBtree = p;
41110  pCur->pBt = pBt;
41111  pCur->wrFlag = (u8)wrFlag;
41112  pCur->pNext = pBt->pCursor;
41113  if( pCur->pNext ){
41114    pCur->pNext->pPrev = pCur;
41115  }
41116  pBt->pCursor = pCur;
41117  pCur->eState = CURSOR_INVALID;
41118  pCur->cachedRowid = 0;
41119  return SQLITE_OK;
41120}
41121SQLITE_PRIVATE int sqlite3BtreeCursor(
41122  Btree *p,                                   /* The btree */
41123  int iTable,                                 /* Root page of table to open */
41124  int wrFlag,                                 /* 1 to write. 0 read-only */
41125  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
41126  BtCursor *pCur                              /* Write new cursor here */
41127){
41128  int rc;
41129  sqlite3BtreeEnter(p);
41130  rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
41131  sqlite3BtreeLeave(p);
41132  return rc;
41133}
41134
41135/*
41136** Return the size of a BtCursor object in bytes.
41137**
41138** This interfaces is needed so that users of cursors can preallocate
41139** sufficient storage to hold a cursor.  The BtCursor object is opaque
41140** to users so they cannot do the sizeof() themselves - they must call
41141** this routine.
41142*/
41143SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
41144  return ROUND8(sizeof(BtCursor));
41145}
41146
41147/*
41148** Initialize memory that will be converted into a BtCursor object.
41149**
41150** The simple approach here would be to memset() the entire object
41151** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
41152** do not need to be zeroed and they are large, so we can save a lot
41153** of run-time by skipping the initialization of those elements.
41154*/
41155SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
41156  memset(p, 0, offsetof(BtCursor, iPage));
41157}
41158
41159/*
41160** Set the cached rowid value of every cursor in the same database file
41161** as pCur and having the same root page number as pCur.  The value is
41162** set to iRowid.
41163**
41164** Only positive rowid values are considered valid for this cache.
41165** The cache is initialized to zero, indicating an invalid cache.
41166** A btree will work fine with zero or negative rowids.  We just cannot
41167** cache zero or negative rowids, which means tables that use zero or
41168** negative rowids might run a little slower.  But in practice, zero
41169** or negative rowids are very uncommon so this should not be a problem.
41170*/
41171SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
41172  BtCursor *p;
41173  for(p=pCur->pBt->pCursor; p; p=p->pNext){
41174    if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
41175  }
41176  assert( pCur->cachedRowid==iRowid );
41177}
41178
41179/*
41180** Return the cached rowid for the given cursor.  A negative or zero
41181** return value indicates that the rowid cache is invalid and should be
41182** ignored.  If the rowid cache has never before been set, then a
41183** zero is returned.
41184*/
41185SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
41186  return pCur->cachedRowid;
41187}
41188
41189/*
41190** Close a cursor.  The read lock on the database file is released
41191** when the last cursor is closed.
41192*/
41193SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
41194  Btree *pBtree = pCur->pBtree;
41195  if( pBtree ){
41196    int i;
41197    BtShared *pBt = pCur->pBt;
41198    sqlite3BtreeEnter(pBtree);
41199    sqlite3BtreeClearCursor(pCur);
41200    if( pCur->pPrev ){
41201      pCur->pPrev->pNext = pCur->pNext;
41202    }else{
41203      pBt->pCursor = pCur->pNext;
41204    }
41205    if( pCur->pNext ){
41206      pCur->pNext->pPrev = pCur->pPrev;
41207    }
41208    for(i=0; i<=pCur->iPage; i++){
41209      releasePage(pCur->apPage[i]);
41210    }
41211    unlockBtreeIfUnused(pBt);
41212    invalidateOverflowCache(pCur);
41213    /* sqlite3_free(pCur); */
41214    sqlite3BtreeLeave(pBtree);
41215  }
41216  return SQLITE_OK;
41217}
41218
41219/*
41220** Make sure the BtCursor* given in the argument has a valid
41221** BtCursor.info structure.  If it is not already valid, call
41222** btreeParseCell() to fill it in.
41223**
41224** BtCursor.info is a cache of the information in the current cell.
41225** Using this cache reduces the number of calls to btreeParseCell().
41226**
41227** 2007-06-25:  There is a bug in some versions of MSVC that cause the
41228** compiler to crash when getCellInfo() is implemented as a macro.
41229** But there is a measureable speed advantage to using the macro on gcc
41230** (when less compiler optimizations like -Os or -O0 are used and the
41231** compiler is not doing agressive inlining.)  So we use a real function
41232** for MSVC and a macro for everything else.  Ticket #2457.
41233*/
41234#ifndef NDEBUG
41235  static void assertCellInfo(BtCursor *pCur){
41236    CellInfo info;
41237    int iPage = pCur->iPage;
41238    memset(&info, 0, sizeof(info));
41239    btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
41240    assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
41241  }
41242#else
41243  #define assertCellInfo(x)
41244#endif
41245#ifdef _MSC_VER
41246  /* Use a real function in MSVC to work around bugs in that compiler. */
41247  static void getCellInfo(BtCursor *pCur){
41248    if( pCur->info.nSize==0 ){
41249      int iPage = pCur->iPage;
41250      btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
41251      pCur->validNKey = 1;
41252    }else{
41253      assertCellInfo(pCur);
41254    }
41255  }
41256#else /* if not _MSC_VER */
41257  /* Use a macro in all other compilers so that the function is inlined */
41258#define getCellInfo(pCur)                                                      \
41259  if( pCur->info.nSize==0 ){                                                   \
41260    int iPage = pCur->iPage;                                                   \
41261    btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
41262    pCur->validNKey = 1;                                                       \
41263  }else{                                                                       \
41264    assertCellInfo(pCur);                                                      \
41265  }
41266#endif /* _MSC_VER */
41267
41268#ifndef NDEBUG  /* The next routine used only within assert() statements */
41269/*
41270** Return true if the given BtCursor is valid.  A valid cursor is one
41271** that is currently pointing to a row in a (non-empty) table.
41272** This is a verification routine is used only within assert() statements.
41273*/
41274SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
41275  return pCur && pCur->eState==CURSOR_VALID;
41276}
41277#endif /* NDEBUG */
41278
41279/*
41280** Set *pSize to the size of the buffer needed to hold the value of
41281** the key for the current entry.  If the cursor is not pointing
41282** to a valid entry, *pSize is set to 0.
41283**
41284** For a table with the INTKEY flag set, this routine returns the key
41285** itself, not the number of bytes in the key.
41286**
41287** The caller must position the cursor prior to invoking this routine.
41288**
41289** This routine cannot fail.  It always returns SQLITE_OK.
41290*/
41291SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
41292  assert( cursorHoldsMutex(pCur) );
41293  assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
41294  if( pCur->eState!=CURSOR_VALID ){
41295    *pSize = 0;
41296  }else{
41297    getCellInfo(pCur);
41298    *pSize = pCur->info.nKey;
41299  }
41300  return SQLITE_OK;
41301}
41302
41303/*
41304** Set *pSize to the number of bytes of data in the entry the
41305** cursor currently points to.
41306**
41307** The caller must guarantee that the cursor is pointing to a non-NULL
41308** valid entry.  In other words, the calling procedure must guarantee
41309** that the cursor has Cursor.eState==CURSOR_VALID.
41310**
41311** Failure is not possible.  This function always returns SQLITE_OK.
41312** It might just as well be a procedure (returning void) but we continue
41313** to return an integer result code for historical reasons.
41314*/
41315SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
41316  assert( cursorHoldsMutex(pCur) );
41317  assert( pCur->eState==CURSOR_VALID );
41318  getCellInfo(pCur);
41319  *pSize = pCur->info.nData;
41320  return SQLITE_OK;
41321}
41322
41323/*
41324** Given the page number of an overflow page in the database (parameter
41325** ovfl), this function finds the page number of the next page in the
41326** linked list of overflow pages. If possible, it uses the auto-vacuum
41327** pointer-map data instead of reading the content of page ovfl to do so.
41328**
41329** If an error occurs an SQLite error code is returned. Otherwise:
41330**
41331** The page number of the next overflow page in the linked list is
41332** written to *pPgnoNext. If page ovfl is the last page in its linked
41333** list, *pPgnoNext is set to zero.
41334**
41335** If ppPage is not NULL, and a reference to the MemPage object corresponding
41336** to page number pOvfl was obtained, then *ppPage is set to point to that
41337** reference. It is the responsibility of the caller to call releasePage()
41338** on *ppPage to free the reference. In no reference was obtained (because
41339** the pointer-map was used to obtain the value for *pPgnoNext), then
41340** *ppPage is set to zero.
41341*/
41342static int getOverflowPage(
41343  BtShared *pBt,               /* The database file */
41344  Pgno ovfl,                   /* Current overflow page number */
41345  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
41346  Pgno *pPgnoNext              /* OUT: Next overflow page number */
41347){
41348  Pgno next = 0;
41349  MemPage *pPage = 0;
41350  int rc = SQLITE_OK;
41351
41352  assert( sqlite3_mutex_held(pBt->mutex) );
41353  assert(pPgnoNext);
41354
41355#ifndef SQLITE_OMIT_AUTOVACUUM
41356  /* Try to find the next page in the overflow list using the
41357  ** autovacuum pointer-map pages. Guess that the next page in
41358  ** the overflow list is page number (ovfl+1). If that guess turns
41359  ** out to be wrong, fall back to loading the data of page
41360  ** number ovfl to determine the next page number.
41361  */
41362  if( pBt->autoVacuum ){
41363    Pgno pgno;
41364    Pgno iGuess = ovfl+1;
41365    u8 eType;
41366
41367    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
41368      iGuess++;
41369    }
41370
41371    if( iGuess<=pagerPagecount(pBt) ){
41372      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
41373      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
41374        next = iGuess;
41375        rc = SQLITE_DONE;
41376      }
41377    }
41378  }
41379#endif
41380
41381  assert( next==0 || rc==SQLITE_DONE );
41382  if( rc==SQLITE_OK ){
41383    rc = btreeGetPage(pBt, ovfl, &pPage, 0);
41384    assert( rc==SQLITE_OK || pPage==0 );
41385    if( rc==SQLITE_OK ){
41386      next = get4byte(pPage->aData);
41387    }
41388  }
41389
41390  *pPgnoNext = next;
41391  if( ppPage ){
41392    *ppPage = pPage;
41393  }else{
41394    releasePage(pPage);
41395  }
41396  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
41397}
41398
41399/*
41400** Copy data from a buffer to a page, or from a page to a buffer.
41401**
41402** pPayload is a pointer to data stored on database page pDbPage.
41403** If argument eOp is false, then nByte bytes of data are copied
41404** from pPayload to the buffer pointed at by pBuf. If eOp is true,
41405** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
41406** of data are copied from the buffer pBuf to pPayload.
41407**
41408** SQLITE_OK is returned on success, otherwise an error code.
41409*/
41410static int copyPayload(
41411  void *pPayload,           /* Pointer to page data */
41412  void *pBuf,               /* Pointer to buffer */
41413  int nByte,                /* Number of bytes to copy */
41414  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
41415  DbPage *pDbPage           /* Page containing pPayload */
41416){
41417  if( eOp ){
41418    /* Copy data from buffer to page (a write operation) */
41419    int rc = sqlite3PagerWrite(pDbPage);
41420    if( rc!=SQLITE_OK ){
41421      return rc;
41422    }
41423    memcpy(pPayload, pBuf, nByte);
41424  }else{
41425    /* Copy data from page to buffer (a read operation) */
41426    memcpy(pBuf, pPayload, nByte);
41427  }
41428  return SQLITE_OK;
41429}
41430
41431/*
41432** This function is used to read or overwrite payload information
41433** for the entry that the pCur cursor is pointing to. If the eOp
41434** parameter is 0, this is a read operation (data copied into
41435** buffer pBuf). If it is non-zero, a write (data copied from
41436** buffer pBuf).
41437**
41438** A total of "amt" bytes are read or written beginning at "offset".
41439** Data is read to or from the buffer pBuf.
41440**
41441** The content being read or written might appear on the main page
41442** or be scattered out on multiple overflow pages.
41443**
41444** If the BtCursor.isIncrblobHandle flag is set, and the current
41445** cursor entry uses one or more overflow pages, this function
41446** allocates space for and lazily popluates the overflow page-list
41447** cache array (BtCursor.aOverflow). Subsequent calls use this
41448** cache to make seeking to the supplied offset more efficient.
41449**
41450** Once an overflow page-list cache has been allocated, it may be
41451** invalidated if some other cursor writes to the same table, or if
41452** the cursor is moved to a different row. Additionally, in auto-vacuum
41453** mode, the following events may invalidate an overflow page-list cache.
41454**
41455**   * An incremental vacuum,
41456**   * A commit in auto_vacuum="full" mode,
41457**   * Creating a table (may require moving an overflow page).
41458*/
41459static int accessPayload(
41460  BtCursor *pCur,      /* Cursor pointing to entry to read from */
41461  u32 offset,          /* Begin reading this far into payload */
41462  u32 amt,             /* Read this many bytes */
41463  unsigned char *pBuf, /* Write the bytes into this buffer */
41464  int eOp              /* zero to read. non-zero to write. */
41465){
41466  unsigned char *aPayload;
41467  int rc = SQLITE_OK;
41468  u32 nKey;
41469  int iIdx = 0;
41470  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
41471  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
41472
41473  assert( pPage );
41474  assert( pCur->eState==CURSOR_VALID );
41475  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
41476  assert( cursorHoldsMutex(pCur) );
41477
41478  getCellInfo(pCur);
41479  aPayload = pCur->info.pCell + pCur->info.nHeader;
41480  nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
41481
41482  if( NEVER(offset+amt > nKey+pCur->info.nData)
41483   || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
41484  ){
41485    /* Trying to read or write past the end of the data is an error */
41486    return SQLITE_CORRUPT_BKPT;
41487  }
41488
41489  /* Check if data must be read/written to/from the btree page itself. */
41490  if( offset<pCur->info.nLocal ){
41491    int a = amt;
41492    if( a+offset>pCur->info.nLocal ){
41493      a = pCur->info.nLocal - offset;
41494    }
41495    rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
41496    offset = 0;
41497    pBuf += a;
41498    amt -= a;
41499  }else{
41500    offset -= pCur->info.nLocal;
41501  }
41502
41503  if( rc==SQLITE_OK && amt>0 ){
41504    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
41505    Pgno nextPage;
41506
41507    nextPage = get4byte(&aPayload[pCur->info.nLocal]);
41508
41509#ifndef SQLITE_OMIT_INCRBLOB
41510    /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
41511    ** has not been allocated, allocate it now. The array is sized at
41512    ** one entry for each overflow page in the overflow chain. The
41513    ** page number of the first overflow page is stored in aOverflow[0],
41514    ** etc. A value of 0 in the aOverflow[] array means "not yet known"
41515    ** (the cache is lazily populated).
41516    */
41517    if( pCur->isIncrblobHandle && !pCur->aOverflow ){
41518      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
41519      pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
41520      /* nOvfl is always positive.  If it were zero, fetchPayload would have
41521      ** been used instead of this routine. */
41522      if( ALWAYS(nOvfl) && !pCur->aOverflow ){
41523        rc = SQLITE_NOMEM;
41524      }
41525    }
41526
41527    /* If the overflow page-list cache has been allocated and the
41528    ** entry for the first required overflow page is valid, skip
41529    ** directly to it.
41530    */
41531    if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
41532      iIdx = (offset/ovflSize);
41533      nextPage = pCur->aOverflow[iIdx];
41534      offset = (offset%ovflSize);
41535    }
41536#endif
41537
41538    for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
41539
41540#ifndef SQLITE_OMIT_INCRBLOB
41541      /* If required, populate the overflow page-list cache. */
41542      if( pCur->aOverflow ){
41543        assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
41544        pCur->aOverflow[iIdx] = nextPage;
41545      }
41546#endif
41547
41548      if( offset>=ovflSize ){
41549        /* The only reason to read this page is to obtain the page
41550        ** number for the next page in the overflow chain. The page
41551        ** data is not required. So first try to lookup the overflow
41552        ** page-list cache, if any, then fall back to the getOverflowPage()
41553        ** function.
41554        */
41555#ifndef SQLITE_OMIT_INCRBLOB
41556        if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
41557          nextPage = pCur->aOverflow[iIdx+1];
41558        } else
41559#endif
41560          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
41561        offset -= ovflSize;
41562      }else{
41563        /* Need to read this page properly. It contains some of the
41564        ** range of data that is being read (eOp==0) or written (eOp!=0).
41565        */
41566        DbPage *pDbPage;
41567        int a = amt;
41568        rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
41569        if( rc==SQLITE_OK ){
41570          aPayload = sqlite3PagerGetData(pDbPage);
41571          nextPage = get4byte(aPayload);
41572          if( a + offset > ovflSize ){
41573            a = ovflSize - offset;
41574          }
41575          rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
41576          sqlite3PagerUnref(pDbPage);
41577          offset = 0;
41578          amt -= a;
41579          pBuf += a;
41580        }
41581      }
41582    }
41583  }
41584
41585  if( rc==SQLITE_OK && amt>0 ){
41586    return SQLITE_CORRUPT_BKPT;
41587  }
41588  return rc;
41589}
41590
41591/*
41592** Read part of the key associated with cursor pCur.  Exactly
41593** "amt" bytes will be transfered into pBuf[].  The transfer
41594** begins at "offset".
41595**
41596** The caller must ensure that pCur is pointing to a valid row
41597** in the table.
41598**
41599** Return SQLITE_OK on success or an error code if anything goes
41600** wrong.  An error is returned if "offset+amt" is larger than
41601** the available payload.
41602*/
41603SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
41604  assert( cursorHoldsMutex(pCur) );
41605  assert( pCur->eState==CURSOR_VALID );
41606  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
41607  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
41608  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
41609}
41610
41611/*
41612** Read part of the data associated with cursor pCur.  Exactly
41613** "amt" bytes will be transfered into pBuf[].  The transfer
41614** begins at "offset".
41615**
41616** Return SQLITE_OK on success or an error code if anything goes
41617** wrong.  An error is returned if "offset+amt" is larger than
41618** the available payload.
41619*/
41620SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
41621  int rc;
41622
41623#ifndef SQLITE_OMIT_INCRBLOB
41624  if ( pCur->eState==CURSOR_INVALID ){
41625    return SQLITE_ABORT;
41626  }
41627#endif
41628
41629  assert( cursorHoldsMutex(pCur) );
41630  rc = restoreCursorPosition(pCur);
41631  if( rc==SQLITE_OK ){
41632    assert( pCur->eState==CURSOR_VALID );
41633    assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
41634    assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
41635    rc = accessPayload(pCur, offset, amt, pBuf, 0);
41636  }
41637  return rc;
41638}
41639
41640/*
41641** Return a pointer to payload information from the entry that the
41642** pCur cursor is pointing to.  The pointer is to the beginning of
41643** the key if skipKey==0 and it points to the beginning of data if
41644** skipKey==1.  The number of bytes of available key/data is written
41645** into *pAmt.  If *pAmt==0, then the value returned will not be
41646** a valid pointer.
41647**
41648** This routine is an optimization.  It is common for the entire key
41649** and data to fit on the local page and for there to be no overflow
41650** pages.  When that is so, this routine can be used to access the
41651** key and data without making a copy.  If the key and/or data spills
41652** onto overflow pages, then accessPayload() must be used to reassemble
41653** the key/data and copy it into a preallocated buffer.
41654**
41655** The pointer returned by this routine looks directly into the cached
41656** page of the database.  The data might change or move the next time
41657** any btree routine is called.
41658*/
41659static const unsigned char *fetchPayload(
41660  BtCursor *pCur,      /* Cursor pointing to entry to read from */
41661  int *pAmt,           /* Write the number of available bytes here */
41662  int skipKey          /* read beginning at data if this is true */
41663){
41664  unsigned char *aPayload;
41665  MemPage *pPage;
41666  u32 nKey;
41667  u32 nLocal;
41668
41669  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
41670  assert( pCur->eState==CURSOR_VALID );
41671  assert( cursorHoldsMutex(pCur) );
41672  pPage = pCur->apPage[pCur->iPage];
41673  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
41674  if( NEVER(pCur->info.nSize==0) ){
41675    btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
41676                   &pCur->info);
41677  }
41678  aPayload = pCur->info.pCell;
41679  aPayload += pCur->info.nHeader;
41680  if( pPage->intKey ){
41681    nKey = 0;
41682  }else{
41683    nKey = (int)pCur->info.nKey;
41684  }
41685  if( skipKey ){
41686    aPayload += nKey;
41687    nLocal = pCur->info.nLocal - nKey;
41688  }else{
41689    nLocal = pCur->info.nLocal;
41690    assert( nLocal<=nKey );
41691  }
41692  *pAmt = nLocal;
41693  return aPayload;
41694}
41695
41696
41697/*
41698** For the entry that cursor pCur is point to, return as
41699** many bytes of the key or data as are available on the local
41700** b-tree page.  Write the number of available bytes into *pAmt.
41701**
41702** The pointer returned is ephemeral.  The key/data may move
41703** or be destroyed on the next call to any Btree routine,
41704** including calls from other threads against the same cache.
41705** Hence, a mutex on the BtShared should be held prior to calling
41706** this routine.
41707**
41708** These routines is used to get quick access to key and data
41709** in the common case where no overflow pages are used.
41710*/
41711SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
41712  const void *p = 0;
41713  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41714  assert( cursorHoldsMutex(pCur) );
41715  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
41716    p = (const void*)fetchPayload(pCur, pAmt, 0);
41717  }
41718  return p;
41719}
41720SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
41721  const void *p = 0;
41722  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41723  assert( cursorHoldsMutex(pCur) );
41724  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
41725    p = (const void*)fetchPayload(pCur, pAmt, 1);
41726  }
41727  return p;
41728}
41729
41730
41731/*
41732** Move the cursor down to a new child page.  The newPgno argument is the
41733** page number of the child page to move to.
41734**
41735** This function returns SQLITE_CORRUPT if the page-header flags field of
41736** the new child page does not match the flags field of the parent (i.e.
41737** if an intkey page appears to be the parent of a non-intkey page, or
41738** vice-versa).
41739*/
41740static int moveToChild(BtCursor *pCur, u32 newPgno){
41741  int rc;
41742  int i = pCur->iPage;
41743  MemPage *pNewPage;
41744  BtShared *pBt = pCur->pBt;
41745
41746  assert( cursorHoldsMutex(pCur) );
41747  assert( pCur->eState==CURSOR_VALID );
41748  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
41749  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
41750    return SQLITE_CORRUPT_BKPT;
41751  }
41752  rc = getAndInitPage(pBt, newPgno, &pNewPage);
41753  if( rc ) return rc;
41754  pCur->apPage[i+1] = pNewPage;
41755  pCur->aiIdx[i+1] = 0;
41756  pCur->iPage++;
41757
41758  pCur->info.nSize = 0;
41759  pCur->validNKey = 0;
41760  if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
41761    return SQLITE_CORRUPT_BKPT;
41762  }
41763  return SQLITE_OK;
41764}
41765
41766#ifndef NDEBUG
41767/*
41768** Page pParent is an internal (non-leaf) tree page. This function
41769** asserts that page number iChild is the left-child if the iIdx'th
41770** cell in page pParent. Or, if iIdx is equal to the total number of
41771** cells in pParent, that page number iChild is the right-child of
41772** the page.
41773*/
41774static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
41775  assert( iIdx<=pParent->nCell );
41776  if( iIdx==pParent->nCell ){
41777    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
41778  }else{
41779    assert( get4byte(findCell(pParent, iIdx))==iChild );
41780  }
41781}
41782#else
41783#  define assertParentIndex(x,y,z)
41784#endif
41785
41786/*
41787** Move the cursor up to the parent page.
41788**
41789** pCur->idx is set to the cell index that contains the pointer
41790** to the page we are coming from.  If we are coming from the
41791** right-most child page then pCur->idx is set to one more than
41792** the largest cell index.
41793*/
41794static void moveToParent(BtCursor *pCur){
41795  assert( cursorHoldsMutex(pCur) );
41796  assert( pCur->eState==CURSOR_VALID );
41797  assert( pCur->iPage>0 );
41798  assert( pCur->apPage[pCur->iPage] );
41799  assertParentIndex(
41800    pCur->apPage[pCur->iPage-1],
41801    pCur->aiIdx[pCur->iPage-1],
41802    pCur->apPage[pCur->iPage]->pgno
41803  );
41804  releasePage(pCur->apPage[pCur->iPage]);
41805  pCur->iPage--;
41806  pCur->info.nSize = 0;
41807  pCur->validNKey = 0;
41808}
41809
41810/*
41811** Move the cursor to point to the root page of its b-tree structure.
41812**
41813** If the table has a virtual root page, then the cursor is moved to point
41814** to the virtual root page instead of the actual root page. A table has a
41815** virtual root page when the actual root page contains no cells and a
41816** single child page. This can only happen with the table rooted at page 1.
41817**
41818** If the b-tree structure is empty, the cursor state is set to
41819** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
41820** cell located on the root (or virtual root) page and the cursor state
41821** is set to CURSOR_VALID.
41822**
41823** If this function returns successfully, it may be assumed that the
41824** page-header flags indicate that the [virtual] root-page is the expected
41825** kind of b-tree page (i.e. if when opening the cursor the caller did not
41826** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
41827** indicating a table b-tree, or if the caller did specify a KeyInfo
41828** structure the flags byte is set to 0x02 or 0x0A, indicating an index
41829** b-tree).
41830*/
41831static int moveToRoot(BtCursor *pCur){
41832  MemPage *pRoot;
41833  int rc = SQLITE_OK;
41834  Btree *p = pCur->pBtree;
41835  BtShared *pBt = p->pBt;
41836
41837  assert( cursorHoldsMutex(pCur) );
41838  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
41839  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
41840  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
41841  if( pCur->eState>=CURSOR_REQUIRESEEK ){
41842    if( pCur->eState==CURSOR_FAULT ){
41843      assert( pCur->skipNext!=SQLITE_OK );
41844      return pCur->skipNext;
41845    }
41846    sqlite3BtreeClearCursor(pCur);
41847  }
41848
41849  if( pCur->iPage>=0 ){
41850    int i;
41851    for(i=1; i<=pCur->iPage; i++){
41852      releasePage(pCur->apPage[i]);
41853    }
41854    pCur->iPage = 0;
41855  }else{
41856    rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
41857    if( rc!=SQLITE_OK ){
41858      pCur->eState = CURSOR_INVALID;
41859      return rc;
41860    }
41861    pCur->iPage = 0;
41862
41863    /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
41864    ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
41865    ** NULL, the caller expects a table b-tree. If this is not the case,
41866    ** return an SQLITE_CORRUPT error.  */
41867    assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
41868    if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
41869      return SQLITE_CORRUPT_BKPT;
41870    }
41871  }
41872
41873  /* Assert that the root page is of the correct type. This must be the
41874  ** case as the call to this function that loaded the root-page (either
41875  ** this call or a previous invocation) would have detected corruption
41876  ** if the assumption were not true, and it is not possible for the flags
41877  ** byte to have been modified while this cursor is holding a reference
41878  ** to the page.  */
41879  pRoot = pCur->apPage[0];
41880  assert( pRoot->pgno==pCur->pgnoRoot );
41881  assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
41882
41883  pCur->aiIdx[0] = 0;
41884  pCur->info.nSize = 0;
41885  pCur->atLast = 0;
41886  pCur->validNKey = 0;
41887
41888  if( pRoot->nCell==0 && !pRoot->leaf ){
41889    Pgno subpage;
41890    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
41891    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
41892    pCur->eState = CURSOR_VALID;
41893    rc = moveToChild(pCur, subpage);
41894  }else{
41895    pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
41896  }
41897  return rc;
41898}
41899
41900/*
41901** Move the cursor down to the left-most leaf entry beneath the
41902** entry to which it is currently pointing.
41903**
41904** The left-most leaf is the one with the smallest key - the first
41905** in ascending order.
41906*/
41907static int moveToLeftmost(BtCursor *pCur){
41908  Pgno pgno;
41909  int rc = SQLITE_OK;
41910  MemPage *pPage;
41911
41912  assert( cursorHoldsMutex(pCur) );
41913  assert( pCur->eState==CURSOR_VALID );
41914  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
41915    assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
41916    pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
41917    rc = moveToChild(pCur, pgno);
41918  }
41919  return rc;
41920}
41921
41922/*
41923** Move the cursor down to the right-most leaf entry beneath the
41924** page to which it is currently pointing.  Notice the difference
41925** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
41926** finds the left-most entry beneath the *entry* whereas moveToRightmost()
41927** finds the right-most entry beneath the *page*.
41928**
41929** The right-most entry is the one with the largest key - the last
41930** key in ascending order.
41931*/
41932static int moveToRightmost(BtCursor *pCur){
41933  Pgno pgno;
41934  int rc = SQLITE_OK;
41935  MemPage *pPage = 0;
41936
41937  assert( cursorHoldsMutex(pCur) );
41938  assert( pCur->eState==CURSOR_VALID );
41939  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
41940    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
41941    pCur->aiIdx[pCur->iPage] = pPage->nCell;
41942    rc = moveToChild(pCur, pgno);
41943  }
41944  if( rc==SQLITE_OK ){
41945    pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
41946    pCur->info.nSize = 0;
41947    pCur->validNKey = 0;
41948  }
41949  return rc;
41950}
41951
41952/* Move the cursor to the first entry in the table.  Return SQLITE_OK
41953** on success.  Set *pRes to 0 if the cursor actually points to something
41954** or set *pRes to 1 if the table is empty.
41955*/
41956SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
41957  int rc;
41958
41959  assert( cursorHoldsMutex(pCur) );
41960  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41961  rc = moveToRoot(pCur);
41962  if( rc==SQLITE_OK ){
41963    if( pCur->eState==CURSOR_INVALID ){
41964      assert( pCur->apPage[pCur->iPage]->nCell==0 );
41965      *pRes = 1;
41966      rc = SQLITE_OK;
41967    }else{
41968      assert( pCur->apPage[pCur->iPage]->nCell>0 );
41969      *pRes = 0;
41970      rc = moveToLeftmost(pCur);
41971    }
41972  }
41973  return rc;
41974}
41975
41976/* Move the cursor to the last entry in the table.  Return SQLITE_OK
41977** on success.  Set *pRes to 0 if the cursor actually points to something
41978** or set *pRes to 1 if the table is empty.
41979*/
41980SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
41981  int rc;
41982
41983  assert( cursorHoldsMutex(pCur) );
41984  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41985
41986  /* If the cursor already points to the last entry, this is a no-op. */
41987  if( CURSOR_VALID==pCur->eState && pCur->atLast ){
41988#ifdef SQLITE_DEBUG
41989    /* This block serves to assert() that the cursor really does point
41990    ** to the last entry in the b-tree. */
41991    int ii;
41992    for(ii=0; ii<pCur->iPage; ii++){
41993      assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
41994    }
41995    assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
41996    assert( pCur->apPage[pCur->iPage]->leaf );
41997#endif
41998    return SQLITE_OK;
41999  }
42000
42001  rc = moveToRoot(pCur);
42002  if( rc==SQLITE_OK ){
42003    if( CURSOR_INVALID==pCur->eState ){
42004      assert( pCur->apPage[pCur->iPage]->nCell==0 );
42005      *pRes = 1;
42006    }else{
42007      assert( pCur->eState==CURSOR_VALID );
42008      *pRes = 0;
42009      rc = moveToRightmost(pCur);
42010      pCur->atLast = rc==SQLITE_OK ?1:0;
42011    }
42012  }
42013  return rc;
42014}
42015
42016/* Move the cursor so that it points to an entry near the key
42017** specified by pIdxKey or intKey.   Return a success code.
42018**
42019** For INTKEY tables, the intKey parameter is used.  pIdxKey
42020** must be NULL.  For index tables, pIdxKey is used and intKey
42021** is ignored.
42022**
42023** If an exact match is not found, then the cursor is always
42024** left pointing at a leaf page which would hold the entry if it
42025** were present.  The cursor might point to an entry that comes
42026** before or after the key.
42027**
42028** An integer is written into *pRes which is the result of
42029** comparing the key with the entry to which the cursor is
42030** pointing.  The meaning of the integer written into
42031** *pRes is as follows:
42032**
42033**     *pRes<0      The cursor is left pointing at an entry that
42034**                  is smaller than intKey/pIdxKey or if the table is empty
42035**                  and the cursor is therefore left point to nothing.
42036**
42037**     *pRes==0     The cursor is left pointing at an entry that
42038**                  exactly matches intKey/pIdxKey.
42039**
42040**     *pRes>0      The cursor is left pointing at an entry that
42041**                  is larger than intKey/pIdxKey.
42042**
42043*/
42044SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
42045  BtCursor *pCur,          /* The cursor to be moved */
42046  UnpackedRecord *pIdxKey, /* Unpacked index key */
42047  i64 intKey,              /* The table key */
42048  int biasRight,           /* If true, bias the search to the high end */
42049  int *pRes                /* Write search results here */
42050){
42051  int rc;
42052
42053  assert( cursorHoldsMutex(pCur) );
42054  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
42055  assert( pRes );
42056  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
42057
42058  /* If the cursor is already positioned at the point we are trying
42059  ** to move to, then just return without doing any work */
42060  if( pCur->eState==CURSOR_VALID && pCur->validNKey
42061   && pCur->apPage[0]->intKey
42062  ){
42063    if( pCur->info.nKey==intKey ){
42064      *pRes = 0;
42065      return SQLITE_OK;
42066    }
42067    if( pCur->atLast && pCur->info.nKey<intKey ){
42068      *pRes = -1;
42069      return SQLITE_OK;
42070    }
42071  }
42072
42073  rc = moveToRoot(pCur);
42074  if( rc ){
42075    return rc;
42076  }
42077  assert( pCur->apPage[pCur->iPage] );
42078  assert( pCur->apPage[pCur->iPage]->isInit );
42079  assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
42080  if( pCur->eState==CURSOR_INVALID ){
42081    *pRes = -1;
42082    assert( pCur->apPage[pCur->iPage]->nCell==0 );
42083    return SQLITE_OK;
42084  }
42085  assert( pCur->apPage[0]->intKey || pIdxKey );
42086  for(;;){
42087    int lwr, upr;
42088    Pgno chldPg;
42089    MemPage *pPage = pCur->apPage[pCur->iPage];
42090    int c;
42091
42092    /* pPage->nCell must be greater than zero. If this is the root-page
42093    ** the cursor would have been INVALID above and this for(;;) loop
42094    ** not run. If this is not the root-page, then the moveToChild() routine
42095    ** would have already detected db corruption. Similarly, pPage must
42096    ** be the right kind (index or table) of b-tree page. Otherwise
42097    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
42098    assert( pPage->nCell>0 );
42099    assert( pPage->intKey==(pIdxKey==0) );
42100    lwr = 0;
42101    upr = pPage->nCell-1;
42102    if( biasRight ){
42103      pCur->aiIdx[pCur->iPage] = (u16)upr;
42104    }else{
42105      pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
42106    }
42107    for(;;){
42108      int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
42109      u8 *pCell;                          /* Pointer to current cell in pPage */
42110
42111      pCur->info.nSize = 0;
42112      pCell = findCell(pPage, idx) + pPage->childPtrSize;
42113      if( pPage->intKey ){
42114        i64 nCellKey;
42115        if( pPage->hasData ){
42116          u32 dummy;
42117          pCell += getVarint32(pCell, dummy);
42118        }
42119        getVarint(pCell, (u64*)&nCellKey);
42120        if( nCellKey==intKey ){
42121          c = 0;
42122        }else if( nCellKey<intKey ){
42123          c = -1;
42124        }else{
42125          assert( nCellKey>intKey );
42126          c = +1;
42127        }
42128        pCur->validNKey = 1;
42129        pCur->info.nKey = nCellKey;
42130      }else{
42131        /* The maximum supported page-size is 32768 bytes. This means that
42132        ** the maximum number of record bytes stored on an index B-Tree
42133        ** page is at most 8198 bytes, which may be stored as a 2-byte
42134        ** varint. This information is used to attempt to avoid parsing
42135        ** the entire cell by checking for the cases where the record is
42136        ** stored entirely within the b-tree page by inspecting the first
42137        ** 2 bytes of the cell.
42138        */
42139        int nCell = pCell[0];
42140        if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
42141          /* This branch runs if the record-size field of the cell is a
42142          ** single byte varint and the record fits entirely on the main
42143          ** b-tree page.  */
42144          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
42145        }else if( !(pCell[1] & 0x80)
42146          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
42147        ){
42148          /* The record-size field is a 2 byte varint and the record
42149          ** fits entirely on the main b-tree page.  */
42150          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
42151        }else{
42152          /* The record flows over onto one or more overflow pages. In
42153          ** this case the whole cell needs to be parsed, a buffer allocated
42154          ** and accessPayload() used to retrieve the record into the
42155          ** buffer before VdbeRecordCompare() can be called. */
42156          void *pCellKey;
42157          u8 * const pCellBody = pCell - pPage->childPtrSize;
42158          btreeParseCellPtr(pPage, pCellBody, &pCur->info);
42159          nCell = (int)pCur->info.nKey;
42160          pCellKey = sqlite3Malloc( nCell );
42161          if( pCellKey==0 ){
42162            rc = SQLITE_NOMEM;
42163            goto moveto_finish;
42164          }
42165          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
42166          if( rc ){
42167            sqlite3_free(pCellKey);
42168            goto moveto_finish;
42169          }
42170          c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
42171          sqlite3_free(pCellKey);
42172        }
42173      }
42174      if( c==0 ){
42175        if( pPage->intKey && !pPage->leaf ){
42176          lwr = idx;
42177          upr = lwr - 1;
42178          break;
42179        }else{
42180          *pRes = 0;
42181          rc = SQLITE_OK;
42182          goto moveto_finish;
42183        }
42184      }
42185      if( c<0 ){
42186        lwr = idx+1;
42187      }else{
42188        upr = idx-1;
42189      }
42190      if( lwr>upr ){
42191        break;
42192      }
42193      pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
42194    }
42195    assert( lwr==upr+1 );
42196    assert( pPage->isInit );
42197    if( pPage->leaf ){
42198      chldPg = 0;
42199    }else if( lwr>=pPage->nCell ){
42200      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
42201    }else{
42202      chldPg = get4byte(findCell(pPage, lwr));
42203    }
42204    if( chldPg==0 ){
42205      assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
42206      *pRes = c;
42207      rc = SQLITE_OK;
42208      goto moveto_finish;
42209    }
42210    pCur->aiIdx[pCur->iPage] = (u16)lwr;
42211    pCur->info.nSize = 0;
42212    pCur->validNKey = 0;
42213    rc = moveToChild(pCur, chldPg);
42214    if( rc ) goto moveto_finish;
42215  }
42216moveto_finish:
42217  return rc;
42218}
42219
42220
42221/*
42222** Return TRUE if the cursor is not pointing at an entry of the table.
42223**
42224** TRUE will be returned after a call to sqlite3BtreeNext() moves
42225** past the last entry in the table or sqlite3BtreePrev() moves past
42226** the first entry.  TRUE is also returned if the table is empty.
42227*/
42228SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
42229  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
42230  ** have been deleted? This API will need to change to return an error code
42231  ** as well as the boolean result value.
42232  */
42233  return (CURSOR_VALID!=pCur->eState);
42234}
42235
42236/*
42237** Advance the cursor to the next entry in the database.  If
42238** successful then set *pRes=0.  If the cursor
42239** was already pointing to the last entry in the database before
42240** this routine was called, then set *pRes=1.
42241*/
42242SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
42243  int rc;
42244  int idx;
42245  MemPage *pPage;
42246
42247  assert( cursorHoldsMutex(pCur) );
42248  rc = restoreCursorPosition(pCur);
42249  if( rc!=SQLITE_OK ){
42250    return rc;
42251  }
42252  assert( pRes!=0 );
42253  if( CURSOR_INVALID==pCur->eState ){
42254    *pRes = 1;
42255    return SQLITE_OK;
42256  }
42257  if( pCur->skipNext>0 ){
42258    pCur->skipNext = 0;
42259    *pRes = 0;
42260    return SQLITE_OK;
42261  }
42262  pCur->skipNext = 0;
42263
42264  pPage = pCur->apPage[pCur->iPage];
42265  idx = ++pCur->aiIdx[pCur->iPage];
42266  assert( pPage->isInit );
42267  assert( idx<=pPage->nCell );
42268
42269  pCur->info.nSize = 0;
42270  pCur->validNKey = 0;
42271  if( idx>=pPage->nCell ){
42272    if( !pPage->leaf ){
42273      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
42274      if( rc ) return rc;
42275      rc = moveToLeftmost(pCur);
42276      *pRes = 0;
42277      return rc;
42278    }
42279    do{
42280      if( pCur->iPage==0 ){
42281        *pRes = 1;
42282        pCur->eState = CURSOR_INVALID;
42283        return SQLITE_OK;
42284      }
42285      moveToParent(pCur);
42286      pPage = pCur->apPage[pCur->iPage];
42287    }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
42288    *pRes = 0;
42289    if( pPage->intKey ){
42290      rc = sqlite3BtreeNext(pCur, pRes);
42291    }else{
42292      rc = SQLITE_OK;
42293    }
42294    return rc;
42295  }
42296  *pRes = 0;
42297  if( pPage->leaf ){
42298    return SQLITE_OK;
42299  }
42300  rc = moveToLeftmost(pCur);
42301  return rc;
42302}
42303
42304
42305/*
42306** Step the cursor to the back to the previous entry in the database.  If
42307** successful then set *pRes=0.  If the cursor
42308** was already pointing to the first entry in the database before
42309** this routine was called, then set *pRes=1.
42310*/
42311SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
42312  int rc;
42313  MemPage *pPage;
42314
42315  assert( cursorHoldsMutex(pCur) );
42316  rc = restoreCursorPosition(pCur);
42317  if( rc!=SQLITE_OK ){
42318    return rc;
42319  }
42320  pCur->atLast = 0;
42321  if( CURSOR_INVALID==pCur->eState ){
42322    *pRes = 1;
42323    return SQLITE_OK;
42324  }
42325  if( pCur->skipNext<0 ){
42326    pCur->skipNext = 0;
42327    *pRes = 0;
42328    return SQLITE_OK;
42329  }
42330  pCur->skipNext = 0;
42331
42332  pPage = pCur->apPage[pCur->iPage];
42333  assert( pPage->isInit );
42334  if( !pPage->leaf ){
42335    int idx = pCur->aiIdx[pCur->iPage];
42336    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
42337    if( rc ){
42338      return rc;
42339    }
42340    rc = moveToRightmost(pCur);
42341  }else{
42342    while( pCur->aiIdx[pCur->iPage]==0 ){
42343      if( pCur->iPage==0 ){
42344        pCur->eState = CURSOR_INVALID;
42345        *pRes = 1;
42346        return SQLITE_OK;
42347      }
42348      moveToParent(pCur);
42349    }
42350    pCur->info.nSize = 0;
42351    pCur->validNKey = 0;
42352
42353    pCur->aiIdx[pCur->iPage]--;
42354    pPage = pCur->apPage[pCur->iPage];
42355    if( pPage->intKey && !pPage->leaf ){
42356      rc = sqlite3BtreePrevious(pCur, pRes);
42357    }else{
42358      rc = SQLITE_OK;
42359    }
42360  }
42361  *pRes = 0;
42362  return rc;
42363}
42364
42365/*
42366** Allocate a new page from the database file.
42367**
42368** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
42369** has already been called on the new page.)  The new page has also
42370** been referenced and the calling routine is responsible for calling
42371** sqlite3PagerUnref() on the new page when it is done.
42372**
42373** SQLITE_OK is returned on success.  Any other return value indicates
42374** an error.  *ppPage and *pPgno are undefined in the event of an error.
42375** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
42376**
42377** If the "nearby" parameter is not 0, then a (feeble) effort is made to
42378** locate a page close to the page number "nearby".  This can be used in an
42379** attempt to keep related pages close to each other in the database file,
42380** which in turn can make database access faster.
42381**
42382** If the "exact" parameter is not 0, and the page-number nearby exists
42383** anywhere on the free-list, then it is guarenteed to be returned. This
42384** is only used by auto-vacuum databases when allocating a new table.
42385*/
42386static int allocateBtreePage(
42387  BtShared *pBt,
42388  MemPage **ppPage,
42389  Pgno *pPgno,
42390  Pgno nearby,
42391  u8 exact
42392){
42393  MemPage *pPage1;
42394  int rc;
42395  u32 n;     /* Number of pages on the freelist */
42396  u32 k;     /* Number of leaves on the trunk of the freelist */
42397  MemPage *pTrunk = 0;
42398  MemPage *pPrevTrunk = 0;
42399  Pgno mxPage;     /* Total size of the database file */
42400
42401  assert( sqlite3_mutex_held(pBt->mutex) );
42402  pPage1 = pBt->pPage1;
42403  mxPage = pagerPagecount(pBt);
42404  n = get4byte(&pPage1->aData[36]);
42405  testcase( n==mxPage-1 );
42406  if( n>=mxPage ){
42407    return SQLITE_CORRUPT_BKPT;
42408  }
42409  if( n>0 ){
42410    /* There are pages on the freelist.  Reuse one of those pages. */
42411    Pgno iTrunk;
42412    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
42413
42414    /* If the 'exact' parameter was true and a query of the pointer-map
42415    ** shows that the page 'nearby' is somewhere on the free-list, then
42416    ** the entire-list will be searched for that page.
42417    */
42418#ifndef SQLITE_OMIT_AUTOVACUUM
42419    if( exact && nearby<=mxPage ){
42420      u8 eType;
42421      assert( nearby>0 );
42422      assert( pBt->autoVacuum );
42423      rc = ptrmapGet(pBt, nearby, &eType, 0);
42424      if( rc ) return rc;
42425      if( eType==PTRMAP_FREEPAGE ){
42426        searchList = 1;
42427      }
42428      *pPgno = nearby;
42429    }
42430#endif
42431
42432    /* Decrement the free-list count by 1. Set iTrunk to the index of the
42433    ** first free-list trunk page. iPrevTrunk is initially 1.
42434    */
42435    rc = sqlite3PagerWrite(pPage1->pDbPage);
42436    if( rc ) return rc;
42437    put4byte(&pPage1->aData[36], n-1);
42438
42439    /* The code within this loop is run only once if the 'searchList' variable
42440    ** is not true. Otherwise, it runs once for each trunk-page on the
42441    ** free-list until the page 'nearby' is located.
42442    */
42443    do {
42444      pPrevTrunk = pTrunk;
42445      if( pPrevTrunk ){
42446        iTrunk = get4byte(&pPrevTrunk->aData[0]);
42447      }else{
42448        iTrunk = get4byte(&pPage1->aData[32]);
42449      }
42450      testcase( iTrunk==mxPage );
42451      if( iTrunk>mxPage ){
42452        rc = SQLITE_CORRUPT_BKPT;
42453      }else{
42454        rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
42455      }
42456      if( rc ){
42457        pTrunk = 0;
42458        goto end_allocate_page;
42459      }
42460
42461      k = get4byte(&pTrunk->aData[4]);
42462      if( k==0 && !searchList ){
42463        /* The trunk has no leaves and the list is not being searched.
42464        ** So extract the trunk page itself and use it as the newly
42465        ** allocated page */
42466        assert( pPrevTrunk==0 );
42467        rc = sqlite3PagerWrite(pTrunk->pDbPage);
42468        if( rc ){
42469          goto end_allocate_page;
42470        }
42471        *pPgno = iTrunk;
42472        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
42473        *ppPage = pTrunk;
42474        pTrunk = 0;
42475        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
42476      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
42477        /* Value of k is out of range.  Database corruption */
42478        rc = SQLITE_CORRUPT_BKPT;
42479        goto end_allocate_page;
42480#ifndef SQLITE_OMIT_AUTOVACUUM
42481      }else if( searchList && nearby==iTrunk ){
42482        /* The list is being searched and this trunk page is the page
42483        ** to allocate, regardless of whether it has leaves.
42484        */
42485        assert( *pPgno==iTrunk );
42486        *ppPage = pTrunk;
42487        searchList = 0;
42488        rc = sqlite3PagerWrite(pTrunk->pDbPage);
42489        if( rc ){
42490          goto end_allocate_page;
42491        }
42492        if( k==0 ){
42493          if( !pPrevTrunk ){
42494            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
42495          }else{
42496            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
42497          }
42498        }else{
42499          /* The trunk page is required by the caller but it contains
42500          ** pointers to free-list leaves. The first leaf becomes a trunk
42501          ** page in this case.
42502          */
42503          MemPage *pNewTrunk;
42504          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
42505          if( iNewTrunk>mxPage ){
42506            rc = SQLITE_CORRUPT_BKPT;
42507            goto end_allocate_page;
42508          }
42509          testcase( iNewTrunk==mxPage );
42510          rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
42511          if( rc!=SQLITE_OK ){
42512            goto end_allocate_page;
42513          }
42514          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
42515          if( rc!=SQLITE_OK ){
42516            releasePage(pNewTrunk);
42517            goto end_allocate_page;
42518          }
42519          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
42520          put4byte(&pNewTrunk->aData[4], k-1);
42521          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
42522          releasePage(pNewTrunk);
42523          if( !pPrevTrunk ){
42524            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
42525            put4byte(&pPage1->aData[32], iNewTrunk);
42526          }else{
42527            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
42528            if( rc ){
42529              goto end_allocate_page;
42530            }
42531            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
42532          }
42533        }
42534        pTrunk = 0;
42535        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
42536#endif
42537      }else if( k>0 ){
42538        /* Extract a leaf from the trunk */
42539        u32 closest;
42540        Pgno iPage;
42541        unsigned char *aData = pTrunk->aData;
42542        rc = sqlite3PagerWrite(pTrunk->pDbPage);
42543        if( rc ){
42544          goto end_allocate_page;
42545        }
42546        if( nearby>0 ){
42547          u32 i;
42548          int dist;
42549          closest = 0;
42550          dist = get4byte(&aData[8]) - nearby;
42551          if( dist<0 ) dist = -dist;
42552          for(i=1; i<k; i++){
42553            int d2 = get4byte(&aData[8+i*4]) - nearby;
42554            if( d2<0 ) d2 = -d2;
42555            if( d2<dist ){
42556              closest = i;
42557              dist = d2;
42558            }
42559          }
42560        }else{
42561          closest = 0;
42562        }
42563
42564        iPage = get4byte(&aData[8+closest*4]);
42565        testcase( iPage==mxPage );
42566        if( iPage>mxPage ){
42567          rc = SQLITE_CORRUPT_BKPT;
42568          goto end_allocate_page;
42569        }
42570        testcase( iPage==mxPage );
42571        if( !searchList || iPage==nearby ){
42572          int noContent;
42573          *pPgno = iPage;
42574          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
42575                 ": %d more free pages\n",
42576                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
42577          if( closest<k-1 ){
42578            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
42579          }
42580          put4byte(&aData[4], k-1);
42581          assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
42582          noContent = !btreeGetHasContent(pBt, *pPgno);
42583          rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
42584          if( rc==SQLITE_OK ){
42585            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
42586            if( rc!=SQLITE_OK ){
42587              releasePage(*ppPage);
42588            }
42589          }
42590          searchList = 0;
42591        }
42592      }
42593      releasePage(pPrevTrunk);
42594      pPrevTrunk = 0;
42595    }while( searchList );
42596  }else{
42597    /* There are no pages on the freelist, so create a new page at the
42598    ** end of the file */
42599    int nPage = pagerPagecount(pBt);
42600    *pPgno = nPage + 1;
42601
42602    if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
42603      (*pPgno)++;
42604    }
42605
42606#ifndef SQLITE_OMIT_AUTOVACUUM
42607    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
42608      /* If *pPgno refers to a pointer-map page, allocate two new pages
42609      ** at the end of the file instead of one. The first allocated page
42610      ** becomes a new pointer-map page, the second is used by the caller.
42611      */
42612      MemPage *pPg = 0;
42613      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
42614      assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
42615      rc = btreeGetPage(pBt, *pPgno, &pPg, 0);
42616      if( rc==SQLITE_OK ){
42617        rc = sqlite3PagerWrite(pPg->pDbPage);
42618        releasePage(pPg);
42619      }
42620      if( rc ) return rc;
42621      (*pPgno)++;
42622      if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
42623    }
42624#endif
42625
42626    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
42627    rc = btreeGetPage(pBt, *pPgno, ppPage, 0);
42628    if( rc ) return rc;
42629    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
42630    if( rc!=SQLITE_OK ){
42631      releasePage(*ppPage);
42632    }
42633    TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
42634  }
42635
42636  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
42637
42638end_allocate_page:
42639  releasePage(pTrunk);
42640  releasePage(pPrevTrunk);
42641  if( rc==SQLITE_OK ){
42642    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
42643      releasePage(*ppPage);
42644      return SQLITE_CORRUPT_BKPT;
42645    }
42646    (*ppPage)->isInit = 0;
42647  }else{
42648    *ppPage = 0;
42649  }
42650  return rc;
42651}
42652
42653/*
42654** This function is used to add page iPage to the database file free-list.
42655** It is assumed that the page is not already a part of the free-list.
42656**
42657** The value passed as the second argument to this function is optional.
42658** If the caller happens to have a pointer to the MemPage object
42659** corresponding to page iPage handy, it may pass it as the second value.
42660** Otherwise, it may pass NULL.
42661**
42662** If a pointer to a MemPage object is passed as the second argument,
42663** its reference count is not altered by this function.
42664*/
42665static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
42666  MemPage *pTrunk = 0;                /* Free-list trunk page */
42667  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
42668  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
42669  MemPage *pPage;                     /* Page being freed. May be NULL. */
42670  int rc;                             /* Return Code */
42671  int nFree;                          /* Initial number of pages on free-list */
42672
42673  assert( sqlite3_mutex_held(pBt->mutex) );
42674  assert( iPage>1 );
42675  assert( !pMemPage || pMemPage->pgno==iPage );
42676
42677  if( pMemPage ){
42678    pPage = pMemPage;
42679    sqlite3PagerRef(pPage->pDbPage);
42680  }else{
42681    pPage = btreePageLookup(pBt, iPage);
42682  }
42683
42684  /* Increment the free page count on pPage1 */
42685  rc = sqlite3PagerWrite(pPage1->pDbPage);
42686  if( rc ) goto freepage_out;
42687  nFree = get4byte(&pPage1->aData[36]);
42688  put4byte(&pPage1->aData[36], nFree+1);
42689
42690#ifdef SQLITE_SECURE_DELETE
42691  /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
42692  ** always fully overwrite deleted information with zeros.
42693  */
42694  if( (!pPage && (rc = btreeGetPage(pBt, iPage, &pPage, 0)))
42695   ||            (rc = sqlite3PagerWrite(pPage->pDbPage))
42696  ){
42697    goto freepage_out;
42698  }
42699  memset(pPage->aData, 0, pPage->pBt->pageSize);
42700#endif
42701
42702  /* If the database supports auto-vacuum, write an entry in the pointer-map
42703  ** to indicate that the page is free.
42704  */
42705  if( ISAUTOVACUUM ){
42706    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
42707    if( rc ) goto freepage_out;
42708  }
42709
42710  /* Now manipulate the actual database free-list structure. There are two
42711  ** possibilities. If the free-list is currently empty, or if the first
42712  ** trunk page in the free-list is full, then this page will become a
42713  ** new free-list trunk page. Otherwise, it will become a leaf of the
42714  ** first trunk page in the current free-list. This block tests if it
42715  ** is possible to add the page as a new free-list leaf.
42716  */
42717  if( nFree!=0 ){
42718    u32 nLeaf;                /* Initial number of leaf cells on trunk page */
42719
42720    iTrunk = get4byte(&pPage1->aData[32]);
42721    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
42722    if( rc!=SQLITE_OK ){
42723      goto freepage_out;
42724    }
42725
42726    nLeaf = get4byte(&pTrunk->aData[4]);
42727    assert( pBt->usableSize>32 );
42728    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
42729      rc = SQLITE_CORRUPT_BKPT;
42730      goto freepage_out;
42731    }
42732    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
42733      /* In this case there is room on the trunk page to insert the page
42734      ** being freed as a new leaf.
42735      **
42736      ** Note that the trunk page is not really full until it contains
42737      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
42738      ** coded.  But due to a coding error in versions of SQLite prior to
42739      ** 3.6.0, databases with freelist trunk pages holding more than
42740      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
42741      ** to maintain backwards compatibility with older versions of SQLite,
42742      ** we will continue to restrict the number of entries to usableSize/4 - 8
42743      ** for now.  At some point in the future (once everyone has upgraded
42744      ** to 3.6.0 or later) we should consider fixing the conditional above
42745      ** to read "usableSize/4-2" instead of "usableSize/4-8".
42746      */
42747      rc = sqlite3PagerWrite(pTrunk->pDbPage);
42748      if( rc==SQLITE_OK ){
42749        put4byte(&pTrunk->aData[4], nLeaf+1);
42750        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
42751#ifndef SQLITE_SECURE_DELETE
42752        if( pPage ){
42753          sqlite3PagerDontWrite(pPage->pDbPage);
42754        }
42755#endif
42756        rc = btreeSetHasContent(pBt, iPage);
42757      }
42758      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
42759      goto freepage_out;
42760    }
42761  }
42762
42763  /* If control flows to this point, then it was not possible to add the
42764  ** the page being freed as a leaf page of the first trunk in the free-list.
42765  ** Possibly because the free-list is empty, or possibly because the
42766  ** first trunk in the free-list is full. Either way, the page being freed
42767  ** will become the new first trunk page in the free-list.
42768  */
42769  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
42770    goto freepage_out;
42771  }
42772  rc = sqlite3PagerWrite(pPage->pDbPage);
42773  if( rc!=SQLITE_OK ){
42774    goto freepage_out;
42775  }
42776  put4byte(pPage->aData, iTrunk);
42777  put4byte(&pPage->aData[4], 0);
42778  put4byte(&pPage1->aData[32], iPage);
42779  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
42780
42781freepage_out:
42782  if( pPage ){
42783    pPage->isInit = 0;
42784  }
42785  releasePage(pPage);
42786  releasePage(pTrunk);
42787  return rc;
42788}
42789static void freePage(MemPage *pPage, int *pRC){
42790  if( (*pRC)==SQLITE_OK ){
42791    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
42792  }
42793}
42794
42795/*
42796** Free any overflow pages associated with the given Cell.
42797*/
42798static int clearCell(MemPage *pPage, unsigned char *pCell){
42799  BtShared *pBt = pPage->pBt;
42800  CellInfo info;
42801  Pgno ovflPgno;
42802  int rc;
42803  int nOvfl;
42804  u16 ovflPageSize;
42805
42806  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42807  btreeParseCellPtr(pPage, pCell, &info);
42808  if( info.iOverflow==0 ){
42809    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
42810  }
42811  ovflPgno = get4byte(&pCell[info.iOverflow]);
42812  assert( pBt->usableSize > 4 );
42813  ovflPageSize = pBt->usableSize - 4;
42814  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
42815  assert( ovflPgno==0 || nOvfl>0 );
42816  while( nOvfl-- ){
42817    Pgno iNext = 0;
42818    MemPage *pOvfl = 0;
42819    if( ovflPgno<2 || ovflPgno>pagerPagecount(pBt) ){
42820      /* 0 is not a legal page number and page 1 cannot be an
42821      ** overflow page. Therefore if ovflPgno<2 or past the end of the
42822      ** file the database must be corrupt. */
42823      return SQLITE_CORRUPT_BKPT;
42824    }
42825    if( nOvfl ){
42826      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
42827      if( rc ) return rc;
42828    }
42829    rc = freePage2(pBt, pOvfl, ovflPgno);
42830    if( pOvfl ){
42831      sqlite3PagerUnref(pOvfl->pDbPage);
42832    }
42833    if( rc ) return rc;
42834    ovflPgno = iNext;
42835  }
42836  return SQLITE_OK;
42837}
42838
42839/*
42840** Create the byte sequence used to represent a cell on page pPage
42841** and write that byte sequence into pCell[].  Overflow pages are
42842** allocated and filled in as necessary.  The calling procedure
42843** is responsible for making sure sufficient space has been allocated
42844** for pCell[].
42845**
42846** Note that pCell does not necessary need to point to the pPage->aData
42847** area.  pCell might point to some temporary storage.  The cell will
42848** be constructed in this temporary area then copied into pPage->aData
42849** later.
42850*/
42851static int fillInCell(
42852  MemPage *pPage,                /* The page that contains the cell */
42853  unsigned char *pCell,          /* Complete text of the cell */
42854  const void *pKey, i64 nKey,    /* The key */
42855  const void *pData,int nData,   /* The data */
42856  int nZero,                     /* Extra zero bytes to append to pData */
42857  int *pnSize                    /* Write cell size here */
42858){
42859  int nPayload;
42860  const u8 *pSrc;
42861  int nSrc, n, rc;
42862  int spaceLeft;
42863  MemPage *pOvfl = 0;
42864  MemPage *pToRelease = 0;
42865  unsigned char *pPrior;
42866  unsigned char *pPayload;
42867  BtShared *pBt = pPage->pBt;
42868  Pgno pgnoOvfl = 0;
42869  int nHeader;
42870  CellInfo info;
42871
42872  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42873
42874  /* pPage is not necessarily writeable since pCell might be auxiliary
42875  ** buffer space that is separate from the pPage buffer area */
42876  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
42877            || sqlite3PagerIswriteable(pPage->pDbPage) );
42878
42879  /* Fill in the header. */
42880  nHeader = 0;
42881  if( !pPage->leaf ){
42882    nHeader += 4;
42883  }
42884  if( pPage->hasData ){
42885    nHeader += putVarint(&pCell[nHeader], nData+nZero);
42886  }else{
42887    nData = nZero = 0;
42888  }
42889  nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
42890  btreeParseCellPtr(pPage, pCell, &info);
42891  assert( info.nHeader==nHeader );
42892  assert( info.nKey==nKey );
42893  assert( info.nData==(u32)(nData+nZero) );
42894
42895  /* Fill in the payload */
42896  nPayload = nData + nZero;
42897  if( pPage->intKey ){
42898    pSrc = pData;
42899    nSrc = nData;
42900    nData = 0;
42901  }else{
42902    if( NEVER(nKey>0x7fffffff || pKey==0) ){
42903      return SQLITE_CORRUPT_BKPT;
42904    }
42905    nPayload += (int)nKey;
42906    pSrc = pKey;
42907    nSrc = (int)nKey;
42908  }
42909  *pnSize = info.nSize;
42910  spaceLeft = info.nLocal;
42911  pPayload = &pCell[nHeader];
42912  pPrior = &pCell[info.iOverflow];
42913
42914  while( nPayload>0 ){
42915    if( spaceLeft==0 ){
42916#ifndef SQLITE_OMIT_AUTOVACUUM
42917      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
42918      if( pBt->autoVacuum ){
42919        do{
42920          pgnoOvfl++;
42921        } while(
42922          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
42923        );
42924      }
42925#endif
42926      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
42927#ifndef SQLITE_OMIT_AUTOVACUUM
42928      /* If the database supports auto-vacuum, and the second or subsequent
42929      ** overflow page is being allocated, add an entry to the pointer-map
42930      ** for that page now.
42931      **
42932      ** If this is the first overflow page, then write a partial entry
42933      ** to the pointer-map. If we write nothing to this pointer-map slot,
42934      ** then the optimistic overflow chain processing in clearCell()
42935      ** may misinterpret the uninitialised values and delete the
42936      ** wrong pages from the database.
42937      */
42938      if( pBt->autoVacuum && rc==SQLITE_OK ){
42939        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
42940        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
42941        if( rc ){
42942          releasePage(pOvfl);
42943        }
42944      }
42945#endif
42946      if( rc ){
42947        releasePage(pToRelease);
42948        return rc;
42949      }
42950
42951      /* If pToRelease is not zero than pPrior points into the data area
42952      ** of pToRelease.  Make sure pToRelease is still writeable. */
42953      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
42954
42955      /* If pPrior is part of the data area of pPage, then make sure pPage
42956      ** is still writeable */
42957      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
42958            || sqlite3PagerIswriteable(pPage->pDbPage) );
42959
42960      put4byte(pPrior, pgnoOvfl);
42961      releasePage(pToRelease);
42962      pToRelease = pOvfl;
42963      pPrior = pOvfl->aData;
42964      put4byte(pPrior, 0);
42965      pPayload = &pOvfl->aData[4];
42966      spaceLeft = pBt->usableSize - 4;
42967    }
42968    n = nPayload;
42969    if( n>spaceLeft ) n = spaceLeft;
42970
42971    /* If pToRelease is not zero than pPayload points into the data area
42972    ** of pToRelease.  Make sure pToRelease is still writeable. */
42973    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
42974
42975    /* If pPayload is part of the data area of pPage, then make sure pPage
42976    ** is still writeable */
42977    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
42978            || sqlite3PagerIswriteable(pPage->pDbPage) );
42979
42980    if( nSrc>0 ){
42981      if( n>nSrc ) n = nSrc;
42982      assert( pSrc );
42983      memcpy(pPayload, pSrc, n);
42984    }else{
42985      memset(pPayload, 0, n);
42986    }
42987    nPayload -= n;
42988    pPayload += n;
42989    pSrc += n;
42990    nSrc -= n;
42991    spaceLeft -= n;
42992    if( nSrc==0 ){
42993      nSrc = nData;
42994      pSrc = pData;
42995    }
42996  }
42997  releasePage(pToRelease);
42998  return SQLITE_OK;
42999}
43000
43001/*
43002** Remove the i-th cell from pPage.  This routine effects pPage only.
43003** The cell content is not freed or deallocated.  It is assumed that
43004** the cell content has been copied someplace else.  This routine just
43005** removes the reference to the cell from pPage.
43006**
43007** "sz" must be the number of bytes in the cell.
43008*/
43009static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
43010  int i;          /* Loop counter */
43011  int pc;         /* Offset to cell content of cell being deleted */
43012  u8 *data;       /* pPage->aData */
43013  u8 *ptr;        /* Used to move bytes around within data[] */
43014  int rc;         /* The return code */
43015  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
43016
43017  if( *pRC ) return;
43018
43019  assert( idx>=0 && idx<pPage->nCell );
43020  assert( sz==cellSize(pPage, idx) );
43021  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
43022  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43023  data = pPage->aData;
43024  ptr = &data[pPage->cellOffset + 2*idx];
43025  pc = get2byte(ptr);
43026  hdr = pPage->hdrOffset;
43027  testcase( pc==get2byte(&data[hdr+5]) );
43028  testcase( pc+sz==pPage->pBt->usableSize );
43029  if( pc < get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
43030    *pRC = SQLITE_CORRUPT_BKPT;
43031    return;
43032  }
43033  rc = freeSpace(pPage, pc, sz);
43034  if( rc ){
43035    *pRC = rc;
43036    return;
43037  }
43038  for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
43039    ptr[0] = ptr[2];
43040    ptr[1] = ptr[3];
43041  }
43042  pPage->nCell--;
43043  put2byte(&data[hdr+3], pPage->nCell);
43044  pPage->nFree += 2;
43045}
43046
43047/*
43048** Insert a new cell on pPage at cell index "i".  pCell points to the
43049** content of the cell.
43050**
43051** If the cell content will fit on the page, then put it there.  If it
43052** will not fit, then make a copy of the cell content into pTemp if
43053** pTemp is not null.  Regardless of pTemp, allocate a new entry
43054** in pPage->aOvfl[] and make it point to the cell content (either
43055** in pTemp or the original pCell) and also record its index.
43056** Allocating a new entry in pPage->aCell[] implies that
43057** pPage->nOverflow is incremented.
43058**
43059** If nSkip is non-zero, then do not copy the first nSkip bytes of the
43060** cell. The caller will overwrite them after this function returns. If
43061** nSkip is non-zero, then pCell may not point to an invalid memory location
43062** (but pCell+nSkip is always valid).
43063*/
43064static void insertCell(
43065  MemPage *pPage,   /* Page into which we are copying */
43066  int i,            /* New cell becomes the i-th cell of the page */
43067  u8 *pCell,        /* Content of the new cell */
43068  int sz,           /* Bytes of content in pCell */
43069  u8 *pTemp,        /* Temp storage space for pCell, if needed */
43070  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
43071  int *pRC          /* Read and write return code from here */
43072){
43073  int idx;          /* Where to write new cell content in data[] */
43074  int j;            /* Loop counter */
43075  int end;          /* First byte past the last cell pointer in data[] */
43076  int ins;          /* Index in data[] where new cell pointer is inserted */
43077  int cellOffset;   /* Address of first cell pointer in data[] */
43078  u8 *data;         /* The content of the whole page */
43079  u8 *ptr;          /* Used for moving information around in data[] */
43080
43081  int nSkip = (iChild ? 4 : 0);
43082
43083  if( *pRC ) return;
43084
43085  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
43086  assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
43087  assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
43088  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43089  /* The cell should normally be sized correctly.  However, when moving a
43090  ** malformed cell from a leaf page to an interior page, if the cell size
43091  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
43092  ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
43093  ** the term after the || in the following assert(). */
43094  assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
43095  if( pPage->nOverflow || sz+2>pPage->nFree ){
43096    if( pTemp ){
43097      memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
43098      pCell = pTemp;
43099    }
43100    if( iChild ){
43101      put4byte(pCell, iChild);
43102    }
43103    j = pPage->nOverflow++;
43104    assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
43105    pPage->aOvfl[j].pCell = pCell;
43106    pPage->aOvfl[j].idx = (u16)i;
43107  }else{
43108    int rc = sqlite3PagerWrite(pPage->pDbPage);
43109    if( rc!=SQLITE_OK ){
43110      *pRC = rc;
43111      return;
43112    }
43113    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
43114    data = pPage->aData;
43115    cellOffset = pPage->cellOffset;
43116    end = cellOffset + 2*pPage->nCell;
43117    ins = cellOffset + 2*i;
43118    rc = allocateSpace(pPage, sz, &idx);
43119    if( rc ){ *pRC = rc; return; }
43120    /* The allocateSpace() routine guarantees the following two properties
43121    ** if it returns success */
43122    assert( idx >= end+2 );
43123    assert( idx+sz <= pPage->pBt->usableSize );
43124    pPage->nCell++;
43125    pPage->nFree -= (u16)(2 + sz);
43126    memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
43127    if( iChild ){
43128      put4byte(&data[idx], iChild);
43129    }
43130    for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
43131      ptr[0] = ptr[-2];
43132      ptr[1] = ptr[-1];
43133    }
43134    put2byte(&data[ins], idx);
43135    put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
43136#ifndef SQLITE_OMIT_AUTOVACUUM
43137    if( pPage->pBt->autoVacuum ){
43138      /* The cell may contain a pointer to an overflow page. If so, write
43139      ** the entry for the overflow page into the pointer map.
43140      */
43141      ptrmapPutOvflPtr(pPage, pCell, pRC);
43142    }
43143#endif
43144  }
43145}
43146
43147/*
43148** Add a list of cells to a page.  The page should be initially empty.
43149** The cells are guaranteed to fit on the page.
43150*/
43151static void assemblePage(
43152  MemPage *pPage,   /* The page to be assemblied */
43153  int nCell,        /* The number of cells to add to this page */
43154  u8 **apCell,      /* Pointers to cell bodies */
43155  u16 *aSize        /* Sizes of the cells */
43156){
43157  int i;            /* Loop counter */
43158  u8 *pCellptr;     /* Address of next cell pointer */
43159  int cellbody;     /* Address of next cell body */
43160  u8 * const data = pPage->aData;             /* Pointer to data for pPage */
43161  const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
43162  const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
43163
43164  assert( pPage->nOverflow==0 );
43165  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43166  assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
43167  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
43168
43169  /* Check that the page has just been zeroed by zeroPage() */
43170  assert( pPage->nCell==0 );
43171  assert( get2byte(&data[hdr+5])==nUsable );
43172
43173  pCellptr = &data[pPage->cellOffset + nCell*2];
43174  cellbody = nUsable;
43175  for(i=nCell-1; i>=0; i--){
43176    pCellptr -= 2;
43177    cellbody -= aSize[i];
43178    put2byte(pCellptr, cellbody);
43179    memcpy(&data[cellbody], apCell[i], aSize[i]);
43180  }
43181  put2byte(&data[hdr+3], nCell);
43182  put2byte(&data[hdr+5], cellbody);
43183  pPage->nFree -= (nCell*2 + nUsable - cellbody);
43184  pPage->nCell = (u16)nCell;
43185}
43186
43187/*
43188** The following parameters determine how many adjacent pages get involved
43189** in a balancing operation.  NN is the number of neighbors on either side
43190** of the page that participate in the balancing operation.  NB is the
43191** total number of pages that participate, including the target page and
43192** NN neighbors on either side.
43193**
43194** The minimum value of NN is 1 (of course).  Increasing NN above 1
43195** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
43196** in exchange for a larger degradation in INSERT and UPDATE performance.
43197** The value of NN appears to give the best results overall.
43198*/
43199#define NN 1             /* Number of neighbors on either side of pPage */
43200#define NB (NN*2+1)      /* Total pages involved in the balance */
43201
43202
43203#ifndef SQLITE_OMIT_QUICKBALANCE
43204/*
43205** This version of balance() handles the common special case where
43206** a new entry is being inserted on the extreme right-end of the
43207** tree, in other words, when the new entry will become the largest
43208** entry in the tree.
43209**
43210** Instead of trying to balance the 3 right-most leaf pages, just add
43211** a new page to the right-hand side and put the one new entry in
43212** that page.  This leaves the right side of the tree somewhat
43213** unbalanced.  But odds are that we will be inserting new entries
43214** at the end soon afterwards so the nearly empty page will quickly
43215** fill up.  On average.
43216**
43217** pPage is the leaf page which is the right-most page in the tree.
43218** pParent is its parent.  pPage must have a single overflow entry
43219** which is also the right-most entry on the page.
43220**
43221** The pSpace buffer is used to store a temporary copy of the divider
43222** cell that will be inserted into pParent. Such a cell consists of a 4
43223** byte page number followed by a variable length integer. In other
43224** words, at most 13 bytes. Hence the pSpace buffer must be at
43225** least 13 bytes in size.
43226*/
43227static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
43228  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
43229  MemPage *pNew;                       /* Newly allocated page */
43230  int rc;                              /* Return Code */
43231  Pgno pgnoNew;                        /* Page number of pNew */
43232
43233  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43234  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
43235  assert( pPage->nOverflow==1 );
43236
43237  if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
43238
43239  /* Allocate a new page. This page will become the right-sibling of
43240  ** pPage. Make the parent page writable, so that the new divider cell
43241  ** may be inserted. If both these operations are successful, proceed.
43242  */
43243  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
43244
43245  if( rc==SQLITE_OK ){
43246
43247    u8 *pOut = &pSpace[4];
43248    u8 *pCell = pPage->aOvfl[0].pCell;
43249    u16 szCell = cellSizePtr(pPage, pCell);
43250    u8 *pStop;
43251
43252    assert( sqlite3PagerIswriteable(pNew->pDbPage) );
43253    assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
43254    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
43255    assemblePage(pNew, 1, &pCell, &szCell);
43256
43257    /* If this is an auto-vacuum database, update the pointer map
43258    ** with entries for the new page, and any pointer from the
43259    ** cell on the page to an overflow page. If either of these
43260    ** operations fails, the return code is set, but the contents
43261    ** of the parent page are still manipulated by thh code below.
43262    ** That is Ok, at this point the parent page is guaranteed to
43263    ** be marked as dirty. Returning an error code will cause a
43264    ** rollback, undoing any changes made to the parent page.
43265    */
43266    if( ISAUTOVACUUM ){
43267      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
43268      if( szCell>pNew->minLocal ){
43269        ptrmapPutOvflPtr(pNew, pCell, &rc);
43270      }
43271    }
43272
43273    /* Create a divider cell to insert into pParent. The divider cell
43274    ** consists of a 4-byte page number (the page number of pPage) and
43275    ** a variable length key value (which must be the same value as the
43276    ** largest key on pPage).
43277    **
43278    ** To find the largest key value on pPage, first find the right-most
43279    ** cell on pPage. The first two fields of this cell are the
43280    ** record-length (a variable length integer at most 32-bits in size)
43281    ** and the key value (a variable length integer, may have any value).
43282    ** The first of the while(...) loops below skips over the record-length
43283    ** field. The second while(...) loop copies the key value from the
43284    ** cell on pPage into the pSpace buffer.
43285    */
43286    pCell = findCell(pPage, pPage->nCell-1);
43287    pStop = &pCell[9];
43288    while( (*(pCell++)&0x80) && pCell<pStop );
43289    pStop = &pCell[9];
43290    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
43291
43292    /* Insert the new divider cell into pParent. */
43293    insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
43294               0, pPage->pgno, &rc);
43295
43296    /* Set the right-child pointer of pParent to point to the new page. */
43297    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
43298
43299    /* Release the reference to the new page. */
43300    releasePage(pNew);
43301  }
43302
43303  return rc;
43304}
43305#endif /* SQLITE_OMIT_QUICKBALANCE */
43306
43307#if 0
43308/*
43309** This function does not contribute anything to the operation of SQLite.
43310** it is sometimes activated temporarily while debugging code responsible
43311** for setting pointer-map entries.
43312*/
43313static int ptrmapCheckPages(MemPage **apPage, int nPage){
43314  int i, j;
43315  for(i=0; i<nPage; i++){
43316    Pgno n;
43317    u8 e;
43318    MemPage *pPage = apPage[i];
43319    BtShared *pBt = pPage->pBt;
43320    assert( pPage->isInit );
43321
43322    for(j=0; j<pPage->nCell; j++){
43323      CellInfo info;
43324      u8 *z;
43325
43326      z = findCell(pPage, j);
43327      btreeParseCellPtr(pPage, z, &info);
43328      if( info.iOverflow ){
43329        Pgno ovfl = get4byte(&z[info.iOverflow]);
43330        ptrmapGet(pBt, ovfl, &e, &n);
43331        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
43332      }
43333      if( !pPage->leaf ){
43334        Pgno child = get4byte(z);
43335        ptrmapGet(pBt, child, &e, &n);
43336        assert( n==pPage->pgno && e==PTRMAP_BTREE );
43337      }
43338    }
43339    if( !pPage->leaf ){
43340      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
43341      ptrmapGet(pBt, child, &e, &n);
43342      assert( n==pPage->pgno && e==PTRMAP_BTREE );
43343    }
43344  }
43345  return 1;
43346}
43347#endif
43348
43349/*
43350** This function is used to copy the contents of the b-tree node stored
43351** on page pFrom to page pTo. If page pFrom was not a leaf page, then
43352** the pointer-map entries for each child page are updated so that the
43353** parent page stored in the pointer map is page pTo. If pFrom contained
43354** any cells with overflow page pointers, then the corresponding pointer
43355** map entries are also updated so that the parent page is page pTo.
43356**
43357** If pFrom is currently carrying any overflow cells (entries in the
43358** MemPage.aOvfl[] array), they are not copied to pTo.
43359**
43360** Before returning, page pTo is reinitialized using btreeInitPage().
43361**
43362** The performance of this function is not critical. It is only used by
43363** the balance_shallower() and balance_deeper() procedures, neither of
43364** which are called often under normal circumstances.
43365*/
43366static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
43367  if( (*pRC)==SQLITE_OK ){
43368    BtShared * const pBt = pFrom->pBt;
43369    u8 * const aFrom = pFrom->aData;
43370    u8 * const aTo = pTo->aData;
43371    int const iFromHdr = pFrom->hdrOffset;
43372    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
43373    int rc;
43374    int iData;
43375
43376
43377    assert( pFrom->isInit );
43378    assert( pFrom->nFree>=iToHdr );
43379    assert( get2byte(&aFrom[iFromHdr+5])<=pBt->usableSize );
43380
43381    /* Copy the b-tree node content from page pFrom to page pTo. */
43382    iData = get2byte(&aFrom[iFromHdr+5]);
43383    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
43384    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
43385
43386    /* Reinitialize page pTo so that the contents of the MemPage structure
43387    ** match the new data. The initialization of pTo can actually fail under
43388    ** fairly obscure circumstances, even though it is a copy of initialized
43389    ** page pFrom.
43390    */
43391    pTo->isInit = 0;
43392    rc = btreeInitPage(pTo);
43393    if( rc!=SQLITE_OK ){
43394      *pRC = rc;
43395      return;
43396    }
43397
43398    /* If this is an auto-vacuum database, update the pointer-map entries
43399    ** for any b-tree or overflow pages that pTo now contains the pointers to.
43400    */
43401    if( ISAUTOVACUUM ){
43402      *pRC = setChildPtrmaps(pTo);
43403    }
43404  }
43405}
43406
43407/*
43408** This routine redistributes cells on the iParentIdx'th child of pParent
43409** (hereafter "the page") and up to 2 siblings so that all pages have about the
43410** same amount of free space. Usually a single sibling on either side of the
43411** page are used in the balancing, though both siblings might come from one
43412** side if the page is the first or last child of its parent. If the page
43413** has fewer than 2 siblings (something which can only happen if the page
43414** is a root page or a child of a root page) then all available siblings
43415** participate in the balancing.
43416**
43417** The number of siblings of the page might be increased or decreased by
43418** one or two in an effort to keep pages nearly full but not over full.
43419**
43420** Note that when this routine is called, some of the cells on the page
43421** might not actually be stored in MemPage.aData[]. This can happen
43422** if the page is overfull. This routine ensures that all cells allocated
43423** to the page and its siblings fit into MemPage.aData[] before returning.
43424**
43425** In the course of balancing the page and its siblings, cells may be
43426** inserted into or removed from the parent page (pParent). Doing so
43427** may cause the parent page to become overfull or underfull. If this
43428** happens, it is the responsibility of the caller to invoke the correct
43429** balancing routine to fix this problem (see the balance() routine).
43430**
43431** If this routine fails for any reason, it might leave the database
43432** in a corrupted state. So if this routine fails, the database should
43433** be rolled back.
43434**
43435** The third argument to this function, aOvflSpace, is a pointer to a
43436** buffer big enough to hold one page. If while inserting cells into the parent
43437** page (pParent) the parent page becomes overfull, this buffer is
43438** used to store the parent's overflow cells. Because this function inserts
43439** a maximum of four divider cells into the parent page, and the maximum
43440** size of a cell stored within an internal node is always less than 1/4
43441** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
43442** enough for all overflow cells.
43443**
43444** If aOvflSpace is set to a null pointer, this function returns
43445** SQLITE_NOMEM.
43446*/
43447static int balance_nonroot(
43448  MemPage *pParent,               /* Parent page of siblings being balanced */
43449  int iParentIdx,                 /* Index of "the page" in pParent */
43450  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
43451  int isRoot                      /* True if pParent is a root-page */
43452){
43453  BtShared *pBt;               /* The whole database */
43454  int nCell = 0;               /* Number of cells in apCell[] */
43455  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
43456  int nNew = 0;                /* Number of pages in apNew[] */
43457  int nOld;                    /* Number of pages in apOld[] */
43458  int i, j, k;                 /* Loop counters */
43459  int nxDiv;                   /* Next divider slot in pParent->aCell[] */
43460  int rc = SQLITE_OK;          /* The return code */
43461  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
43462  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
43463  int usableSpace;             /* Bytes in pPage beyond the header */
43464  int pageFlags;               /* Value of pPage->aData[0] */
43465  int subtotal;                /* Subtotal of bytes in cells on one page */
43466  int iSpace1 = 0;             /* First unused byte of aSpace1[] */
43467  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
43468  int szScratch;               /* Size of scratch memory requested */
43469  MemPage *apOld[NB];          /* pPage and up to two siblings */
43470  MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
43471  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
43472  u8 *pRight;                  /* Location in parent of right-sibling pointer */
43473  u8 *apDiv[NB-1];             /* Divider cells in pParent */
43474  int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
43475  int szNew[NB+2];             /* Combined size of cells place on i-th page */
43476  u8 **apCell = 0;             /* All cells begin balanced */
43477  u16 *szCell;                 /* Local size of all cells in apCell[] */
43478  u8 *aSpace1;                 /* Space for copies of dividers cells */
43479  Pgno pgno;                   /* Temp var to store a page number in */
43480
43481  pBt = pParent->pBt;
43482  assert( sqlite3_mutex_held(pBt->mutex) );
43483  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
43484
43485#if 0
43486  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
43487#endif
43488
43489  /* At this point pParent may have at most one overflow cell. And if
43490  ** this overflow cell is present, it must be the cell with
43491  ** index iParentIdx. This scenario comes about when this function
43492  ** is called (indirectly) from sqlite3BtreeDelete().
43493  */
43494  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
43495  assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
43496
43497  if( !aOvflSpace ){
43498    return SQLITE_NOMEM;
43499  }
43500
43501  /* Find the sibling pages to balance. Also locate the cells in pParent
43502  ** that divide the siblings. An attempt is made to find NN siblings on
43503  ** either side of pPage. More siblings are taken from one side, however,
43504  ** if there are fewer than NN siblings on the other side. If pParent
43505  ** has NB or fewer children then all children of pParent are taken.
43506  **
43507  ** This loop also drops the divider cells from the parent page. This
43508  ** way, the remainder of the function does not have to deal with any
43509  ** overflow cells in the parent page, since if any existed they will
43510  ** have already been removed.
43511  */
43512  i = pParent->nOverflow + pParent->nCell;
43513  if( i<2 ){
43514    nxDiv = 0;
43515    nOld = i+1;
43516  }else{
43517    nOld = 3;
43518    if( iParentIdx==0 ){
43519      nxDiv = 0;
43520    }else if( iParentIdx==i ){
43521      nxDiv = i-2;
43522    }else{
43523      nxDiv = iParentIdx-1;
43524    }
43525    i = 2;
43526  }
43527  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
43528    pRight = &pParent->aData[pParent->hdrOffset+8];
43529  }else{
43530    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
43531  }
43532  pgno = get4byte(pRight);
43533  while( 1 ){
43534    rc = getAndInitPage(pBt, pgno, &apOld[i]);
43535    if( rc ){
43536      memset(apOld, 0, (i+1)*sizeof(MemPage*));
43537      goto balance_cleanup;
43538    }
43539    nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
43540    if( (i--)==0 ) break;
43541
43542    if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
43543      apDiv[i] = pParent->aOvfl[0].pCell;
43544      pgno = get4byte(apDiv[i]);
43545      szNew[i] = cellSizePtr(pParent, apDiv[i]);
43546      pParent->nOverflow = 0;
43547    }else{
43548      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
43549      pgno = get4byte(apDiv[i]);
43550      szNew[i] = cellSizePtr(pParent, apDiv[i]);
43551
43552      /* Drop the cell from the parent page. apDiv[i] still points to
43553      ** the cell within the parent, even though it has been dropped.
43554      ** This is safe because dropping a cell only overwrites the first
43555      ** four bytes of it, and this function does not need the first
43556      ** four bytes of the divider cell. So the pointer is safe to use
43557      ** later on.
43558      **
43559      ** Unless SQLite is compiled in secure-delete mode. In this case,
43560      ** the dropCell() routine will overwrite the entire cell with zeroes.
43561      ** In this case, temporarily copy the cell into the aOvflSpace[]
43562      ** buffer. It will be copied out again as soon as the aSpace[] buffer
43563      ** is allocated.  */
43564#ifdef SQLITE_SECURE_DELETE
43565      memcpy(&aOvflSpace[apDiv[i]-pParent->aData], apDiv[i], szNew[i]);
43566      apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
43567#endif
43568      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
43569    }
43570  }
43571
43572  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
43573  ** alignment */
43574  nMaxCells = (nMaxCells + 3)&~3;
43575
43576  /*
43577  ** Allocate space for memory structures
43578  */
43579  k = pBt->pageSize + ROUND8(sizeof(MemPage));
43580  szScratch =
43581       nMaxCells*sizeof(u8*)                       /* apCell */
43582     + nMaxCells*sizeof(u16)                       /* szCell */
43583     + pBt->pageSize                               /* aSpace1 */
43584     + k*nOld;                                     /* Page copies (apCopy) */
43585  apCell = sqlite3ScratchMalloc( szScratch );
43586  if( apCell==0 ){
43587    rc = SQLITE_NOMEM;
43588    goto balance_cleanup;
43589  }
43590  szCell = (u16*)&apCell[nMaxCells];
43591  aSpace1 = (u8*)&szCell[nMaxCells];
43592  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
43593
43594  /*
43595  ** Load pointers to all cells on sibling pages and the divider cells
43596  ** into the local apCell[] array.  Make copies of the divider cells
43597  ** into space obtained from aSpace1[] and remove the the divider Cells
43598  ** from pParent.
43599  **
43600  ** If the siblings are on leaf pages, then the child pointers of the
43601  ** divider cells are stripped from the cells before they are copied
43602  ** into aSpace1[].  In this way, all cells in apCell[] are without
43603  ** child pointers.  If siblings are not leaves, then all cell in
43604  ** apCell[] include child pointers.  Either way, all cells in apCell[]
43605  ** are alike.
43606  **
43607  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
43608  **       leafData:  1 if pPage holds key+data and pParent holds only keys.
43609  */
43610  leafCorrection = apOld[0]->leaf*4;
43611  leafData = apOld[0]->hasData;
43612  for(i=0; i<nOld; i++){
43613    int limit;
43614
43615    /* Before doing anything else, take a copy of the i'th original sibling
43616    ** The rest of this function will use data from the copies rather
43617    ** that the original pages since the original pages will be in the
43618    ** process of being overwritten.  */
43619    MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
43620    memcpy(pOld, apOld[i], sizeof(MemPage));
43621    pOld->aData = (void*)&pOld[1];
43622    memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
43623
43624    limit = pOld->nCell+pOld->nOverflow;
43625    for(j=0; j<limit; j++){
43626      assert( nCell<nMaxCells );
43627      apCell[nCell] = findOverflowCell(pOld, j);
43628      szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
43629      nCell++;
43630    }
43631    if( i<nOld-1 && !leafData){
43632      u16 sz = (u16)szNew[i];
43633      u8 *pTemp;
43634      assert( nCell<nMaxCells );
43635      szCell[nCell] = sz;
43636      pTemp = &aSpace1[iSpace1];
43637      iSpace1 += sz;
43638      assert( sz<=pBt->pageSize/4 );
43639      assert( iSpace1<=pBt->pageSize );
43640      memcpy(pTemp, apDiv[i], sz);
43641      apCell[nCell] = pTemp+leafCorrection;
43642      assert( leafCorrection==0 || leafCorrection==4 );
43643      szCell[nCell] = szCell[nCell] - leafCorrection;
43644      if( !pOld->leaf ){
43645        assert( leafCorrection==0 );
43646        assert( pOld->hdrOffset==0 );
43647        /* The right pointer of the child page pOld becomes the left
43648        ** pointer of the divider cell */
43649        memcpy(apCell[nCell], &pOld->aData[8], 4);
43650      }else{
43651        assert( leafCorrection==4 );
43652        if( szCell[nCell]<4 ){
43653          /* Do not allow any cells smaller than 4 bytes. */
43654          szCell[nCell] = 4;
43655        }
43656      }
43657      nCell++;
43658    }
43659  }
43660
43661  /*
43662  ** Figure out the number of pages needed to hold all nCell cells.
43663  ** Store this number in "k".  Also compute szNew[] which is the total
43664  ** size of all cells on the i-th page and cntNew[] which is the index
43665  ** in apCell[] of the cell that divides page i from page i+1.
43666  ** cntNew[k] should equal nCell.
43667  **
43668  ** Values computed by this block:
43669  **
43670  **           k: The total number of sibling pages
43671  **    szNew[i]: Spaced used on the i-th sibling page.
43672  **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
43673  **              the right of the i-th sibling page.
43674  ** usableSpace: Number of bytes of space available on each sibling.
43675  **
43676  */
43677  usableSpace = pBt->usableSize - 12 + leafCorrection;
43678  for(subtotal=k=i=0; i<nCell; i++){
43679    assert( i<nMaxCells );
43680    subtotal += szCell[i] + 2;
43681    if( subtotal > usableSpace ){
43682      szNew[k] = subtotal - szCell[i];
43683      cntNew[k] = i;
43684      if( leafData ){ i--; }
43685      subtotal = 0;
43686      k++;
43687      if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
43688    }
43689  }
43690  szNew[k] = subtotal;
43691  cntNew[k] = nCell;
43692  k++;
43693
43694  /*
43695  ** The packing computed by the previous block is biased toward the siblings
43696  ** on the left side.  The left siblings are always nearly full, while the
43697  ** right-most sibling might be nearly empty.  This block of code attempts
43698  ** to adjust the packing of siblings to get a better balance.
43699  **
43700  ** This adjustment is more than an optimization.  The packing above might
43701  ** be so out of balance as to be illegal.  For example, the right-most
43702  ** sibling might be completely empty.  This adjustment is not optional.
43703  */
43704  for(i=k-1; i>0; i--){
43705    int szRight = szNew[i];  /* Size of sibling on the right */
43706    int szLeft = szNew[i-1]; /* Size of sibling on the left */
43707    int r;              /* Index of right-most cell in left sibling */
43708    int d;              /* Index of first cell to the left of right sibling */
43709
43710    r = cntNew[i-1] - 1;
43711    d = r + 1 - leafData;
43712    assert( d<nMaxCells );
43713    assert( r<nMaxCells );
43714    while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
43715      szRight += szCell[d] + 2;
43716      szLeft -= szCell[r] + 2;
43717      cntNew[i-1]--;
43718      r = cntNew[i-1] - 1;
43719      d = r + 1 - leafData;
43720    }
43721    szNew[i] = szRight;
43722    szNew[i-1] = szLeft;
43723  }
43724
43725  /* Either we found one or more cells (cntnew[0])>0) or pPage is
43726  ** a virtual root page.  A virtual root page is when the real root
43727  ** page is page 1 and we are the only child of that page.
43728  */
43729  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
43730
43731  TRACE(("BALANCE: old: %d %d %d  ",
43732    apOld[0]->pgno,
43733    nOld>=2 ? apOld[1]->pgno : 0,
43734    nOld>=3 ? apOld[2]->pgno : 0
43735  ));
43736
43737  /*
43738  ** Allocate k new pages.  Reuse old pages where possible.
43739  */
43740  if( apOld[0]->pgno<=1 ){
43741    rc = SQLITE_CORRUPT_BKPT;
43742    goto balance_cleanup;
43743  }
43744  pageFlags = apOld[0]->aData[0];
43745  for(i=0; i<k; i++){
43746    MemPage *pNew;
43747    if( i<nOld ){
43748      pNew = apNew[i] = apOld[i];
43749      apOld[i] = 0;
43750      rc = sqlite3PagerWrite(pNew->pDbPage);
43751      nNew++;
43752      if( rc ) goto balance_cleanup;
43753    }else{
43754      assert( i>0 );
43755      rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
43756      if( rc ) goto balance_cleanup;
43757      apNew[i] = pNew;
43758      nNew++;
43759
43760      /* Set the pointer-map entry for the new sibling page. */
43761      if( ISAUTOVACUUM ){
43762        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
43763        if( rc!=SQLITE_OK ){
43764          goto balance_cleanup;
43765        }
43766      }
43767    }
43768  }
43769
43770  /* Free any old pages that were not reused as new pages.
43771  */
43772  while( i<nOld ){
43773    freePage(apOld[i], &rc);
43774    if( rc ) goto balance_cleanup;
43775    releasePage(apOld[i]);
43776    apOld[i] = 0;
43777    i++;
43778  }
43779
43780  /*
43781  ** Put the new pages in accending order.  This helps to
43782  ** keep entries in the disk file in order so that a scan
43783  ** of the table is a linear scan through the file.  That
43784  ** in turn helps the operating system to deliver pages
43785  ** from the disk more rapidly.
43786  **
43787  ** An O(n^2) insertion sort algorithm is used, but since
43788  ** n is never more than NB (a small constant), that should
43789  ** not be a problem.
43790  **
43791  ** When NB==3, this one optimization makes the database
43792  ** about 25% faster for large insertions and deletions.
43793  */
43794  for(i=0; i<k-1; i++){
43795    int minV = apNew[i]->pgno;
43796    int minI = i;
43797    for(j=i+1; j<k; j++){
43798      if( apNew[j]->pgno<(unsigned)minV ){
43799        minI = j;
43800        minV = apNew[j]->pgno;
43801      }
43802    }
43803    if( minI>i ){
43804      int t;
43805      MemPage *pT;
43806      t = apNew[i]->pgno;
43807      pT = apNew[i];
43808      apNew[i] = apNew[minI];
43809      apNew[minI] = pT;
43810    }
43811  }
43812  TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
43813    apNew[0]->pgno, szNew[0],
43814    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
43815    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
43816    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
43817    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
43818
43819  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
43820  put4byte(pRight, apNew[nNew-1]->pgno);
43821
43822  /*
43823  ** Evenly distribute the data in apCell[] across the new pages.
43824  ** Insert divider cells into pParent as necessary.
43825  */
43826  j = 0;
43827  for(i=0; i<nNew; i++){
43828    /* Assemble the new sibling page. */
43829    MemPage *pNew = apNew[i];
43830    assert( j<nMaxCells );
43831    zeroPage(pNew, pageFlags);
43832    assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
43833    assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
43834    assert( pNew->nOverflow==0 );
43835
43836    j = cntNew[i];
43837
43838    /* If the sibling page assembled above was not the right-most sibling,
43839    ** insert a divider cell into the parent page.
43840    */
43841    assert( i<nNew-1 || j==nCell );
43842    if( j<nCell ){
43843      u8 *pCell;
43844      u8 *pTemp;
43845      int sz;
43846
43847      assert( j<nMaxCells );
43848      pCell = apCell[j];
43849      sz = szCell[j] + leafCorrection;
43850      pTemp = &aOvflSpace[iOvflSpace];
43851      if( !pNew->leaf ){
43852        memcpy(&pNew->aData[8], pCell, 4);
43853      }else if( leafData ){
43854        /* If the tree is a leaf-data tree, and the siblings are leaves,
43855        ** then there is no divider cell in apCell[]. Instead, the divider
43856        ** cell consists of the integer key for the right-most cell of
43857        ** the sibling-page assembled above only.
43858        */
43859        CellInfo info;
43860        j--;
43861        btreeParseCellPtr(pNew, apCell[j], &info);
43862        pCell = pTemp;
43863        sz = 4 + putVarint(&pCell[4], info.nKey);
43864        pTemp = 0;
43865      }else{
43866        pCell -= 4;
43867        /* Obscure case for non-leaf-data trees: If the cell at pCell was
43868        ** previously stored on a leaf node, and its reported size was 4
43869        ** bytes, then it may actually be smaller than this
43870        ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
43871        ** any cell). But it is important to pass the correct size to
43872        ** insertCell(), so reparse the cell now.
43873        **
43874        ** Note that this can never happen in an SQLite data file, as all
43875        ** cells are at least 4 bytes. It only happens in b-trees used
43876        ** to evaluate "IN (SELECT ...)" and similar clauses.
43877        */
43878        if( szCell[j]==4 ){
43879          assert(leafCorrection==4);
43880          sz = cellSizePtr(pParent, pCell);
43881        }
43882      }
43883      iOvflSpace += sz;
43884      assert( sz<=pBt->pageSize/4 );
43885      assert( iOvflSpace<=pBt->pageSize );
43886      insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
43887      if( rc!=SQLITE_OK ) goto balance_cleanup;
43888      assert( sqlite3PagerIswriteable(pParent->pDbPage) );
43889
43890      j++;
43891      nxDiv++;
43892    }
43893  }
43894  assert( j==nCell );
43895  assert( nOld>0 );
43896  assert( nNew>0 );
43897  if( (pageFlags & PTF_LEAF)==0 ){
43898    u8 *zChild = &apCopy[nOld-1]->aData[8];
43899    memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
43900  }
43901
43902  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
43903    /* The root page of the b-tree now contains no cells. The only sibling
43904    ** page is the right-child of the parent. Copy the contents of the
43905    ** child page into the parent, decreasing the overall height of the
43906    ** b-tree structure by one. This is described as the "balance-shallower"
43907    ** sub-algorithm in some documentation.
43908    **
43909    ** If this is an auto-vacuum database, the call to copyNodeContent()
43910    ** sets all pointer-map entries corresponding to database image pages
43911    ** for which the pointer is stored within the content being copied.
43912    **
43913    ** The second assert below verifies that the child page is defragmented
43914    ** (it must be, as it was just reconstructed using assemblePage()). This
43915    ** is important if the parent page happens to be page 1 of the database
43916    ** image.  */
43917    assert( nNew==1 );
43918    assert( apNew[0]->nFree ==
43919        (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
43920    );
43921    copyNodeContent(apNew[0], pParent, &rc);
43922    freePage(apNew[0], &rc);
43923  }else if( ISAUTOVACUUM ){
43924    /* Fix the pointer-map entries for all the cells that were shifted around.
43925    ** There are several different types of pointer-map entries that need to
43926    ** be dealt with by this routine. Some of these have been set already, but
43927    ** many have not. The following is a summary:
43928    **
43929    **   1) The entries associated with new sibling pages that were not
43930    **      siblings when this function was called. These have already
43931    **      been set. We don't need to worry about old siblings that were
43932    **      moved to the free-list - the freePage() code has taken care
43933    **      of those.
43934    **
43935    **   2) The pointer-map entries associated with the first overflow
43936    **      page in any overflow chains used by new divider cells. These
43937    **      have also already been taken care of by the insertCell() code.
43938    **
43939    **   3) If the sibling pages are not leaves, then the child pages of
43940    **      cells stored on the sibling pages may need to be updated.
43941    **
43942    **   4) If the sibling pages are not internal intkey nodes, then any
43943    **      overflow pages used by these cells may need to be updated
43944    **      (internal intkey nodes never contain pointers to overflow pages).
43945    **
43946    **   5) If the sibling pages are not leaves, then the pointer-map
43947    **      entries for the right-child pages of each sibling may need
43948    **      to be updated.
43949    **
43950    ** Cases 1 and 2 are dealt with above by other code. The next
43951    ** block deals with cases 3 and 4 and the one after that, case 5. Since
43952    ** setting a pointer map entry is a relatively expensive operation, this
43953    ** code only sets pointer map entries for child or overflow pages that have
43954    ** actually moved between pages.  */
43955    MemPage *pNew = apNew[0];
43956    MemPage *pOld = apCopy[0];
43957    int nOverflow = pOld->nOverflow;
43958    int iNextOld = pOld->nCell + nOverflow;
43959    int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
43960    j = 0;                             /* Current 'old' sibling page */
43961    k = 0;                             /* Current 'new' sibling page */
43962    for(i=0; i<nCell; i++){
43963      int isDivider = 0;
43964      while( i==iNextOld ){
43965        /* Cell i is the cell immediately following the last cell on old
43966        ** sibling page j. If the siblings are not leaf pages of an
43967        ** intkey b-tree, then cell i was a divider cell. */
43968        pOld = apCopy[++j];
43969        iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
43970        if( pOld->nOverflow ){
43971          nOverflow = pOld->nOverflow;
43972          iOverflow = i + !leafData + pOld->aOvfl[0].idx;
43973        }
43974        isDivider = !leafData;
43975      }
43976
43977      assert(nOverflow>0 || iOverflow<i );
43978      assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
43979      assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
43980      if( i==iOverflow ){
43981        isDivider = 1;
43982        if( (--nOverflow)>0 ){
43983          iOverflow++;
43984        }
43985      }
43986
43987      if( i==cntNew[k] ){
43988        /* Cell i is the cell immediately following the last cell on new
43989        ** sibling page k. If the siblings are not leaf pages of an
43990        ** intkey b-tree, then cell i is a divider cell.  */
43991        pNew = apNew[++k];
43992        if( !leafData ) continue;
43993      }
43994      assert( j<nOld );
43995      assert( k<nNew );
43996
43997      /* If the cell was originally divider cell (and is not now) or
43998      ** an overflow cell, or if the cell was located on a different sibling
43999      ** page before the balancing, then the pointer map entries associated
44000      ** with any child or overflow pages need to be updated.  */
44001      if( isDivider || pOld->pgno!=pNew->pgno ){
44002        if( !leafCorrection ){
44003          ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
44004        }
44005        if( szCell[i]>pNew->minLocal ){
44006          ptrmapPutOvflPtr(pNew, apCell[i], &rc);
44007        }
44008      }
44009    }
44010
44011    if( !leafCorrection ){
44012      for(i=0; i<nNew; i++){
44013        u32 key = get4byte(&apNew[i]->aData[8]);
44014        ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
44015      }
44016    }
44017
44018#if 0
44019    /* The ptrmapCheckPages() contains assert() statements that verify that
44020    ** all pointer map pages are set correctly. This is helpful while
44021    ** debugging. This is usually disabled because a corrupt database may
44022    ** cause an assert() statement to fail.  */
44023    ptrmapCheckPages(apNew, nNew);
44024    ptrmapCheckPages(&pParent, 1);
44025#endif
44026  }
44027
44028  assert( pParent->isInit );
44029  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
44030          nOld, nNew, nCell));
44031
44032  /*
44033  ** Cleanup before returning.
44034  */
44035balance_cleanup:
44036  sqlite3ScratchFree(apCell);
44037  for(i=0; i<nOld; i++){
44038    releasePage(apOld[i]);
44039  }
44040  for(i=0; i<nNew; i++){
44041    releasePage(apNew[i]);
44042  }
44043
44044  return rc;
44045}
44046
44047
44048/*
44049** This function is called when the root page of a b-tree structure is
44050** overfull (has one or more overflow pages).
44051**
44052** A new child page is allocated and the contents of the current root
44053** page, including overflow cells, are copied into the child. The root
44054** page is then overwritten to make it an empty page with the right-child
44055** pointer pointing to the new page.
44056**
44057** Before returning, all pointer-map entries corresponding to pages
44058** that the new child-page now contains pointers to are updated. The
44059** entry corresponding to the new right-child pointer of the root
44060** page is also updated.
44061**
44062** If successful, *ppChild is set to contain a reference to the child
44063** page and SQLITE_OK is returned. In this case the caller is required
44064** to call releasePage() on *ppChild exactly once. If an error occurs,
44065** an error code is returned and *ppChild is set to 0.
44066*/
44067static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
44068  int rc;                        /* Return value from subprocedures */
44069  MemPage *pChild = 0;           /* Pointer to a new child page */
44070  Pgno pgnoChild = 0;            /* Page number of the new child page */
44071  BtShared *pBt = pRoot->pBt;    /* The BTree */
44072
44073  assert( pRoot->nOverflow>0 );
44074  assert( sqlite3_mutex_held(pBt->mutex) );
44075
44076  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
44077  ** page that will become the new right-child of pPage. Copy the contents
44078  ** of the node stored on pRoot into the new child page.
44079  */
44080  rc = sqlite3PagerWrite(pRoot->pDbPage);
44081  if( rc==SQLITE_OK ){
44082    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
44083    copyNodeContent(pRoot, pChild, &rc);
44084    if( ISAUTOVACUUM ){
44085      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
44086    }
44087  }
44088  if( rc ){
44089    *ppChild = 0;
44090    releasePage(pChild);
44091    return rc;
44092  }
44093  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
44094  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
44095  assert( pChild->nCell==pRoot->nCell );
44096
44097  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
44098
44099  /* Copy the overflow cells from pRoot to pChild */
44100  memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
44101  pChild->nOverflow = pRoot->nOverflow;
44102
44103  /* Zero the contents of pRoot. Then install pChild as the right-child. */
44104  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
44105  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
44106
44107  *ppChild = pChild;
44108  return SQLITE_OK;
44109}
44110
44111/*
44112** The page that pCur currently points to has just been modified in
44113** some way. This function figures out if this modification means the
44114** tree needs to be balanced, and if so calls the appropriate balancing
44115** routine. Balancing routines are:
44116**
44117**   balance_quick()
44118**   balance_deeper()
44119**   balance_nonroot()
44120*/
44121static int balance(BtCursor *pCur){
44122  int rc = SQLITE_OK;
44123  const int nMin = pCur->pBt->usableSize * 2 / 3;
44124  u8 aBalanceQuickSpace[13];
44125  u8 *pFree = 0;
44126
44127  TESTONLY( int balance_quick_called = 0 );
44128  TESTONLY( int balance_deeper_called = 0 );
44129
44130  do {
44131    int iPage = pCur->iPage;
44132    MemPage *pPage = pCur->apPage[iPage];
44133
44134    if( iPage==0 ){
44135      if( pPage->nOverflow ){
44136        /* The root page of the b-tree is overfull. In this case call the
44137        ** balance_deeper() function to create a new child for the root-page
44138        ** and copy the current contents of the root-page to it. The
44139        ** next iteration of the do-loop will balance the child page.
44140        */
44141        assert( (balance_deeper_called++)==0 );
44142        rc = balance_deeper(pPage, &pCur->apPage[1]);
44143        if( rc==SQLITE_OK ){
44144          pCur->iPage = 1;
44145          pCur->aiIdx[0] = 0;
44146          pCur->aiIdx[1] = 0;
44147          assert( pCur->apPage[1]->nOverflow );
44148        }
44149      }else{
44150        break;
44151      }
44152    }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
44153      break;
44154    }else{
44155      MemPage * const pParent = pCur->apPage[iPage-1];
44156      int const iIdx = pCur->aiIdx[iPage-1];
44157
44158      rc = sqlite3PagerWrite(pParent->pDbPage);
44159      if( rc==SQLITE_OK ){
44160#ifndef SQLITE_OMIT_QUICKBALANCE
44161        if( pPage->hasData
44162         && pPage->nOverflow==1
44163         && pPage->aOvfl[0].idx==pPage->nCell
44164         && pParent->pgno!=1
44165         && pParent->nCell==iIdx
44166        ){
44167          /* Call balance_quick() to create a new sibling of pPage on which
44168          ** to store the overflow cell. balance_quick() inserts a new cell
44169          ** into pParent, which may cause pParent overflow. If this
44170          ** happens, the next interation of the do-loop will balance pParent
44171          ** use either balance_nonroot() or balance_deeper(). Until this
44172          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
44173          ** buffer.
44174          **
44175          ** The purpose of the following assert() is to check that only a
44176          ** single call to balance_quick() is made for each call to this
44177          ** function. If this were not verified, a subtle bug involving reuse
44178          ** of the aBalanceQuickSpace[] might sneak in.
44179          */
44180          assert( (balance_quick_called++)==0 );
44181          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
44182        }else
44183#endif
44184        {
44185          /* In this case, call balance_nonroot() to redistribute cells
44186          ** between pPage and up to 2 of its sibling pages. This involves
44187          ** modifying the contents of pParent, which may cause pParent to
44188          ** become overfull or underfull. The next iteration of the do-loop
44189          ** will balance the parent page to correct this.
44190          **
44191          ** If the parent page becomes overfull, the overflow cell or cells
44192          ** are stored in the pSpace buffer allocated immediately below.
44193          ** A subsequent iteration of the do-loop will deal with this by
44194          ** calling balance_nonroot() (balance_deeper() may be called first,
44195          ** but it doesn't deal with overflow cells - just moves them to a
44196          ** different page). Once this subsequent call to balance_nonroot()
44197          ** has completed, it is safe to release the pSpace buffer used by
44198          ** the previous call, as the overflow cell data will have been
44199          ** copied either into the body of a database page or into the new
44200          ** pSpace buffer passed to the latter call to balance_nonroot().
44201          */
44202          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
44203          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
44204          if( pFree ){
44205            /* If pFree is not NULL, it points to the pSpace buffer used
44206            ** by a previous call to balance_nonroot(). Its contents are
44207            ** now stored either on real database pages or within the
44208            ** new pSpace buffer, so it may be safely freed here. */
44209            sqlite3PageFree(pFree);
44210          }
44211
44212          /* The pSpace buffer will be freed after the next call to
44213          ** balance_nonroot(), or just before this function returns, whichever
44214          ** comes first. */
44215          pFree = pSpace;
44216        }
44217      }
44218
44219      pPage->nOverflow = 0;
44220
44221      /* The next iteration of the do-loop balances the parent page. */
44222      releasePage(pPage);
44223      pCur->iPage--;
44224    }
44225  }while( rc==SQLITE_OK );
44226
44227  if( pFree ){
44228    sqlite3PageFree(pFree);
44229  }
44230  return rc;
44231}
44232
44233
44234/*
44235** Insert a new record into the BTree.  The key is given by (pKey,nKey)
44236** and the data is given by (pData,nData).  The cursor is used only to
44237** define what table the record should be inserted into.  The cursor
44238** is left pointing at a random location.
44239**
44240** For an INTKEY table, only the nKey value of the key is used.  pKey is
44241** ignored.  For a ZERODATA table, the pData and nData are both ignored.
44242**
44243** If the seekResult parameter is non-zero, then a successful call to
44244** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
44245** been performed. seekResult is the search result returned (a negative
44246** number if pCur points at an entry that is smaller than (pKey, nKey), or
44247** a positive value if pCur points at an etry that is larger than
44248** (pKey, nKey)).
44249**
44250** If the seekResult parameter is non-zero, then the caller guarantees that
44251** cursor pCur is pointing at the existing copy of a row that is to be
44252** overwritten.  If the seekResult parameter is 0, then cursor pCur may
44253** point to any entry or to no entry at all and so this function has to seek
44254** the cursor before the new key can be inserted.
44255*/
44256SQLITE_PRIVATE int sqlite3BtreeInsert(
44257  BtCursor *pCur,                /* Insert data into the table of this cursor */
44258  const void *pKey, i64 nKey,    /* The key of the new record */
44259  const void *pData, int nData,  /* The data of the new record */
44260  int nZero,                     /* Number of extra 0 bytes to append to data */
44261  int appendBias,                /* True if this is likely an append */
44262  int seekResult                 /* Result of prior MovetoUnpacked() call */
44263){
44264  int rc;
44265  int loc = seekResult;          /* -1: before desired location  +1: after */
44266  int szNew = 0;
44267  int idx;
44268  MemPage *pPage;
44269  Btree *p = pCur->pBtree;
44270  BtShared *pBt = p->pBt;
44271  unsigned char *oldCell;
44272  unsigned char *newCell = 0;
44273
44274  if( pCur->eState==CURSOR_FAULT ){
44275    assert( pCur->skipNext!=SQLITE_OK );
44276    return pCur->skipNext;
44277  }
44278
44279  assert( cursorHoldsMutex(pCur) );
44280  assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
44281  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
44282
44283  /* Assert that the caller has been consistent. If this cursor was opened
44284  ** expecting an index b-tree, then the caller should be inserting blob
44285  ** keys with no associated data. If the cursor was opened expecting an
44286  ** intkey table, the caller should be inserting integer keys with a
44287  ** blob of associated data.  */
44288  assert( (pKey==0)==(pCur->pKeyInfo==0) );
44289
44290  /* If this is an insert into a table b-tree, invalidate any incrblob
44291  ** cursors open on the row being replaced (assuming this is a replace
44292  ** operation - if it is not, the following is a no-op).  */
44293  if( pCur->pKeyInfo==0 ){
44294    invalidateIncrblobCursors(p, nKey, 0);
44295  }
44296
44297  /* Save the positions of any other cursors open on this table.
44298  **
44299  ** In some cases, the call to btreeMoveto() below is a no-op. For
44300  ** example, when inserting data into a table with auto-generated integer
44301  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
44302  ** integer key to use. It then calls this function to actually insert the
44303  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
44304  ** that the cursor is already where it needs to be and returns without
44305  ** doing any work. To avoid thwarting these optimizations, it is important
44306  ** not to clear the cursor here.
44307  */
44308  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
44309  if( rc ) return rc;
44310  if( !loc ){
44311    rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
44312    if( rc ) return rc;
44313  }
44314  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
44315
44316  pPage = pCur->apPage[pCur->iPage];
44317  assert( pPage->intKey || nKey>=0 );
44318  assert( pPage->leaf || !pPage->intKey );
44319
44320  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
44321          pCur->pgnoRoot, nKey, nData, pPage->pgno,
44322          loc==0 ? "overwrite" : "new entry"));
44323  assert( pPage->isInit );
44324  allocateTempSpace(pBt);
44325  newCell = pBt->pTmpSpace;
44326  if( newCell==0 ) return SQLITE_NOMEM;
44327  rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
44328  if( rc ) goto end_insert;
44329  assert( szNew==cellSizePtr(pPage, newCell) );
44330  assert( szNew<=MX_CELL_SIZE(pBt) );
44331  idx = pCur->aiIdx[pCur->iPage];
44332  if( loc==0 ){
44333    u16 szOld;
44334    assert( idx<pPage->nCell );
44335    rc = sqlite3PagerWrite(pPage->pDbPage);
44336    if( rc ){
44337      goto end_insert;
44338    }
44339    oldCell = findCell(pPage, idx);
44340    if( !pPage->leaf ){
44341      memcpy(newCell, oldCell, 4);
44342    }
44343    szOld = cellSizePtr(pPage, oldCell);
44344    rc = clearCell(pPage, oldCell);
44345    dropCell(pPage, idx, szOld, &rc);
44346    if( rc ) goto end_insert;
44347  }else if( loc<0 && pPage->nCell>0 ){
44348    assert( pPage->leaf );
44349    idx = ++pCur->aiIdx[pCur->iPage];
44350  }else{
44351    assert( pPage->leaf );
44352  }
44353  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
44354  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
44355
44356  /* If no error has occured and pPage has an overflow cell, call balance()
44357  ** to redistribute the cells within the tree. Since balance() may move
44358  ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
44359  ** variables.
44360  **
44361  ** Previous versions of SQLite called moveToRoot() to move the cursor
44362  ** back to the root page as balance() used to invalidate the contents
44363  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
44364  ** set the cursor state to "invalid". This makes common insert operations
44365  ** slightly faster.
44366  **
44367  ** There is a subtle but important optimization here too. When inserting
44368  ** multiple records into an intkey b-tree using a single cursor (as can
44369  ** happen while processing an "INSERT INTO ... SELECT" statement), it
44370  ** is advantageous to leave the cursor pointing to the last entry in
44371  ** the b-tree if possible. If the cursor is left pointing to the last
44372  ** entry in the table, and the next row inserted has an integer key
44373  ** larger than the largest existing key, it is possible to insert the
44374  ** row without seeking the cursor. This can be a big performance boost.
44375  */
44376  pCur->info.nSize = 0;
44377  pCur->validNKey = 0;
44378  if( rc==SQLITE_OK && pPage->nOverflow ){
44379    rc = balance(pCur);
44380
44381    /* Must make sure nOverflow is reset to zero even if the balance()
44382    ** fails. Internal data structure corruption will result otherwise.
44383    ** Also, set the cursor state to invalid. This stops saveCursorPosition()
44384    ** from trying to save the current position of the cursor.  */
44385    pCur->apPage[pCur->iPage]->nOverflow = 0;
44386    pCur->eState = CURSOR_INVALID;
44387  }
44388  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
44389
44390end_insert:
44391  return rc;
44392}
44393
44394/*
44395** Delete the entry that the cursor is pointing to.  The cursor
44396** is left pointing at a arbitrary location.
44397*/
44398SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
44399  Btree *p = pCur->pBtree;
44400  BtShared *pBt = p->pBt;
44401  int rc;                              /* Return code */
44402  MemPage *pPage;                      /* Page to delete cell from */
44403  unsigned char *pCell;                /* Pointer to cell to delete */
44404  int iCellIdx;                        /* Index of cell to delete */
44405  int iCellDepth;                      /* Depth of node containing pCell */
44406
44407  assert( cursorHoldsMutex(pCur) );
44408  assert( pBt->inTransaction==TRANS_WRITE );
44409  assert( !pBt->readOnly );
44410  assert( pCur->wrFlag );
44411  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
44412  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
44413
44414  if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
44415   || NEVER(pCur->eState!=CURSOR_VALID)
44416  ){
44417    return SQLITE_ERROR;  /* Something has gone awry. */
44418  }
44419
44420  /* If this is a delete operation to remove a row from a table b-tree,
44421  ** invalidate any incrblob cursors open on the row being deleted.  */
44422  if( pCur->pKeyInfo==0 ){
44423    invalidateIncrblobCursors(p, pCur->info.nKey, 0);
44424  }
44425
44426  iCellDepth = pCur->iPage;
44427  iCellIdx = pCur->aiIdx[iCellDepth];
44428  pPage = pCur->apPage[iCellDepth];
44429  pCell = findCell(pPage, iCellIdx);
44430
44431  /* If the page containing the entry to delete is not a leaf page, move
44432  ** the cursor to the largest entry in the tree that is smaller than
44433  ** the entry being deleted. This cell will replace the cell being deleted
44434  ** from the internal node. The 'previous' entry is used for this instead
44435  ** of the 'next' entry, as the previous entry is always a part of the
44436  ** sub-tree headed by the child page of the cell being deleted. This makes
44437  ** balancing the tree following the delete operation easier.  */
44438  if( !pPage->leaf ){
44439    int notUsed;
44440    rc = sqlite3BtreePrevious(pCur, &notUsed);
44441    if( rc ) return rc;
44442  }
44443
44444  /* Save the positions of any other cursors open on this table before
44445  ** making any modifications. Make the page containing the entry to be
44446  ** deleted writable. Then free any overflow pages associated with the
44447  ** entry and finally remove the cell itself from within the page.
44448  */
44449  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
44450  if( rc ) return rc;
44451  rc = sqlite3PagerWrite(pPage->pDbPage);
44452  if( rc ) return rc;
44453  rc = clearCell(pPage, pCell);
44454  dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
44455  if( rc ) return rc;
44456
44457  /* If the cell deleted was not located on a leaf page, then the cursor
44458  ** is currently pointing to the largest entry in the sub-tree headed
44459  ** by the child-page of the cell that was just deleted from an internal
44460  ** node. The cell from the leaf node needs to be moved to the internal
44461  ** node to replace the deleted cell.  */
44462  if( !pPage->leaf ){
44463    MemPage *pLeaf = pCur->apPage[pCur->iPage];
44464    int nCell;
44465    Pgno n = pCur->apPage[iCellDepth+1]->pgno;
44466    unsigned char *pTmp;
44467
44468    pCell = findCell(pLeaf, pLeaf->nCell-1);
44469    nCell = cellSizePtr(pLeaf, pCell);
44470    assert( MX_CELL_SIZE(pBt)>=nCell );
44471
44472    allocateTempSpace(pBt);
44473    pTmp = pBt->pTmpSpace;
44474
44475    rc = sqlite3PagerWrite(pLeaf->pDbPage);
44476    insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
44477    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
44478    if( rc ) return rc;
44479  }
44480
44481  /* Balance the tree. If the entry deleted was located on a leaf page,
44482  ** then the cursor still points to that page. In this case the first
44483  ** call to balance() repairs the tree, and the if(...) condition is
44484  ** never true.
44485  **
44486  ** Otherwise, if the entry deleted was on an internal node page, then
44487  ** pCur is pointing to the leaf page from which a cell was removed to
44488  ** replace the cell deleted from the internal node. This is slightly
44489  ** tricky as the leaf node may be underfull, and the internal node may
44490  ** be either under or overfull. In this case run the balancing algorithm
44491  ** on the leaf node first. If the balance proceeds far enough up the
44492  ** tree that we can be sure that any problem in the internal node has
44493  ** been corrected, so be it. Otherwise, after balancing the leaf node,
44494  ** walk the cursor up the tree to the internal node and balance it as
44495  ** well.  */
44496  rc = balance(pCur);
44497  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
44498    while( pCur->iPage>iCellDepth ){
44499      releasePage(pCur->apPage[pCur->iPage--]);
44500    }
44501    rc = balance(pCur);
44502  }
44503
44504  if( rc==SQLITE_OK ){
44505    moveToRoot(pCur);
44506  }
44507  return rc;
44508}
44509
44510/*
44511** Create a new BTree table.  Write into *piTable the page
44512** number for the root page of the new table.
44513**
44514** The type of type is determined by the flags parameter.  Only the
44515** following values of flags are currently in use.  Other values for
44516** flags might not work:
44517**
44518**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
44519**     BTREE_ZERODATA                  Used for SQL indices
44520*/
44521static int btreeCreateTable(Btree *p, int *piTable, int flags){
44522  BtShared *pBt = p->pBt;
44523  MemPage *pRoot;
44524  Pgno pgnoRoot;
44525  int rc;
44526
44527  assert( sqlite3BtreeHoldsMutex(p) );
44528  assert( pBt->inTransaction==TRANS_WRITE );
44529  assert( !pBt->readOnly );
44530
44531#ifdef SQLITE_OMIT_AUTOVACUUM
44532  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
44533  if( rc ){
44534    return rc;
44535  }
44536#else
44537  if( pBt->autoVacuum ){
44538    Pgno pgnoMove;      /* Move a page here to make room for the root-page */
44539    MemPage *pPageMove; /* The page to move to. */
44540
44541    /* Creating a new table may probably require moving an existing database
44542    ** to make room for the new tables root page. In case this page turns
44543    ** out to be an overflow page, delete all overflow page-map caches
44544    ** held by open cursors.
44545    */
44546    invalidateAllOverflowCache(pBt);
44547
44548    /* Read the value of meta[3] from the database to determine where the
44549    ** root page of the new table should go. meta[3] is the largest root-page
44550    ** created so far, so the new root-page is (meta[3]+1).
44551    */
44552    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
44553    pgnoRoot++;
44554
44555    /* The new root-page may not be allocated on a pointer-map page, or the
44556    ** PENDING_BYTE page.
44557    */
44558    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
44559        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
44560      pgnoRoot++;
44561    }
44562    assert( pgnoRoot>=3 );
44563
44564    /* Allocate a page. The page that currently resides at pgnoRoot will
44565    ** be moved to the allocated page (unless the allocated page happens
44566    ** to reside at pgnoRoot).
44567    */
44568    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
44569    if( rc!=SQLITE_OK ){
44570      return rc;
44571    }
44572
44573    if( pgnoMove!=pgnoRoot ){
44574      /* pgnoRoot is the page that will be used for the root-page of
44575      ** the new table (assuming an error did not occur). But we were
44576      ** allocated pgnoMove. If required (i.e. if it was not allocated
44577      ** by extending the file), the current page at position pgnoMove
44578      ** is already journaled.
44579      */
44580      u8 eType = 0;
44581      Pgno iPtrPage = 0;
44582
44583      releasePage(pPageMove);
44584
44585      /* Move the page currently at pgnoRoot to pgnoMove. */
44586      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
44587      if( rc!=SQLITE_OK ){
44588        return rc;
44589      }
44590      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
44591      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
44592        rc = SQLITE_CORRUPT_BKPT;
44593      }
44594      if( rc!=SQLITE_OK ){
44595        releasePage(pRoot);
44596        return rc;
44597      }
44598      assert( eType!=PTRMAP_ROOTPAGE );
44599      assert( eType!=PTRMAP_FREEPAGE );
44600      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
44601      releasePage(pRoot);
44602
44603      /* Obtain the page at pgnoRoot */
44604      if( rc!=SQLITE_OK ){
44605        return rc;
44606      }
44607      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
44608      if( rc!=SQLITE_OK ){
44609        return rc;
44610      }
44611      rc = sqlite3PagerWrite(pRoot->pDbPage);
44612      if( rc!=SQLITE_OK ){
44613        releasePage(pRoot);
44614        return rc;
44615      }
44616    }else{
44617      pRoot = pPageMove;
44618    }
44619
44620    /* Update the pointer-map and meta-data with the new root-page number. */
44621    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
44622    if( rc ){
44623      releasePage(pRoot);
44624      return rc;
44625    }
44626    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
44627    if( rc ){
44628      releasePage(pRoot);
44629      return rc;
44630    }
44631
44632  }else{
44633    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
44634    if( rc ) return rc;
44635  }
44636#endif
44637  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
44638  zeroPage(pRoot, flags | PTF_LEAF);
44639  sqlite3PagerUnref(pRoot->pDbPage);
44640  *piTable = (int)pgnoRoot;
44641  return SQLITE_OK;
44642}
44643SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
44644  int rc;
44645  sqlite3BtreeEnter(p);
44646  rc = btreeCreateTable(p, piTable, flags);
44647  sqlite3BtreeLeave(p);
44648  return rc;
44649}
44650
44651/*
44652** Erase the given database page and all its children.  Return
44653** the page to the freelist.
44654*/
44655static int clearDatabasePage(
44656  BtShared *pBt,           /* The BTree that contains the table */
44657  Pgno pgno,               /* Page number to clear */
44658  int freePageFlag,        /* Deallocate page if true */
44659  int *pnChange            /* Add number of Cells freed to this counter */
44660){
44661  MemPage *pPage;
44662  int rc;
44663  unsigned char *pCell;
44664  int i;
44665
44666  assert( sqlite3_mutex_held(pBt->mutex) );
44667  if( pgno>pagerPagecount(pBt) ){
44668    return SQLITE_CORRUPT_BKPT;
44669  }
44670
44671  rc = getAndInitPage(pBt, pgno, &pPage);
44672  if( rc ) return rc;
44673  for(i=0; i<pPage->nCell; i++){
44674    pCell = findCell(pPage, i);
44675    if( !pPage->leaf ){
44676      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
44677      if( rc ) goto cleardatabasepage_out;
44678    }
44679    rc = clearCell(pPage, pCell);
44680    if( rc ) goto cleardatabasepage_out;
44681  }
44682  if( !pPage->leaf ){
44683    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
44684    if( rc ) goto cleardatabasepage_out;
44685  }else if( pnChange ){
44686    assert( pPage->intKey );
44687    *pnChange += pPage->nCell;
44688  }
44689  if( freePageFlag ){
44690    freePage(pPage, &rc);
44691  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
44692    zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
44693  }
44694
44695cleardatabasepage_out:
44696  releasePage(pPage);
44697  return rc;
44698}
44699
44700/*
44701** Delete all information from a single table in the database.  iTable is
44702** the page number of the root of the table.  After this routine returns,
44703** the root page is empty, but still exists.
44704**
44705** This routine will fail with SQLITE_LOCKED if there are any open
44706** read cursors on the table.  Open write cursors are moved to the
44707** root of the table.
44708**
44709** If pnChange is not NULL, then table iTable must be an intkey table. The
44710** integer value pointed to by pnChange is incremented by the number of
44711** entries in the table.
44712*/
44713SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
44714  int rc;
44715  BtShared *pBt = p->pBt;
44716  sqlite3BtreeEnter(p);
44717  assert( p->inTrans==TRANS_WRITE );
44718
44719  /* Invalidate all incrblob cursors open on table iTable (assuming iTable
44720  ** is the root of a table b-tree - if it is not, the following call is
44721  ** a no-op).  */
44722  invalidateIncrblobCursors(p, 0, 1);
44723
44724  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
44725  if( SQLITE_OK==rc ){
44726    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
44727  }
44728  sqlite3BtreeLeave(p);
44729  return rc;
44730}
44731
44732/*
44733** Erase all information in a table and add the root of the table to
44734** the freelist.  Except, the root of the principle table (the one on
44735** page 1) is never added to the freelist.
44736**
44737** This routine will fail with SQLITE_LOCKED if there are any open
44738** cursors on the table.
44739**
44740** If AUTOVACUUM is enabled and the page at iTable is not the last
44741** root page in the database file, then the last root page
44742** in the database file is moved into the slot formerly occupied by
44743** iTable and that last slot formerly occupied by the last root page
44744** is added to the freelist instead of iTable.  In this say, all
44745** root pages are kept at the beginning of the database file, which
44746** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
44747** page number that used to be the last root page in the file before
44748** the move.  If no page gets moved, *piMoved is set to 0.
44749** The last root page is recorded in meta[3] and the value of
44750** meta[3] is updated by this procedure.
44751*/
44752static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
44753  int rc;
44754  MemPage *pPage = 0;
44755  BtShared *pBt = p->pBt;
44756
44757  assert( sqlite3BtreeHoldsMutex(p) );
44758  assert( p->inTrans==TRANS_WRITE );
44759
44760  /* It is illegal to drop a table if any cursors are open on the
44761  ** database. This is because in auto-vacuum mode the backend may
44762  ** need to move another root-page to fill a gap left by the deleted
44763  ** root page. If an open cursor was using this page a problem would
44764  ** occur.
44765  **
44766  ** This error is caught long before control reaches this point.
44767  */
44768  if( NEVER(pBt->pCursor) ){
44769    sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
44770    return SQLITE_LOCKED_SHAREDCACHE;
44771  }
44772
44773  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
44774  if( rc ) return rc;
44775  rc = sqlite3BtreeClearTable(p, iTable, 0);
44776  if( rc ){
44777    releasePage(pPage);
44778    return rc;
44779  }
44780
44781  *piMoved = 0;
44782
44783  if( iTable>1 ){
44784#ifdef SQLITE_OMIT_AUTOVACUUM
44785    freePage(pPage, &rc);
44786    releasePage(pPage);
44787#else
44788    if( pBt->autoVacuum ){
44789      Pgno maxRootPgno;
44790      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
44791
44792      if( iTable==maxRootPgno ){
44793        /* If the table being dropped is the table with the largest root-page
44794        ** number in the database, put the root page on the free list.
44795        */
44796        freePage(pPage, &rc);
44797        releasePage(pPage);
44798        if( rc!=SQLITE_OK ){
44799          return rc;
44800        }
44801      }else{
44802        /* The table being dropped does not have the largest root-page
44803        ** number in the database. So move the page that does into the
44804        ** gap left by the deleted root-page.
44805        */
44806        MemPage *pMove;
44807        releasePage(pPage);
44808        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
44809        if( rc!=SQLITE_OK ){
44810          return rc;
44811        }
44812        rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
44813        releasePage(pMove);
44814        if( rc!=SQLITE_OK ){
44815          return rc;
44816        }
44817        pMove = 0;
44818        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
44819        freePage(pMove, &rc);
44820        releasePage(pMove);
44821        if( rc!=SQLITE_OK ){
44822          return rc;
44823        }
44824        *piMoved = maxRootPgno;
44825      }
44826
44827      /* Set the new 'max-root-page' value in the database header. This
44828      ** is the old value less one, less one more if that happens to
44829      ** be a root-page number, less one again if that is the
44830      ** PENDING_BYTE_PAGE.
44831      */
44832      maxRootPgno--;
44833      while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
44834             || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
44835        maxRootPgno--;
44836      }
44837      assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
44838
44839      rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
44840    }else{
44841      freePage(pPage, &rc);
44842      releasePage(pPage);
44843    }
44844#endif
44845  }else{
44846    /* If sqlite3BtreeDropTable was called on page 1.
44847    ** This really never should happen except in a corrupt
44848    ** database.
44849    */
44850    zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
44851    releasePage(pPage);
44852  }
44853  return rc;
44854}
44855SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
44856  int rc;
44857  sqlite3BtreeEnter(p);
44858  rc = btreeDropTable(p, iTable, piMoved);
44859  sqlite3BtreeLeave(p);
44860  return rc;
44861}
44862
44863
44864/*
44865** This function may only be called if the b-tree connection already
44866** has a read or write transaction open on the database.
44867**
44868** Read the meta-information out of a database file.  Meta[0]
44869** is the number of free pages currently in the database.  Meta[1]
44870** through meta[15] are available for use by higher layers.  Meta[0]
44871** is read-only, the others are read/write.
44872**
44873** The schema layer numbers meta values differently.  At the schema
44874** layer (and the SetCookie and ReadCookie opcodes) the number of
44875** free pages is not visible.  So Cookie[0] is the same as Meta[1].
44876*/
44877SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
44878  BtShared *pBt = p->pBt;
44879
44880  sqlite3BtreeEnter(p);
44881  assert( p->inTrans>TRANS_NONE );
44882  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
44883  assert( pBt->pPage1 );
44884  assert( idx>=0 && idx<=15 );
44885
44886  *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
44887
44888  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
44889  ** database, mark the database as read-only.  */
44890#ifdef SQLITE_OMIT_AUTOVACUUM
44891  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
44892#endif
44893
44894  sqlite3BtreeLeave(p);
44895}
44896
44897/*
44898** Write meta-information back into the database.  Meta[0] is
44899** read-only and may not be written.
44900*/
44901SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
44902  BtShared *pBt = p->pBt;
44903  unsigned char *pP1;
44904  int rc;
44905  assert( idx>=1 && idx<=15 );
44906  sqlite3BtreeEnter(p);
44907  assert( p->inTrans==TRANS_WRITE );
44908  assert( pBt->pPage1!=0 );
44909  pP1 = pBt->pPage1->aData;
44910  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
44911  if( rc==SQLITE_OK ){
44912    put4byte(&pP1[36 + idx*4], iMeta);
44913#ifndef SQLITE_OMIT_AUTOVACUUM
44914    if( idx==BTREE_INCR_VACUUM ){
44915      assert( pBt->autoVacuum || iMeta==0 );
44916      assert( iMeta==0 || iMeta==1 );
44917      pBt->incrVacuum = (u8)iMeta;
44918    }
44919#endif
44920  }
44921  sqlite3BtreeLeave(p);
44922  return rc;
44923}
44924
44925#ifndef SQLITE_OMIT_BTREECOUNT
44926/*
44927** The first argument, pCur, is a cursor opened on some b-tree. Count the
44928** number of entries in the b-tree and write the result to *pnEntry.
44929**
44930** SQLITE_OK is returned if the operation is successfully executed.
44931** Otherwise, if an error is encountered (i.e. an IO error or database
44932** corruption) an SQLite error code is returned.
44933*/
44934SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
44935  i64 nEntry = 0;                      /* Value to return in *pnEntry */
44936  int rc;                              /* Return code */
44937  rc = moveToRoot(pCur);
44938
44939  /* Unless an error occurs, the following loop runs one iteration for each
44940  ** page in the B-Tree structure (not including overflow pages).
44941  */
44942  while( rc==SQLITE_OK ){
44943    int iIdx;                          /* Index of child node in parent */
44944    MemPage *pPage;                    /* Current page of the b-tree */
44945
44946    /* If this is a leaf page or the tree is not an int-key tree, then
44947    ** this page contains countable entries. Increment the entry counter
44948    ** accordingly.
44949    */
44950    pPage = pCur->apPage[pCur->iPage];
44951    if( pPage->leaf || !pPage->intKey ){
44952      nEntry += pPage->nCell;
44953    }
44954
44955    /* pPage is a leaf node. This loop navigates the cursor so that it
44956    ** points to the first interior cell that it points to the parent of
44957    ** the next page in the tree that has not yet been visited. The
44958    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
44959    ** of the page, or to the number of cells in the page if the next page
44960    ** to visit is the right-child of its parent.
44961    **
44962    ** If all pages in the tree have been visited, return SQLITE_OK to the
44963    ** caller.
44964    */
44965    if( pPage->leaf ){
44966      do {
44967        if( pCur->iPage==0 ){
44968          /* All pages of the b-tree have been visited. Return successfully. */
44969          *pnEntry = nEntry;
44970          return SQLITE_OK;
44971        }
44972        moveToParent(pCur);
44973      }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
44974
44975      pCur->aiIdx[pCur->iPage]++;
44976      pPage = pCur->apPage[pCur->iPage];
44977    }
44978
44979    /* Descend to the child node of the cell that the cursor currently
44980    ** points at. This is the right-child if (iIdx==pPage->nCell).
44981    */
44982    iIdx = pCur->aiIdx[pCur->iPage];
44983    if( iIdx==pPage->nCell ){
44984      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
44985    }else{
44986      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
44987    }
44988  }
44989
44990  /* An error has occurred. Return an error code. */
44991  return rc;
44992}
44993#endif
44994
44995/*
44996** Return the pager associated with a BTree.  This routine is used for
44997** testing and debugging only.
44998*/
44999SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
45000  return p->pBt->pPager;
45001}
45002
45003#ifndef SQLITE_OMIT_INTEGRITY_CHECK
45004/*
45005** Append a message to the error message string.
45006*/
45007static void checkAppendMsg(
45008  IntegrityCk *pCheck,
45009  char *zMsg1,
45010  const char *zFormat,
45011  ...
45012){
45013  va_list ap;
45014  if( !pCheck->mxErr ) return;
45015  pCheck->mxErr--;
45016  pCheck->nErr++;
45017  va_start(ap, zFormat);
45018  if( pCheck->errMsg.nChar ){
45019    sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
45020  }
45021  if( zMsg1 ){
45022    sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
45023  }
45024  sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
45025  va_end(ap);
45026  if( pCheck->errMsg.mallocFailed ){
45027    pCheck->mallocFailed = 1;
45028  }
45029}
45030#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
45031
45032#ifndef SQLITE_OMIT_INTEGRITY_CHECK
45033/*
45034** Add 1 to the reference count for page iPage.  If this is the second
45035** reference to the page, add an error message to pCheck->zErrMsg.
45036** Return 1 if there are 2 ore more references to the page and 0 if
45037** if this is the first reference to the page.
45038**
45039** Also check that the page number is in bounds.
45040*/
45041static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
45042  if( iPage==0 ) return 1;
45043  if( iPage>pCheck->nPage ){
45044    checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
45045    return 1;
45046  }
45047  if( pCheck->anRef[iPage]==1 ){
45048    checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
45049    return 1;
45050  }
45051  return  (pCheck->anRef[iPage]++)>1;
45052}
45053
45054#ifndef SQLITE_OMIT_AUTOVACUUM
45055/*
45056** Check that the entry in the pointer-map for page iChild maps to
45057** page iParent, pointer type ptrType. If not, append an error message
45058** to pCheck.
45059*/
45060static void checkPtrmap(
45061  IntegrityCk *pCheck,   /* Integrity check context */
45062  Pgno iChild,           /* Child page number */
45063  u8 eType,              /* Expected pointer map type */
45064  Pgno iParent,          /* Expected pointer map parent page number */
45065  char *zContext         /* Context description (used for error msg) */
45066){
45067  int rc;
45068  u8 ePtrmapType;
45069  Pgno iPtrmapParent;
45070
45071  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
45072  if( rc!=SQLITE_OK ){
45073    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
45074    checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
45075    return;
45076  }
45077
45078  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
45079    checkAppendMsg(pCheck, zContext,
45080      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
45081      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
45082  }
45083}
45084#endif
45085
45086/*
45087** Check the integrity of the freelist or of an overflow page list.
45088** Verify that the number of pages on the list is N.
45089*/
45090static void checkList(
45091  IntegrityCk *pCheck,  /* Integrity checking context */
45092  int isFreeList,       /* True for a freelist.  False for overflow page list */
45093  int iPage,            /* Page number for first page in the list */
45094  int N,                /* Expected number of pages in the list */
45095  char *zContext        /* Context for error messages */
45096){
45097  int i;
45098  int expected = N;
45099  int iFirst = iPage;
45100  while( N-- > 0 && pCheck->mxErr ){
45101    DbPage *pOvflPage;
45102    unsigned char *pOvflData;
45103    if( iPage<1 ){
45104      checkAppendMsg(pCheck, zContext,
45105         "%d of %d pages missing from overflow list starting at %d",
45106          N+1, expected, iFirst);
45107      break;
45108    }
45109    if( checkRef(pCheck, iPage, zContext) ) break;
45110    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
45111      checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
45112      break;
45113    }
45114    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
45115    if( isFreeList ){
45116      int n = get4byte(&pOvflData[4]);
45117#ifndef SQLITE_OMIT_AUTOVACUUM
45118      if( pCheck->pBt->autoVacuum ){
45119        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
45120      }
45121#endif
45122      if( n>pCheck->pBt->usableSize/4-2 ){
45123        checkAppendMsg(pCheck, zContext,
45124           "freelist leaf count too big on page %d", iPage);
45125        N--;
45126      }else{
45127        for(i=0; i<n; i++){
45128          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
45129#ifndef SQLITE_OMIT_AUTOVACUUM
45130          if( pCheck->pBt->autoVacuum ){
45131            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
45132          }
45133#endif
45134          checkRef(pCheck, iFreePage, zContext);
45135        }
45136        N -= n;
45137      }
45138    }
45139#ifndef SQLITE_OMIT_AUTOVACUUM
45140    else{
45141      /* If this database supports auto-vacuum and iPage is not the last
45142      ** page in this overflow list, check that the pointer-map entry for
45143      ** the following page matches iPage.
45144      */
45145      if( pCheck->pBt->autoVacuum && N>0 ){
45146        i = get4byte(pOvflData);
45147        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
45148      }
45149    }
45150#endif
45151    iPage = get4byte(pOvflData);
45152    sqlite3PagerUnref(pOvflPage);
45153  }
45154}
45155#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
45156
45157#ifndef SQLITE_OMIT_INTEGRITY_CHECK
45158/*
45159** Do various sanity checks on a single page of a tree.  Return
45160** the tree depth.  Root pages return 0.  Parents of root pages
45161** return 1, and so forth.
45162**
45163** These checks are done:
45164**
45165**      1.  Make sure that cells and freeblocks do not overlap
45166**          but combine to completely cover the page.
45167**  NO  2.  Make sure cell keys are in order.
45168**  NO  3.  Make sure no key is less than or equal to zLowerBound.
45169**  NO  4.  Make sure no key is greater than or equal to zUpperBound.
45170**      5.  Check the integrity of overflow pages.
45171**      6.  Recursively call checkTreePage on all children.
45172**      7.  Verify that the depth of all children is the same.
45173**      8.  Make sure this page is at least 33% full or else it is
45174**          the root of the tree.
45175*/
45176static int checkTreePage(
45177  IntegrityCk *pCheck,  /* Context for the sanity check */
45178  int iPage,            /* Page number of the page to check */
45179  char *zParentContext, /* Parent context */
45180  i64 *pnParentMinKey,
45181  i64 *pnParentMaxKey
45182){
45183  MemPage *pPage;
45184  int i, rc, depth, d2, pgno, cnt;
45185  int hdr, cellStart;
45186  int nCell;
45187  u8 *data;
45188  BtShared *pBt;
45189  int usableSize;
45190  char zContext[100];
45191  char *hit = 0;
45192  i64 nMinKey = 0;
45193  i64 nMaxKey = 0;
45194
45195  sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
45196
45197  /* Check that the page exists
45198  */
45199  pBt = pCheck->pBt;
45200  usableSize = pBt->usableSize;
45201  if( iPage==0 ) return 0;
45202  if( checkRef(pCheck, iPage, zParentContext) ) return 0;
45203  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
45204    checkAppendMsg(pCheck, zContext,
45205       "unable to get the page. error code=%d", rc);
45206    return 0;
45207  }
45208
45209  /* Clear MemPage.isInit to make sure the corruption detection code in
45210  ** btreeInitPage() is executed.  */
45211  pPage->isInit = 0;
45212  if( (rc = btreeInitPage(pPage))!=0 ){
45213    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
45214    checkAppendMsg(pCheck, zContext,
45215                   "btreeInitPage() returns error code %d", rc);
45216    releasePage(pPage);
45217    return 0;
45218  }
45219
45220  /* Check out all the cells.
45221  */
45222  depth = 0;
45223  for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
45224    u8 *pCell;
45225    u32 sz;
45226    CellInfo info;
45227
45228    /* Check payload overflow pages
45229    */
45230    sqlite3_snprintf(sizeof(zContext), zContext,
45231             "On tree page %d cell %d: ", iPage, i);
45232    pCell = findCell(pPage,i);
45233    btreeParseCellPtr(pPage, pCell, &info);
45234    sz = info.nData;
45235    if( !pPage->intKey ) sz += (int)info.nKey;
45236    /* For intKey pages, check that the keys are in order.
45237    */
45238    else if( i==0 ) nMinKey = nMaxKey = info.nKey;
45239    else{
45240      if( info.nKey <= nMaxKey ){
45241        checkAppendMsg(pCheck, zContext,
45242            "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
45243      }
45244      nMaxKey = info.nKey;
45245    }
45246    assert( sz==info.nPayload );
45247    if( (sz>info.nLocal)
45248     && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
45249    ){
45250      int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
45251      Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
45252#ifndef SQLITE_OMIT_AUTOVACUUM
45253      if( pBt->autoVacuum ){
45254        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
45255      }
45256#endif
45257      checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
45258    }
45259
45260    /* Check sanity of left child page.
45261    */
45262    if( !pPage->leaf ){
45263      pgno = get4byte(pCell);
45264#ifndef SQLITE_OMIT_AUTOVACUUM
45265      if( pBt->autoVacuum ){
45266        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
45267      }
45268#endif
45269      d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
45270      if( i>0 && d2!=depth ){
45271        checkAppendMsg(pCheck, zContext, "Child page depth differs");
45272      }
45273      depth = d2;
45274    }
45275  }
45276
45277  if( !pPage->leaf ){
45278    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
45279    sqlite3_snprintf(sizeof(zContext), zContext,
45280                     "On page %d at right child: ", iPage);
45281#ifndef SQLITE_OMIT_AUTOVACUUM
45282    if( pBt->autoVacuum ){
45283      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
45284    }
45285#endif
45286    checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
45287  }
45288
45289  /* For intKey leaf pages, check that the min/max keys are in order
45290  ** with any left/parent/right pages.
45291  */
45292  if( pPage->leaf && pPage->intKey ){
45293    /* if we are a left child page */
45294    if( pnParentMinKey ){
45295      /* if we are the left most child page */
45296      if( !pnParentMaxKey ){
45297        if( nMaxKey > *pnParentMinKey ){
45298          checkAppendMsg(pCheck, zContext,
45299              "Rowid %lld out of order (max larger than parent min of %lld)",
45300              nMaxKey, *pnParentMinKey);
45301        }
45302      }else{
45303        if( nMinKey <= *pnParentMinKey ){
45304          checkAppendMsg(pCheck, zContext,
45305              "Rowid %lld out of order (min less than parent min of %lld)",
45306              nMinKey, *pnParentMinKey);
45307        }
45308        if( nMaxKey > *pnParentMaxKey ){
45309          checkAppendMsg(pCheck, zContext,
45310              "Rowid %lld out of order (max larger than parent max of %lld)",
45311              nMaxKey, *pnParentMaxKey);
45312        }
45313        *pnParentMinKey = nMaxKey;
45314      }
45315    /* else if we're a right child page */
45316    } else if( pnParentMaxKey ){
45317      if( nMinKey <= *pnParentMaxKey ){
45318        checkAppendMsg(pCheck, zContext,
45319            "Rowid %lld out of order (min less than parent max of %lld)",
45320            nMinKey, *pnParentMaxKey);
45321      }
45322    }
45323  }
45324
45325  /* Check for complete coverage of the page
45326  */
45327  data = pPage->aData;
45328  hdr = pPage->hdrOffset;
45329  hit = sqlite3PageMalloc( pBt->pageSize );
45330  if( hit==0 ){
45331    pCheck->mallocFailed = 1;
45332  }else{
45333    u16 contentOffset = get2byte(&data[hdr+5]);
45334    assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
45335    memset(hit+contentOffset, 0, usableSize-contentOffset);
45336    memset(hit, 1, contentOffset);
45337    nCell = get2byte(&data[hdr+3]);
45338    cellStart = hdr + 12 - 4*pPage->leaf;
45339    for(i=0; i<nCell; i++){
45340      int pc = get2byte(&data[cellStart+i*2]);
45341      u16 size = 1024;
45342      int j;
45343      if( pc<=usableSize-4 ){
45344        size = cellSizePtr(pPage, &data[pc]);
45345      }
45346      if( (pc+size-1)>=usableSize ){
45347        checkAppendMsg(pCheck, 0,
45348            "Corruption detected in cell %d on page %d",i,iPage);
45349      }else{
45350        for(j=pc+size-1; j>=pc; j--) hit[j]++;
45351      }
45352    }
45353    i = get2byte(&data[hdr+1]);
45354    while( i>0 ){
45355      int size, j;
45356      assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
45357      size = get2byte(&data[i+2]);
45358      assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
45359      for(j=i+size-1; j>=i; j--) hit[j]++;
45360      j = get2byte(&data[i]);
45361      assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
45362      assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
45363      i = j;
45364    }
45365    for(i=cnt=0; i<usableSize; i++){
45366      if( hit[i]==0 ){
45367        cnt++;
45368      }else if( hit[i]>1 ){
45369        checkAppendMsg(pCheck, 0,
45370          "Multiple uses for byte %d of page %d", i, iPage);
45371        break;
45372      }
45373    }
45374    if( cnt!=data[hdr+7] ){
45375      checkAppendMsg(pCheck, 0,
45376          "Fragmentation of %d bytes reported as %d on page %d",
45377          cnt, data[hdr+7], iPage);
45378    }
45379  }
45380  sqlite3PageFree(hit);
45381  releasePage(pPage);
45382  return depth+1;
45383}
45384#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
45385
45386#ifndef SQLITE_OMIT_INTEGRITY_CHECK
45387/*
45388** This routine does a complete check of the given BTree file.  aRoot[] is
45389** an array of pages numbers were each page number is the root page of
45390** a table.  nRoot is the number of entries in aRoot.
45391**
45392** A read-only or read-write transaction must be opened before calling
45393** this function.
45394**
45395** Write the number of error seen in *pnErr.  Except for some memory
45396** allocation errors,  an error message held in memory obtained from
45397** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
45398** returned.  If a memory allocation error occurs, NULL is returned.
45399*/
45400SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
45401  Btree *p,     /* The btree to be checked */
45402  int *aRoot,   /* An array of root pages numbers for individual trees */
45403  int nRoot,    /* Number of entries in aRoot[] */
45404  int mxErr,    /* Stop reporting errors after this many */
45405  int *pnErr    /* Write number of errors seen to this variable */
45406){
45407  Pgno i;
45408  int nRef;
45409  IntegrityCk sCheck;
45410  BtShared *pBt = p->pBt;
45411  char zErr[100];
45412
45413  sqlite3BtreeEnter(p);
45414  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
45415  nRef = sqlite3PagerRefcount(pBt->pPager);
45416  sCheck.pBt = pBt;
45417  sCheck.pPager = pBt->pPager;
45418  sCheck.nPage = pagerPagecount(sCheck.pBt);
45419  sCheck.mxErr = mxErr;
45420  sCheck.nErr = 0;
45421  sCheck.mallocFailed = 0;
45422  *pnErr = 0;
45423  if( sCheck.nPage==0 ){
45424    sqlite3BtreeLeave(p);
45425    return 0;
45426  }
45427  sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
45428  if( !sCheck.anRef ){
45429    *pnErr = 1;
45430    sqlite3BtreeLeave(p);
45431    return 0;
45432  }
45433  for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
45434  i = PENDING_BYTE_PAGE(pBt);
45435  if( i<=sCheck.nPage ){
45436    sCheck.anRef[i] = 1;
45437  }
45438  sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
45439
45440  /* Check the integrity of the freelist
45441  */
45442  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
45443            get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
45444
45445  /* Check all the tables.
45446  */
45447  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
45448    if( aRoot[i]==0 ) continue;
45449#ifndef SQLITE_OMIT_AUTOVACUUM
45450    if( pBt->autoVacuum && aRoot[i]>1 ){
45451      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
45452    }
45453#endif
45454    checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
45455  }
45456
45457  /* Make sure every page in the file is referenced
45458  */
45459  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
45460#ifdef SQLITE_OMIT_AUTOVACUUM
45461    if( sCheck.anRef[i]==0 ){
45462      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
45463    }
45464#else
45465    /* If the database supports auto-vacuum, make sure no tables contain
45466    ** references to pointer-map pages.
45467    */
45468    if( sCheck.anRef[i]==0 &&
45469       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
45470      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
45471    }
45472    if( sCheck.anRef[i]!=0 &&
45473       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
45474      checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
45475    }
45476#endif
45477  }
45478
45479  /* Make sure this analysis did not leave any unref() pages.
45480  ** This is an internal consistency check; an integrity check
45481  ** of the integrity check.
45482  */
45483  if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
45484    checkAppendMsg(&sCheck, 0,
45485      "Outstanding page count goes from %d to %d during this analysis",
45486      nRef, sqlite3PagerRefcount(pBt->pPager)
45487    );
45488  }
45489
45490  /* Clean  up and report errors.
45491  */
45492  sqlite3BtreeLeave(p);
45493  sqlite3_free(sCheck.anRef);
45494  if( sCheck.mallocFailed ){
45495    sqlite3StrAccumReset(&sCheck.errMsg);
45496    *pnErr = sCheck.nErr+1;
45497    return 0;
45498  }
45499  *pnErr = sCheck.nErr;
45500  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
45501  return sqlite3StrAccumFinish(&sCheck.errMsg);
45502}
45503#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
45504
45505/*
45506** Return the full pathname of the underlying database file.
45507**
45508** The pager filename is invariant as long as the pager is
45509** open so it is safe to access without the BtShared mutex.
45510*/
45511SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
45512  assert( p->pBt->pPager!=0 );
45513  return sqlite3PagerFilename(p->pBt->pPager);
45514}
45515
45516/*
45517** Return the pathname of the journal file for this database. The return
45518** value of this routine is the same regardless of whether the journal file
45519** has been created or not.
45520**
45521** The pager journal filename is invariant as long as the pager is
45522** open so it is safe to access without the BtShared mutex.
45523*/
45524SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
45525  assert( p->pBt->pPager!=0 );
45526  return sqlite3PagerJournalname(p->pBt->pPager);
45527}
45528
45529/*
45530** Return non-zero if a transaction is active.
45531*/
45532SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
45533  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
45534  return (p && (p->inTrans==TRANS_WRITE));
45535}
45536
45537/*
45538** Return non-zero if a read (or write) transaction is active.
45539*/
45540SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
45541  assert( p );
45542  assert( sqlite3_mutex_held(p->db->mutex) );
45543  return p->inTrans!=TRANS_NONE;
45544}
45545
45546SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
45547  assert( p );
45548  assert( sqlite3_mutex_held(p->db->mutex) );
45549  return p->nBackup!=0;
45550}
45551
45552/*
45553** This function returns a pointer to a blob of memory associated with
45554** a single shared-btree. The memory is used by client code for its own
45555** purposes (for example, to store a high-level schema associated with
45556** the shared-btree). The btree layer manages reference counting issues.
45557**
45558** The first time this is called on a shared-btree, nBytes bytes of memory
45559** are allocated, zeroed, and returned to the caller. For each subsequent
45560** call the nBytes parameter is ignored and a pointer to the same blob
45561** of memory returned.
45562**
45563** If the nBytes parameter is 0 and the blob of memory has not yet been
45564** allocated, a null pointer is returned. If the blob has already been
45565** allocated, it is returned as normal.
45566**
45567** Just before the shared-btree is closed, the function passed as the
45568** xFree argument when the memory allocation was made is invoked on the
45569** blob of allocated memory. This function should not call sqlite3_free()
45570** on the memory, the btree layer does that.
45571*/
45572SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
45573  BtShared *pBt = p->pBt;
45574  sqlite3BtreeEnter(p);
45575  if( !pBt->pSchema && nBytes ){
45576    pBt->pSchema = sqlite3MallocZero(nBytes);
45577    pBt->xFreeSchema = xFree;
45578  }
45579  sqlite3BtreeLeave(p);
45580  return pBt->pSchema;
45581}
45582
45583/*
45584** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
45585** btree as the argument handle holds an exclusive lock on the
45586** sqlite_master table. Otherwise SQLITE_OK.
45587*/
45588SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
45589  int rc;
45590  assert( sqlite3_mutex_held(p->db->mutex) );
45591  sqlite3BtreeEnter(p);
45592  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
45593  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
45594  sqlite3BtreeLeave(p);
45595  return rc;
45596}
45597
45598
45599#ifndef SQLITE_OMIT_SHARED_CACHE
45600/*
45601** Obtain a lock on the table whose root page is iTab.  The
45602** lock is a write lock if isWritelock is true or a read lock
45603** if it is false.
45604*/
45605SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
45606  int rc = SQLITE_OK;
45607  assert( p->inTrans!=TRANS_NONE );
45608  if( p->sharable ){
45609    u8 lockType = READ_LOCK + isWriteLock;
45610    assert( READ_LOCK+1==WRITE_LOCK );
45611    assert( isWriteLock==0 || isWriteLock==1 );
45612
45613    sqlite3BtreeEnter(p);
45614    rc = querySharedCacheTableLock(p, iTab, lockType);
45615    if( rc==SQLITE_OK ){
45616      rc = setSharedCacheTableLock(p, iTab, lockType);
45617    }
45618    sqlite3BtreeLeave(p);
45619  }
45620  return rc;
45621}
45622#endif
45623
45624#ifndef SQLITE_OMIT_INCRBLOB
45625/*
45626** Argument pCsr must be a cursor opened for writing on an
45627** INTKEY table currently pointing at a valid table entry.
45628** This function modifies the data stored as part of that entry.
45629**
45630** Only the data content may only be modified, it is not possible to
45631** change the length of the data stored. If this function is called with
45632** parameters that attempt to write past the end of the existing data,
45633** no modifications are made and SQLITE_CORRUPT is returned.
45634*/
45635SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
45636  int rc;
45637  assert( cursorHoldsMutex(pCsr) );
45638  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
45639  assert( pCsr->isIncrblobHandle );
45640
45641  rc = restoreCursorPosition(pCsr);
45642  if( rc!=SQLITE_OK ){
45643    return rc;
45644  }
45645  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
45646  if( pCsr->eState!=CURSOR_VALID ){
45647    return SQLITE_ABORT;
45648  }
45649
45650  /* Check some assumptions:
45651  **   (a) the cursor is open for writing,
45652  **   (b) there is a read/write transaction open,
45653  **   (c) the connection holds a write-lock on the table (if required),
45654  **   (d) there are no conflicting read-locks, and
45655  **   (e) the cursor points at a valid row of an intKey table.
45656  */
45657  if( !pCsr->wrFlag ){
45658    return SQLITE_READONLY;
45659  }
45660  assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
45661  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
45662  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
45663  assert( pCsr->apPage[pCsr->iPage]->intKey );
45664
45665  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
45666}
45667
45668/*
45669** Set a flag on this cursor to cache the locations of pages from the
45670** overflow list for the current row. This is used by cursors opened
45671** for incremental blob IO only.
45672**
45673** This function sets a flag only. The actual page location cache
45674** (stored in BtCursor.aOverflow[]) is allocated and used by function
45675** accessPayload() (the worker function for sqlite3BtreeData() and
45676** sqlite3BtreePutData()).
45677*/
45678SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
45679  assert( cursorHoldsMutex(pCur) );
45680  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
45681  assert(!pCur->isIncrblobHandle);
45682  assert(!pCur->aOverflow);
45683  pCur->isIncrblobHandle = 1;
45684}
45685#endif
45686
45687/************** End of btree.c ***********************************************/
45688/************** Begin file backup.c ******************************************/
45689/*
45690** 2009 January 28
45691**
45692** The author disclaims copyright to this source code.  In place of
45693** a legal notice, here is a blessing:
45694**
45695**    May you do good and not evil.
45696**    May you find forgiveness for yourself and forgive others.
45697**    May you share freely, never taking more than you give.
45698**
45699*************************************************************************
45700** This file contains the implementation of the sqlite3_backup_XXX()
45701** API functions and the related features.
45702*/
45703
45704/* Macro to find the minimum of two numeric values.
45705*/
45706#ifndef MIN
45707# define MIN(x,y) ((x)<(y)?(x):(y))
45708#endif
45709
45710/*
45711** Structure allocated for each backup operation.
45712*/
45713struct sqlite3_backup {
45714  sqlite3* pDestDb;        /* Destination database handle */
45715  Btree *pDest;            /* Destination b-tree file */
45716  u32 iDestSchema;         /* Original schema cookie in destination */
45717  int bDestLocked;         /* True once a write-transaction is open on pDest */
45718
45719  Pgno iNext;              /* Page number of the next source page to copy */
45720  sqlite3* pSrcDb;         /* Source database handle */
45721  Btree *pSrc;             /* Source b-tree file */
45722
45723  int rc;                  /* Backup process error code */
45724
45725  /* These two variables are set by every call to backup_step(). They are
45726  ** read by calls to backup_remaining() and backup_pagecount().
45727  */
45728  Pgno nRemaining;         /* Number of pages left to copy */
45729  Pgno nPagecount;         /* Total number of pages to copy */
45730
45731  int isAttached;          /* True once backup has been registered with pager */
45732  sqlite3_backup *pNext;   /* Next backup associated with source pager */
45733};
45734
45735/*
45736** THREAD SAFETY NOTES:
45737**
45738**   Once it has been created using backup_init(), a single sqlite3_backup
45739**   structure may be accessed via two groups of thread-safe entry points:
45740**
45741**     * Via the sqlite3_backup_XXX() API function backup_step() and
45742**       backup_finish(). Both these functions obtain the source database
45743**       handle mutex and the mutex associated with the source BtShared
45744**       structure, in that order.
45745**
45746**     * Via the BackupUpdate() and BackupRestart() functions, which are
45747**       invoked by the pager layer to report various state changes in
45748**       the page cache associated with the source database. The mutex
45749**       associated with the source database BtShared structure will always
45750**       be held when either of these functions are invoked.
45751**
45752**   The other sqlite3_backup_XXX() API functions, backup_remaining() and
45753**   backup_pagecount() are not thread-safe functions. If they are called
45754**   while some other thread is calling backup_step() or backup_finish(),
45755**   the values returned may be invalid. There is no way for a call to
45756**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
45757**   or backup_pagecount().
45758**
45759**   Depending on the SQLite configuration, the database handles and/or
45760**   the Btree objects may have their own mutexes that require locking.
45761**   Non-sharable Btrees (in-memory databases for example), do not have
45762**   associated mutexes.
45763*/
45764
45765/*
45766** Return a pointer corresponding to database zDb (i.e. "main", "temp")
45767** in connection handle pDb. If such a database cannot be found, return
45768** a NULL pointer and write an error message to pErrorDb.
45769**
45770** If the "temp" database is requested, it may need to be opened by this
45771** function. If an error occurs while doing so, return 0 and write an
45772** error message to pErrorDb.
45773*/
45774static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
45775  int i = sqlite3FindDbName(pDb, zDb);
45776
45777  if( i==1 ){
45778    Parse *pParse;
45779    int rc = 0;
45780    pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
45781    if( pParse==0 ){
45782      sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
45783      rc = SQLITE_NOMEM;
45784    }else{
45785      pParse->db = pDb;
45786      if( sqlite3OpenTempDatabase(pParse) ){
45787        sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
45788        rc = SQLITE_ERROR;
45789      }
45790      sqlite3DbFree(pErrorDb, pParse->zErrMsg);
45791      sqlite3StackFree(pErrorDb, pParse);
45792    }
45793    if( rc ){
45794      return 0;
45795    }
45796  }
45797
45798  if( i<0 ){
45799    sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
45800    return 0;
45801  }
45802
45803  return pDb->aDb[i].pBt;
45804}
45805
45806/*
45807** Create an sqlite3_backup process to copy the contents of zSrcDb from
45808** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
45809** a pointer to the new sqlite3_backup object.
45810**
45811** If an error occurs, NULL is returned and an error code and error message
45812** stored in database handle pDestDb.
45813*/
45814SQLITE_API sqlite3_backup *sqlite3_backup_init(
45815  sqlite3* pDestDb,                     /* Database to write to */
45816  const char *zDestDb,                  /* Name of database within pDestDb */
45817  sqlite3* pSrcDb,                      /* Database connection to read from */
45818  const char *zSrcDb                    /* Name of database within pSrcDb */
45819){
45820  sqlite3_backup *p;                    /* Value to return */
45821
45822  /* Lock the source database handle. The destination database
45823  ** handle is not locked in this routine, but it is locked in
45824  ** sqlite3_backup_step(). The user is required to ensure that no
45825  ** other thread accesses the destination handle for the duration
45826  ** of the backup operation.  Any attempt to use the destination
45827  ** database connection while a backup is in progress may cause
45828  ** a malfunction or a deadlock.
45829  */
45830  sqlite3_mutex_enter(pSrcDb->mutex);
45831  sqlite3_mutex_enter(pDestDb->mutex);
45832
45833  if( pSrcDb==pDestDb ){
45834    sqlite3Error(
45835        pDestDb, SQLITE_ERROR, "source and destination must be distinct"
45836    );
45837    p = 0;
45838  }else {
45839    /* Allocate space for a new sqlite3_backup object */
45840    p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
45841    if( !p ){
45842      sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
45843    }
45844  }
45845
45846  /* If the allocation succeeded, populate the new object. */
45847  if( p ){
45848    memset(p, 0, sizeof(sqlite3_backup));
45849    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
45850    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
45851    p->pDestDb = pDestDb;
45852    p->pSrcDb = pSrcDb;
45853    p->iNext = 1;
45854    p->isAttached = 0;
45855
45856    if( 0==p->pSrc || 0==p->pDest ){
45857      /* One (or both) of the named databases did not exist. An error has
45858      ** already been written into the pDestDb handle. All that is left
45859      ** to do here is free the sqlite3_backup structure.
45860      */
45861      sqlite3_free(p);
45862      p = 0;
45863    }
45864  }
45865  if( p ){
45866    p->pSrc->nBackup++;
45867  }
45868
45869  sqlite3_mutex_leave(pDestDb->mutex);
45870  sqlite3_mutex_leave(pSrcDb->mutex);
45871  return p;
45872}
45873
45874/*
45875** Argument rc is an SQLite error code. Return true if this error is
45876** considered fatal if encountered during a backup operation. All errors
45877** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
45878*/
45879static int isFatalError(int rc){
45880  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
45881}
45882
45883/*
45884** Parameter zSrcData points to a buffer containing the data for
45885** page iSrcPg from the source database. Copy this data into the
45886** destination database.
45887*/
45888static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
45889  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
45890  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
45891  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
45892  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
45893  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
45894
45895  int rc = SQLITE_OK;
45896  i64 iOff;
45897
45898  assert( p->bDestLocked );
45899  assert( !isFatalError(p->rc) );
45900  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
45901  assert( zSrcData );
45902
45903  /* Catch the case where the destination is an in-memory database and the
45904  ** page sizes of the source and destination differ.
45905  */
45906  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(sqlite3BtreePager(p->pDest)) ){
45907    rc = SQLITE_READONLY;
45908  }
45909
45910  /* This loop runs once for each destination page spanned by the source
45911  ** page. For each iteration, variable iOff is set to the byte offset
45912  ** of the destination page.
45913  */
45914  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
45915    DbPage *pDestPg = 0;
45916    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
45917    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
45918    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
45919     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
45920    ){
45921      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
45922      u8 *zDestData = sqlite3PagerGetData(pDestPg);
45923      u8 *zOut = &zDestData[iOff%nDestPgsz];
45924
45925      /* Copy the data from the source page into the destination page.
45926      ** Then clear the Btree layer MemPage.isInit flag. Both this module
45927      ** and the pager code use this trick (clearing the first byte
45928      ** of the page 'extra' space to invalidate the Btree layers
45929      ** cached parse of the page). MemPage.isInit is marked
45930      ** "MUST BE FIRST" for this purpose.
45931      */
45932      memcpy(zOut, zIn, nCopy);
45933      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
45934    }
45935    sqlite3PagerUnref(pDestPg);
45936  }
45937
45938  return rc;
45939}
45940
45941/*
45942** If pFile is currently larger than iSize bytes, then truncate it to
45943** exactly iSize bytes. If pFile is not larger than iSize bytes, then
45944** this function is a no-op.
45945**
45946** Return SQLITE_OK if everything is successful, or an SQLite error
45947** code if an error occurs.
45948*/
45949static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
45950  i64 iCurrent;
45951  int rc = sqlite3OsFileSize(pFile, &iCurrent);
45952  if( rc==SQLITE_OK && iCurrent>iSize ){
45953    rc = sqlite3OsTruncate(pFile, iSize);
45954  }
45955  return rc;
45956}
45957
45958/*
45959** Register this backup object with the associated source pager for
45960** callbacks when pages are changed or the cache invalidated.
45961*/
45962static void attachBackupObject(sqlite3_backup *p){
45963  sqlite3_backup **pp;
45964  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
45965  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
45966  p->pNext = *pp;
45967  *pp = p;
45968  p->isAttached = 1;
45969}
45970
45971/*
45972** Copy nPage pages from the source b-tree to the destination.
45973*/
45974SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
45975  int rc;
45976
45977  sqlite3_mutex_enter(p->pSrcDb->mutex);
45978  sqlite3BtreeEnter(p->pSrc);
45979  if( p->pDestDb ){
45980    sqlite3_mutex_enter(p->pDestDb->mutex);
45981  }
45982
45983  rc = p->rc;
45984  if( !isFatalError(rc) ){
45985    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
45986    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
45987    int ii;                            /* Iterator variable */
45988    int nSrcPage = -1;                 /* Size of source db in pages */
45989    int bCloseTrans = 0;               /* True if src db requires unlocking */
45990
45991    /* If the source pager is currently in a write-transaction, return
45992    ** SQLITE_BUSY immediately.
45993    */
45994    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
45995      rc = SQLITE_BUSY;
45996    }else{
45997      rc = SQLITE_OK;
45998    }
45999
46000    /* Lock the destination database, if it is not locked already. */
46001    if( SQLITE_OK==rc && p->bDestLocked==0
46002     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
46003    ){
46004      p->bDestLocked = 1;
46005      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
46006    }
46007
46008    /* If there is no open read-transaction on the source database, open
46009    ** one now. If a transaction is opened here, then it will be closed
46010    ** before this function exits.
46011    */
46012    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
46013      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
46014      bCloseTrans = 1;
46015    }
46016
46017    /* Now that there is a read-lock on the source database, query the
46018    ** source pager for the number of pages in the database.
46019    */
46020    if( rc==SQLITE_OK ){
46021      rc = sqlite3PagerPagecount(pSrcPager, &nSrcPage);
46022    }
46023    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
46024      const Pgno iSrcPg = p->iNext;                 /* Source page number */
46025      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
46026        DbPage *pSrcPg;                             /* Source page object */
46027        rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
46028        if( rc==SQLITE_OK ){
46029          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
46030          sqlite3PagerUnref(pSrcPg);
46031        }
46032      }
46033      p->iNext++;
46034    }
46035    if( rc==SQLITE_OK ){
46036      p->nPagecount = nSrcPage;
46037      p->nRemaining = nSrcPage+1-p->iNext;
46038      if( p->iNext>(Pgno)nSrcPage ){
46039        rc = SQLITE_DONE;
46040      }else if( !p->isAttached ){
46041        attachBackupObject(p);
46042      }
46043    }
46044
46045    /* Update the schema version field in the destination database. This
46046    ** is to make sure that the schema-version really does change in
46047    ** the case where the source and destination databases have the
46048    ** same schema version.
46049    */
46050    if( rc==SQLITE_DONE
46051     && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
46052    ){
46053      const int nSrcPagesize = sqlite3BtreeGetPageSize(p->pSrc);
46054      const int nDestPagesize = sqlite3BtreeGetPageSize(p->pDest);
46055      int nDestTruncate;
46056
46057      if( p->pDestDb ){
46058        sqlite3ResetInternalSchema(p->pDestDb, 0);
46059      }
46060
46061      /* Set nDestTruncate to the final number of pages in the destination
46062      ** database. The complication here is that the destination page
46063      ** size may be different to the source page size.
46064      **
46065      ** If the source page size is smaller than the destination page size,
46066      ** round up. In this case the call to sqlite3OsTruncate() below will
46067      ** fix the size of the file. However it is important to call
46068      ** sqlite3PagerTruncateImage() here so that any pages in the
46069      ** destination file that lie beyond the nDestTruncate page mark are
46070      ** journalled by PagerCommitPhaseOne() before they are destroyed
46071      ** by the file truncation.
46072      */
46073      if( nSrcPagesize<nDestPagesize ){
46074        int ratio = nDestPagesize/nSrcPagesize;
46075        nDestTruncate = (nSrcPage+ratio-1)/ratio;
46076        if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
46077          nDestTruncate--;
46078        }
46079      }else{
46080        nDestTruncate = nSrcPage * (nSrcPagesize/nDestPagesize);
46081      }
46082      sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
46083
46084      if( nSrcPagesize<nDestPagesize ){
46085        /* If the source page-size is smaller than the destination page-size,
46086        ** two extra things may need to happen:
46087        **
46088        **   * The destination may need to be truncated, and
46089        **
46090        **   * Data stored on the pages immediately following the
46091        **     pending-byte page in the source database may need to be
46092        **     copied into the destination database.
46093        */
46094        const i64 iSize = (i64)nSrcPagesize * (i64)nSrcPage;
46095        sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
46096
46097        assert( pFile );
46098        assert( (i64)nDestTruncate*(i64)nDestPagesize >= iSize || (
46099              nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
46100           && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+nDestPagesize
46101        ));
46102        if( SQLITE_OK==(rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1))
46103         && SQLITE_OK==(rc = backupTruncateFile(pFile, iSize))
46104         && SQLITE_OK==(rc = sqlite3PagerSync(pDestPager))
46105        ){
46106          i64 iOff;
46107          i64 iEnd = MIN(PENDING_BYTE + nDestPagesize, iSize);
46108          for(
46109            iOff=PENDING_BYTE+nSrcPagesize;
46110            rc==SQLITE_OK && iOff<iEnd;
46111            iOff+=nSrcPagesize
46112          ){
46113            PgHdr *pSrcPg = 0;
46114            const Pgno iSrcPg = (Pgno)((iOff/nSrcPagesize)+1);
46115            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
46116            if( rc==SQLITE_OK ){
46117              u8 *zData = sqlite3PagerGetData(pSrcPg);
46118              rc = sqlite3OsWrite(pFile, zData, nSrcPagesize, iOff);
46119            }
46120            sqlite3PagerUnref(pSrcPg);
46121          }
46122        }
46123      }else{
46124        rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
46125      }
46126
46127      /* Finish committing the transaction to the destination database. */
46128      if( SQLITE_OK==rc
46129       && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest))
46130      ){
46131        rc = SQLITE_DONE;
46132      }
46133    }
46134
46135    /* If bCloseTrans is true, then this function opened a read transaction
46136    ** on the source database. Close the read transaction here. There is
46137    ** no need to check the return values of the btree methods here, as
46138    ** "committing" a read-only transaction cannot fail.
46139    */
46140    if( bCloseTrans ){
46141      TESTONLY( int rc2 );
46142      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
46143      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc);
46144      assert( rc2==SQLITE_OK );
46145    }
46146
46147    p->rc = rc;
46148  }
46149  if( p->pDestDb ){
46150    sqlite3_mutex_leave(p->pDestDb->mutex);
46151  }
46152  sqlite3BtreeLeave(p->pSrc);
46153  sqlite3_mutex_leave(p->pSrcDb->mutex);
46154  return rc;
46155}
46156
46157/*
46158** Release all resources associated with an sqlite3_backup* handle.
46159*/
46160SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
46161  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
46162  sqlite3_mutex *mutex;                /* Mutex to protect source database */
46163  int rc;                              /* Value to return */
46164
46165  /* Enter the mutexes */
46166  if( p==0 ) return SQLITE_OK;
46167  sqlite3_mutex_enter(p->pSrcDb->mutex);
46168  sqlite3BtreeEnter(p->pSrc);
46169  mutex = p->pSrcDb->mutex;
46170  if( p->pDestDb ){
46171    sqlite3_mutex_enter(p->pDestDb->mutex);
46172  }
46173
46174  /* Detach this backup from the source pager. */
46175  if( p->pDestDb ){
46176    p->pSrc->nBackup--;
46177  }
46178  if( p->isAttached ){
46179    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
46180    while( *pp!=p ){
46181      pp = &(*pp)->pNext;
46182    }
46183    *pp = p->pNext;
46184  }
46185
46186  /* If a transaction is still open on the Btree, roll it back. */
46187  sqlite3BtreeRollback(p->pDest);
46188
46189  /* Set the error code of the destination database handle. */
46190  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
46191  sqlite3Error(p->pDestDb, rc, 0);
46192
46193  /* Exit the mutexes and free the backup context structure. */
46194  if( p->pDestDb ){
46195    sqlite3_mutex_leave(p->pDestDb->mutex);
46196  }
46197  sqlite3BtreeLeave(p->pSrc);
46198  if( p->pDestDb ){
46199    sqlite3_free(p);
46200  }
46201  sqlite3_mutex_leave(mutex);
46202  return rc;
46203}
46204
46205/*
46206** Return the number of pages still to be backed up as of the most recent
46207** call to sqlite3_backup_step().
46208*/
46209SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
46210  return p->nRemaining;
46211}
46212
46213/*
46214** Return the total number of pages in the source database as of the most
46215** recent call to sqlite3_backup_step().
46216*/
46217SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
46218  return p->nPagecount;
46219}
46220
46221/*
46222** This function is called after the contents of page iPage of the
46223** source database have been modified. If page iPage has already been
46224** copied into the destination database, then the data written to the
46225** destination is now invalidated. The destination copy of iPage needs
46226** to be updated with the new data before the backup operation is
46227** complete.
46228**
46229** It is assumed that the mutex associated with the BtShared object
46230** corresponding to the source database is held when this function is
46231** called.
46232*/
46233SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
46234  sqlite3_backup *p;                   /* Iterator variable */
46235  for(p=pBackup; p; p=p->pNext){
46236    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
46237    if( !isFatalError(p->rc) && iPage<p->iNext ){
46238      /* The backup process p has already copied page iPage. But now it
46239      ** has been modified by a transaction on the source pager. Copy
46240      ** the new data into the backup.
46241      */
46242      int rc = backupOnePage(p, iPage, aData);
46243      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
46244      if( rc!=SQLITE_OK ){
46245        p->rc = rc;
46246      }
46247    }
46248  }
46249}
46250
46251/*
46252** Restart the backup process. This is called when the pager layer
46253** detects that the database has been modified by an external database
46254** connection. In this case there is no way of knowing which of the
46255** pages that have been copied into the destination database are still
46256** valid and which are not, so the entire process needs to be restarted.
46257**
46258** It is assumed that the mutex associated with the BtShared object
46259** corresponding to the source database is held when this function is
46260** called.
46261*/
46262SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
46263  sqlite3_backup *p;                   /* Iterator variable */
46264  for(p=pBackup; p; p=p->pNext){
46265    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
46266    p->iNext = 1;
46267  }
46268}
46269
46270#ifndef SQLITE_OMIT_VACUUM
46271/*
46272** Copy the complete content of pBtFrom into pBtTo.  A transaction
46273** must be active for both files.
46274**
46275** The size of file pTo may be reduced by this operation. If anything
46276** goes wrong, the transaction on pTo is rolled back. If successful, the
46277** transaction is committed before returning.
46278*/
46279SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
46280  int rc;
46281  sqlite3_backup b;
46282  sqlite3BtreeEnter(pTo);
46283  sqlite3BtreeEnter(pFrom);
46284
46285  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
46286  ** to 0. This is used by the implementations of sqlite3_backup_step()
46287  ** and sqlite3_backup_finish() to detect that they are being called
46288  ** from this function, not directly by the user.
46289  */
46290  memset(&b, 0, sizeof(b));
46291  b.pSrcDb = pFrom->db;
46292  b.pSrc = pFrom;
46293  b.pDest = pTo;
46294  b.iNext = 1;
46295
46296  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
46297  ** file. By passing this as the number of pages to copy to
46298  ** sqlite3_backup_step(), we can guarantee that the copy finishes
46299  ** within a single call (unless an error occurs). The assert() statement
46300  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
46301  ** or an error code.
46302  */
46303  sqlite3_backup_step(&b, 0x7FFFFFFF);
46304  assert( b.rc!=SQLITE_OK );
46305  rc = sqlite3_backup_finish(&b);
46306  if( rc==SQLITE_OK ){
46307    pTo->pBt->pageSizeFixed = 0;
46308  }
46309
46310  sqlite3BtreeLeave(pFrom);
46311  sqlite3BtreeLeave(pTo);
46312  return rc;
46313}
46314#endif /* SQLITE_OMIT_VACUUM */
46315
46316/************** End of backup.c **********************************************/
46317/************** Begin file vdbemem.c *****************************************/
46318/*
46319** 2004 May 26
46320**
46321** The author disclaims copyright to this source code.  In place of
46322** a legal notice, here is a blessing:
46323**
46324**    May you do good and not evil.
46325**    May you find forgiveness for yourself and forgive others.
46326**    May you share freely, never taking more than you give.
46327**
46328*************************************************************************
46329**
46330** This file contains code use to manipulate "Mem" structure.  A "Mem"
46331** stores a single value in the VDBE.  Mem is an opaque structure visible
46332** only within the VDBE.  Interface routines refer to a Mem using the
46333** name sqlite_value
46334*/
46335
46336/*
46337** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
46338** P if required.
46339*/
46340#define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
46341
46342/*
46343** If pMem is an object with a valid string representation, this routine
46344** ensures the internal encoding for the string representation is
46345** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
46346**
46347** If pMem is not a string object, or the encoding of the string
46348** representation is already stored using the requested encoding, then this
46349** routine is a no-op.
46350**
46351** SQLITE_OK is returned if the conversion is successful (or not required).
46352** SQLITE_NOMEM may be returned if a malloc() fails during conversion
46353** between formats.
46354*/
46355SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
46356  int rc;
46357  assert( (pMem->flags&MEM_RowSet)==0 );
46358  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
46359           || desiredEnc==SQLITE_UTF16BE );
46360  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
46361    return SQLITE_OK;
46362  }
46363  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46364#ifdef SQLITE_OMIT_UTF16
46365  return SQLITE_ERROR;
46366#else
46367
46368  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
46369  ** then the encoding of the value may not have changed.
46370  */
46371  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
46372  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
46373  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
46374  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
46375  return rc;
46376#endif
46377}
46378
46379/*
46380** Make sure pMem->z points to a writable allocation of at least
46381** n bytes.
46382**
46383** If the memory cell currently contains string or blob data
46384** and the third argument passed to this function is true, the
46385** current content of the cell is preserved. Otherwise, it may
46386** be discarded.
46387**
46388** This function sets the MEM_Dyn flag and clears any xDel callback.
46389** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
46390** not set, Mem.n is zeroed.
46391*/
46392SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
46393  assert( 1 >=
46394    ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
46395    (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
46396    ((pMem->flags&MEM_Ephem) ? 1 : 0) +
46397    ((pMem->flags&MEM_Static) ? 1 : 0)
46398  );
46399  assert( (pMem->flags&MEM_RowSet)==0 );
46400
46401  if( n<32 ) n = 32;
46402  if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
46403    if( preserve && pMem->z==pMem->zMalloc ){
46404      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
46405      preserve = 0;
46406    }else{
46407      sqlite3DbFree(pMem->db, pMem->zMalloc);
46408      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
46409    }
46410  }
46411
46412  if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
46413    memcpy(pMem->zMalloc, pMem->z, pMem->n);
46414  }
46415  if( pMem->flags&MEM_Dyn && pMem->xDel ){
46416    pMem->xDel((void *)(pMem->z));
46417  }
46418
46419  pMem->z = pMem->zMalloc;
46420  if( pMem->z==0 ){
46421    pMem->flags = MEM_Null;
46422  }else{
46423    pMem->flags &= ~(MEM_Ephem|MEM_Static);
46424  }
46425  pMem->xDel = 0;
46426  return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
46427}
46428
46429/*
46430** Make the given Mem object MEM_Dyn.  In other words, make it so
46431** that any TEXT or BLOB content is stored in memory obtained from
46432** malloc().  In this way, we know that the memory is safe to be
46433** overwritten or altered.
46434**
46435** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
46436*/
46437SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
46438  int f;
46439  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46440  assert( (pMem->flags&MEM_RowSet)==0 );
46441  expandBlob(pMem);
46442  f = pMem->flags;
46443  if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
46444    if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
46445      return SQLITE_NOMEM;
46446    }
46447    pMem->z[pMem->n] = 0;
46448    pMem->z[pMem->n+1] = 0;
46449    pMem->flags |= MEM_Term;
46450  }
46451
46452  return SQLITE_OK;
46453}
46454
46455/*
46456** If the given Mem* has a zero-filled tail, turn it into an ordinary
46457** blob stored in dynamically allocated space.
46458*/
46459#ifndef SQLITE_OMIT_INCRBLOB
46460SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
46461  if( pMem->flags & MEM_Zero ){
46462    int nByte;
46463    assert( pMem->flags&MEM_Blob );
46464    assert( (pMem->flags&MEM_RowSet)==0 );
46465    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46466
46467    /* Set nByte to the number of bytes required to store the expanded blob. */
46468    nByte = pMem->n + pMem->u.nZero;
46469    if( nByte<=0 ){
46470      nByte = 1;
46471    }
46472    if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
46473      return SQLITE_NOMEM;
46474    }
46475
46476    memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
46477    pMem->n += pMem->u.nZero;
46478    pMem->flags &= ~(MEM_Zero|MEM_Term);
46479  }
46480  return SQLITE_OK;
46481}
46482#endif
46483
46484
46485/*
46486** Make sure the given Mem is \u0000 terminated.
46487*/
46488SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
46489  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46490  if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
46491    return SQLITE_OK;   /* Nothing to do */
46492  }
46493  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
46494    return SQLITE_NOMEM;
46495  }
46496  pMem->z[pMem->n] = 0;
46497  pMem->z[pMem->n+1] = 0;
46498  pMem->flags |= MEM_Term;
46499  return SQLITE_OK;
46500}
46501
46502/*
46503** Add MEM_Str to the set of representations for the given Mem.  Numbers
46504** are converted using sqlite3_snprintf().  Converting a BLOB to a string
46505** is a no-op.
46506**
46507** Existing representations MEM_Int and MEM_Real are *not* invalidated.
46508**
46509** A MEM_Null value will never be passed to this function. This function is
46510** used for converting values to text for returning to the user (i.e. via
46511** sqlite3_value_text()), or for ensuring that values to be used as btree
46512** keys are strings. In the former case a NULL pointer is returned the
46513** user and the later is an internal programming error.
46514*/
46515SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
46516  int rc = SQLITE_OK;
46517  int fg = pMem->flags;
46518  const int nByte = 32;
46519
46520  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46521  assert( !(fg&MEM_Zero) );
46522  assert( !(fg&(MEM_Str|MEM_Blob)) );
46523  assert( fg&(MEM_Int|MEM_Real) );
46524  assert( (pMem->flags&MEM_RowSet)==0 );
46525  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46526
46527
46528  if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
46529    return SQLITE_NOMEM;
46530  }
46531
46532  /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
46533  ** string representation of the value. Then, if the required encoding
46534  ** is UTF-16le or UTF-16be do a translation.
46535  **
46536  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
46537  */
46538  if( fg & MEM_Int ){
46539    sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
46540  }else{
46541    assert( fg & MEM_Real );
46542    sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
46543  }
46544  pMem->n = sqlite3Strlen30(pMem->z);
46545  pMem->enc = SQLITE_UTF8;
46546  pMem->flags |= MEM_Str|MEM_Term;
46547  sqlite3VdbeChangeEncoding(pMem, enc);
46548  return rc;
46549}
46550
46551/*
46552** Memory cell pMem contains the context of an aggregate function.
46553** This routine calls the finalize method for that function.  The
46554** result of the aggregate is stored back into pMem.
46555**
46556** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
46557** otherwise.
46558*/
46559SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
46560  int rc = SQLITE_OK;
46561  if( ALWAYS(pFunc && pFunc->xFinalize) ){
46562    sqlite3_context ctx;
46563    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
46564    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46565    memset(&ctx, 0, sizeof(ctx));
46566    ctx.s.flags = MEM_Null;
46567    ctx.s.db = pMem->db;
46568    ctx.pMem = pMem;
46569    ctx.pFunc = pFunc;
46570    pFunc->xFinalize(&ctx);
46571    assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
46572    sqlite3DbFree(pMem->db, pMem->zMalloc);
46573    memcpy(pMem, &ctx.s, sizeof(ctx.s));
46574    rc = ctx.isError;
46575  }
46576  return rc;
46577}
46578
46579/*
46580** If the memory cell contains a string value that must be freed by
46581** invoking an external callback, free it now. Calling this function
46582** does not free any Mem.zMalloc buffer.
46583*/
46584SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
46585  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
46586  testcase( p->flags & MEM_Agg );
46587  testcase( p->flags & MEM_Dyn );
46588  testcase( p->flags & MEM_RowSet );
46589  testcase( p->flags & MEM_Frame );
46590  if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
46591    if( p->flags&MEM_Agg ){
46592      sqlite3VdbeMemFinalize(p, p->u.pDef);
46593      assert( (p->flags & MEM_Agg)==0 );
46594      sqlite3VdbeMemRelease(p);
46595    }else if( p->flags&MEM_Dyn && p->xDel ){
46596      assert( (p->flags&MEM_RowSet)==0 );
46597      p->xDel((void *)p->z);
46598      p->xDel = 0;
46599    }else if( p->flags&MEM_RowSet ){
46600      sqlite3RowSetClear(p->u.pRowSet);
46601    }else if( p->flags&MEM_Frame ){
46602      sqlite3VdbeMemSetNull(p);
46603    }
46604  }
46605}
46606
46607/*
46608** Release any memory held by the Mem. This may leave the Mem in an
46609** inconsistent state, for example with (Mem.z==0) and
46610** (Mem.type==SQLITE_TEXT).
46611*/
46612SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
46613  sqlite3VdbeMemReleaseExternal(p);
46614  sqlite3DbFree(p->db, p->zMalloc);
46615  p->z = 0;
46616  p->zMalloc = 0;
46617  p->xDel = 0;
46618}
46619
46620/*
46621** Convert a 64-bit IEEE double into a 64-bit signed integer.
46622** If the double is too large, return 0x8000000000000000.
46623**
46624** Most systems appear to do this simply by assigning
46625** variables and without the extra range tests.  But
46626** there are reports that windows throws an expection
46627** if the floating point value is out of range. (See ticket #2880.)
46628** Because we do not completely understand the problem, we will
46629** take the conservative approach and always do range tests
46630** before attempting the conversion.
46631*/
46632static i64 doubleToInt64(double r){
46633  /*
46634  ** Many compilers we encounter do not define constants for the
46635  ** minimum and maximum 64-bit integers, or they define them
46636  ** inconsistently.  And many do not understand the "LL" notation.
46637  ** So we define our own static constants here using nothing
46638  ** larger than a 32-bit integer constant.
46639  */
46640  static const i64 maxInt = LARGEST_INT64;
46641  static const i64 minInt = SMALLEST_INT64;
46642
46643  if( r<(double)minInt ){
46644    return minInt;
46645  }else if( r>(double)maxInt ){
46646    /* minInt is correct here - not maxInt.  It turns out that assigning
46647    ** a very large positive number to an integer results in a very large
46648    ** negative integer.  This makes no sense, but it is what x86 hardware
46649    ** does so for compatibility we will do the same in software. */
46650    return minInt;
46651  }else{
46652    return (i64)r;
46653  }
46654}
46655
46656/*
46657** Return some kind of integer value which is the best we can do
46658** at representing the value that *pMem describes as an integer.
46659** If pMem is an integer, then the value is exact.  If pMem is
46660** a floating-point then the value returned is the integer part.
46661** If pMem is a string or blob, then we make an attempt to convert
46662** it into a integer and return that.  If pMem represents an
46663** an SQL-NULL value, return 0.
46664**
46665** If pMem represents a string value, its encoding might be changed.
46666*/
46667SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
46668  int flags;
46669  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46670  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46671  flags = pMem->flags;
46672  if( flags & MEM_Int ){
46673    return pMem->u.i;
46674  }else if( flags & MEM_Real ){
46675    return doubleToInt64(pMem->r);
46676  }else if( flags & (MEM_Str|MEM_Blob) ){
46677    i64 value;
46678    pMem->flags |= MEM_Str;
46679    if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
46680       || sqlite3VdbeMemNulTerminate(pMem) ){
46681      return 0;
46682    }
46683    assert( pMem->z );
46684    sqlite3Atoi64(pMem->z, &value);
46685    return value;
46686  }else{
46687    return 0;
46688  }
46689}
46690
46691/*
46692** Return the best representation of pMem that we can get into a
46693** double.  If pMem is already a double or an integer, return its
46694** value.  If it is a string or blob, try to convert it to a double.
46695** If it is a NULL, return 0.0.
46696*/
46697SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
46698  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46699  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46700  if( pMem->flags & MEM_Real ){
46701    return pMem->r;
46702  }else if( pMem->flags & MEM_Int ){
46703    return (double)pMem->u.i;
46704  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
46705    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
46706    double val = (double)0;
46707    pMem->flags |= MEM_Str;
46708    if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
46709       || sqlite3VdbeMemNulTerminate(pMem) ){
46710      /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
46711      return (double)0;
46712    }
46713    assert( pMem->z );
46714    sqlite3AtoF(pMem->z, &val);
46715    return val;
46716  }else{
46717    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
46718    return (double)0;
46719  }
46720}
46721
46722/*
46723** The MEM structure is already a MEM_Real.  Try to also make it a
46724** MEM_Int if we can.
46725*/
46726SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
46727  assert( pMem->flags & MEM_Real );
46728  assert( (pMem->flags & MEM_RowSet)==0 );
46729  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46730  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46731
46732  pMem->u.i = doubleToInt64(pMem->r);
46733
46734  /* Only mark the value as an integer if
46735  **
46736  **    (1) the round-trip conversion real->int->real is a no-op, and
46737  **    (2) The integer is neither the largest nor the smallest
46738  **        possible integer (ticket #3922)
46739  **
46740  ** The second and third terms in the following conditional enforces
46741  ** the second condition under the assumption that addition overflow causes
46742  ** values to wrap around.  On x86 hardware, the third term is always
46743  ** true and could be omitted.  But we leave it in because other
46744  ** architectures might behave differently.
46745  */
46746  if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
46747      && ALWAYS(pMem->u.i<LARGEST_INT64) ){
46748    pMem->flags |= MEM_Int;
46749  }
46750}
46751
46752/*
46753** Convert pMem to type integer.  Invalidate any prior representations.
46754*/
46755SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
46756  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46757  assert( (pMem->flags & MEM_RowSet)==0 );
46758  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46759
46760  pMem->u.i = sqlite3VdbeIntValue(pMem);
46761  MemSetTypeFlag(pMem, MEM_Int);
46762  return SQLITE_OK;
46763}
46764
46765/*
46766** Convert pMem so that it is of type MEM_Real.
46767** Invalidate any prior representations.
46768*/
46769SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
46770  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46771  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46772
46773  pMem->r = sqlite3VdbeRealValue(pMem);
46774  MemSetTypeFlag(pMem, MEM_Real);
46775  return SQLITE_OK;
46776}
46777
46778/*
46779** Convert pMem so that it has types MEM_Real or MEM_Int or both.
46780** Invalidate any prior representations.
46781*/
46782SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
46783  double r1, r2;
46784  i64 i;
46785  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
46786  assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
46787  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46788  r1 = sqlite3VdbeRealValue(pMem);
46789  i = doubleToInt64(r1);
46790  r2 = (double)i;
46791  if( r1==r2 ){
46792    sqlite3VdbeMemIntegerify(pMem);
46793  }else{
46794    pMem->r = r1;
46795    MemSetTypeFlag(pMem, MEM_Real);
46796  }
46797  return SQLITE_OK;
46798}
46799
46800/*
46801** Delete any previous value and set the value stored in *pMem to NULL.
46802*/
46803SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
46804  if( pMem->flags & MEM_Frame ){
46805    sqlite3VdbeFrameDelete(pMem->u.pFrame);
46806  }
46807  if( pMem->flags & MEM_RowSet ){
46808    sqlite3RowSetClear(pMem->u.pRowSet);
46809  }
46810  MemSetTypeFlag(pMem, MEM_Null);
46811  pMem->type = SQLITE_NULL;
46812}
46813
46814/*
46815** Delete any previous value and set the value to be a BLOB of length
46816** n containing all zeros.
46817*/
46818SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
46819  sqlite3VdbeMemRelease(pMem);
46820  pMem->flags = MEM_Blob|MEM_Zero;
46821  pMem->type = SQLITE_BLOB;
46822  pMem->n = 0;
46823  if( n<0 ) n = 0;
46824  pMem->u.nZero = n;
46825  pMem->enc = SQLITE_UTF8;
46826
46827#ifdef SQLITE_OMIT_INCRBLOB
46828  sqlite3VdbeMemGrow(pMem, n, 0);
46829  if( pMem->z ){
46830    pMem->n = n;
46831    memset(pMem->z, 0, n);
46832  }
46833#endif
46834}
46835
46836/*
46837** Delete any previous value and set the value stored in *pMem to val,
46838** manifest type INTEGER.
46839*/
46840SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
46841  sqlite3VdbeMemRelease(pMem);
46842  pMem->u.i = val;
46843  pMem->flags = MEM_Int;
46844  pMem->type = SQLITE_INTEGER;
46845}
46846
46847/*
46848** Delete any previous value and set the value stored in *pMem to val,
46849** manifest type REAL.
46850*/
46851SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
46852  if( sqlite3IsNaN(val) ){
46853    sqlite3VdbeMemSetNull(pMem);
46854  }else{
46855    sqlite3VdbeMemRelease(pMem);
46856    pMem->r = val;
46857    pMem->flags = MEM_Real;
46858    pMem->type = SQLITE_FLOAT;
46859  }
46860}
46861
46862/*
46863** Delete any previous value and set the value of pMem to be an
46864** empty boolean index.
46865*/
46866SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
46867  sqlite3 *db = pMem->db;
46868  assert( db!=0 );
46869  assert( (pMem->flags & MEM_RowSet)==0 );
46870  sqlite3VdbeMemRelease(pMem);
46871  pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
46872  if( db->mallocFailed ){
46873    pMem->flags = MEM_Null;
46874  }else{
46875    assert( pMem->zMalloc );
46876    pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
46877                                       sqlite3DbMallocSize(db, pMem->zMalloc));
46878    assert( pMem->u.pRowSet!=0 );
46879    pMem->flags = MEM_RowSet;
46880  }
46881}
46882
46883/*
46884** Return true if the Mem object contains a TEXT or BLOB that is
46885** too large - whose size exceeds SQLITE_MAX_LENGTH.
46886*/
46887SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
46888  assert( p->db!=0 );
46889  if( p->flags & (MEM_Str|MEM_Blob) ){
46890    int n = p->n;
46891    if( p->flags & MEM_Zero ){
46892      n += p->u.nZero;
46893    }
46894    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
46895  }
46896  return 0;
46897}
46898
46899/*
46900** Size of struct Mem not including the Mem.zMalloc member.
46901*/
46902#define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
46903
46904/*
46905** Make an shallow copy of pFrom into pTo.  Prior contents of
46906** pTo are freed.  The pFrom->z field is not duplicated.  If
46907** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
46908** and flags gets srcType (either MEM_Ephem or MEM_Static).
46909*/
46910SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
46911  assert( (pFrom->flags & MEM_RowSet)==0 );
46912  sqlite3VdbeMemReleaseExternal(pTo);
46913  memcpy(pTo, pFrom, MEMCELLSIZE);
46914  pTo->xDel = 0;
46915  if( (pFrom->flags&MEM_Dyn)!=0 || pFrom->z==pFrom->zMalloc ){
46916    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
46917    assert( srcType==MEM_Ephem || srcType==MEM_Static );
46918    pTo->flags |= srcType;
46919  }
46920}
46921
46922/*
46923** Make a full copy of pFrom into pTo.  Prior contents of pTo are
46924** freed before the copy is made.
46925*/
46926SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
46927  int rc = SQLITE_OK;
46928
46929  assert( (pFrom->flags & MEM_RowSet)==0 );
46930  sqlite3VdbeMemReleaseExternal(pTo);
46931  memcpy(pTo, pFrom, MEMCELLSIZE);
46932  pTo->flags &= ~MEM_Dyn;
46933
46934  if( pTo->flags&(MEM_Str|MEM_Blob) ){
46935    if( 0==(pFrom->flags&MEM_Static) ){
46936      pTo->flags |= MEM_Ephem;
46937      rc = sqlite3VdbeMemMakeWriteable(pTo);
46938    }
46939  }
46940
46941  return rc;
46942}
46943
46944/*
46945** Transfer the contents of pFrom to pTo. Any existing value in pTo is
46946** freed. If pFrom contains ephemeral data, a copy is made.
46947**
46948** pFrom contains an SQL NULL when this routine returns.
46949*/
46950SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
46951  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
46952  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
46953  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
46954
46955  sqlite3VdbeMemRelease(pTo);
46956  memcpy(pTo, pFrom, sizeof(Mem));
46957  pFrom->flags = MEM_Null;
46958  pFrom->xDel = 0;
46959  pFrom->zMalloc = 0;
46960}
46961
46962/*
46963** Change the value of a Mem to be a string or a BLOB.
46964**
46965** The memory management strategy depends on the value of the xDel
46966** parameter. If the value passed is SQLITE_TRANSIENT, then the
46967** string is copied into a (possibly existing) buffer managed by the
46968** Mem structure. Otherwise, any existing buffer is freed and the
46969** pointer copied.
46970**
46971** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
46972** size limit) then no memory allocation occurs.  If the string can be
46973** stored without allocating memory, then it is.  If a memory allocation
46974** is required to store the string, then value of pMem is unchanged.  In
46975** either case, SQLITE_TOOBIG is returned.
46976*/
46977SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
46978  Mem *pMem,          /* Memory cell to set to string value */
46979  const char *z,      /* String pointer */
46980  int n,              /* Bytes in string, or negative */
46981  u8 enc,             /* Encoding of z.  0 for BLOBs */
46982  void (*xDel)(void*) /* Destructor function */
46983){
46984  int nByte = n;      /* New value for pMem->n */
46985  int iLimit;         /* Maximum allowed string or blob size */
46986  u16 flags = 0;      /* New value for pMem->flags */
46987
46988  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46989  assert( (pMem->flags & MEM_RowSet)==0 );
46990
46991  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
46992  if( !z ){
46993    sqlite3VdbeMemSetNull(pMem);
46994    return SQLITE_OK;
46995  }
46996
46997  if( pMem->db ){
46998    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
46999  }else{
47000    iLimit = SQLITE_MAX_LENGTH;
47001  }
47002  flags = (enc==0?MEM_Blob:MEM_Str);
47003  if( nByte<0 ){
47004    assert( enc!=0 );
47005    if( enc==SQLITE_UTF8 ){
47006      for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
47007    }else{
47008      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
47009    }
47010    flags |= MEM_Term;
47011  }
47012
47013  /* The following block sets the new values of Mem.z and Mem.xDel. It
47014  ** also sets a flag in local variable "flags" to indicate the memory
47015  ** management (one of MEM_Dyn or MEM_Static).
47016  */
47017  if( xDel==SQLITE_TRANSIENT ){
47018    int nAlloc = nByte;
47019    if( flags&MEM_Term ){
47020      nAlloc += (enc==SQLITE_UTF8?1:2);
47021    }
47022    if( nByte>iLimit ){
47023      return SQLITE_TOOBIG;
47024    }
47025    if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
47026      return SQLITE_NOMEM;
47027    }
47028    memcpy(pMem->z, z, nAlloc);
47029  }else if( xDel==SQLITE_DYNAMIC ){
47030    sqlite3VdbeMemRelease(pMem);
47031    pMem->zMalloc = pMem->z = (char *)z;
47032    pMem->xDel = 0;
47033  }else{
47034    sqlite3VdbeMemRelease(pMem);
47035    pMem->z = (char *)z;
47036    pMem->xDel = xDel;
47037    flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
47038  }
47039
47040  pMem->n = nByte;
47041  pMem->flags = flags;
47042  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
47043  pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
47044
47045#ifndef SQLITE_OMIT_UTF16
47046  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
47047    return SQLITE_NOMEM;
47048  }
47049#endif
47050
47051  if( nByte>iLimit ){
47052    return SQLITE_TOOBIG;
47053  }
47054
47055  return SQLITE_OK;
47056}
47057
47058/*
47059** Compare the values contained by the two memory cells, returning
47060** negative, zero or positive if pMem1 is less than, equal to, or greater
47061** than pMem2. Sorting order is NULL's first, followed by numbers (integers
47062** and reals) sorted numerically, followed by text ordered by the collating
47063** sequence pColl and finally blob's ordered by memcmp().
47064**
47065** Two NULL values are considered equal by this function.
47066*/
47067SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
47068  int rc;
47069  int f1, f2;
47070  int combined_flags;
47071
47072  f1 = pMem1->flags;
47073  f2 = pMem2->flags;
47074  combined_flags = f1|f2;
47075  assert( (combined_flags & MEM_RowSet)==0 );
47076
47077  /* If one value is NULL, it is less than the other. If both values
47078  ** are NULL, return 0.
47079  */
47080  if( combined_flags&MEM_Null ){
47081    return (f2&MEM_Null) - (f1&MEM_Null);
47082  }
47083
47084  /* If one value is a number and the other is not, the number is less.
47085  ** If both are numbers, compare as reals if one is a real, or as integers
47086  ** if both values are integers.
47087  */
47088  if( combined_flags&(MEM_Int|MEM_Real) ){
47089    if( !(f1&(MEM_Int|MEM_Real)) ){
47090      return 1;
47091    }
47092    if( !(f2&(MEM_Int|MEM_Real)) ){
47093      return -1;
47094    }
47095    if( (f1 & f2 & MEM_Int)==0 ){
47096      double r1, r2;
47097      if( (f1&MEM_Real)==0 ){
47098        r1 = (double)pMem1->u.i;
47099      }else{
47100        r1 = pMem1->r;
47101      }
47102      if( (f2&MEM_Real)==0 ){
47103        r2 = (double)pMem2->u.i;
47104      }else{
47105        r2 = pMem2->r;
47106      }
47107      if( r1<r2 ) return -1;
47108      if( r1>r2 ) return 1;
47109      return 0;
47110    }else{
47111      assert( f1&MEM_Int );
47112      assert( f2&MEM_Int );
47113      if( pMem1->u.i < pMem2->u.i ) return -1;
47114      if( pMem1->u.i > pMem2->u.i ) return 1;
47115      return 0;
47116    }
47117  }
47118
47119  /* If one value is a string and the other is a blob, the string is less.
47120  ** If both are strings, compare using the collating functions.
47121  */
47122  if( combined_flags&MEM_Str ){
47123    if( (f1 & MEM_Str)==0 ){
47124      return 1;
47125    }
47126    if( (f2 & MEM_Str)==0 ){
47127      return -1;
47128    }
47129
47130    assert( pMem1->enc==pMem2->enc );
47131    assert( pMem1->enc==SQLITE_UTF8 ||
47132            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
47133
47134    /* The collation sequence must be defined at this point, even if
47135    ** the user deletes the collation sequence after the vdbe program is
47136    ** compiled (this was not always the case).
47137    */
47138    assert( !pColl || pColl->xCmp );
47139
47140    if( pColl ){
47141      if( pMem1->enc==pColl->enc ){
47142        /* The strings are already in the correct encoding.  Call the
47143        ** comparison function directly */
47144        return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
47145      }else{
47146        const void *v1, *v2;
47147        int n1, n2;
47148        Mem c1;
47149        Mem c2;
47150        memset(&c1, 0, sizeof(c1));
47151        memset(&c2, 0, sizeof(c2));
47152        sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
47153        sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
47154        v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
47155        n1 = v1==0 ? 0 : c1.n;
47156        v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
47157        n2 = v2==0 ? 0 : c2.n;
47158        rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
47159        sqlite3VdbeMemRelease(&c1);
47160        sqlite3VdbeMemRelease(&c2);
47161        return rc;
47162      }
47163    }
47164    /* If a NULL pointer was passed as the collate function, fall through
47165    ** to the blob case and use memcmp().  */
47166  }
47167
47168  /* Both values must be blobs.  Compare using memcmp().  */
47169  rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
47170  if( rc==0 ){
47171    rc = pMem1->n - pMem2->n;
47172  }
47173  return rc;
47174}
47175
47176/*
47177** Move data out of a btree key or data field and into a Mem structure.
47178** The data or key is taken from the entry that pCur is currently pointing
47179** to.  offset and amt determine what portion of the data or key to retrieve.
47180** key is true to get the key or false to get data.  The result is written
47181** into the pMem element.
47182**
47183** The pMem structure is assumed to be uninitialized.  Any prior content
47184** is overwritten without being freed.
47185**
47186** If this routine fails for any reason (malloc returns NULL or unable
47187** to read from the disk) then the pMem is left in an inconsistent state.
47188*/
47189SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
47190  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
47191  int offset,       /* Offset from the start of data to return bytes from. */
47192  int amt,          /* Number of bytes to return. */
47193  int key,          /* If true, retrieve from the btree key, not data. */
47194  Mem *pMem         /* OUT: Return data in this Mem structure. */
47195){
47196  char *zData;        /* Data from the btree layer */
47197  int available = 0;  /* Number of bytes available on the local btree page */
47198  int rc = SQLITE_OK; /* Return code */
47199
47200  assert( sqlite3BtreeCursorIsValid(pCur) );
47201
47202  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
47203  ** that both the BtShared and database handle mutexes are held. */
47204  assert( (pMem->flags & MEM_RowSet)==0 );
47205  if( key ){
47206    zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
47207  }else{
47208    zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
47209  }
47210  assert( zData!=0 );
47211
47212  if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
47213    sqlite3VdbeMemRelease(pMem);
47214    pMem->z = &zData[offset];
47215    pMem->flags = MEM_Blob|MEM_Ephem;
47216  }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
47217    pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
47218    pMem->enc = 0;
47219    pMem->type = SQLITE_BLOB;
47220    if( key ){
47221      rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
47222    }else{
47223      rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
47224    }
47225    pMem->z[amt] = 0;
47226    pMem->z[amt+1] = 0;
47227    if( rc!=SQLITE_OK ){
47228      sqlite3VdbeMemRelease(pMem);
47229    }
47230  }
47231  pMem->n = amt;
47232
47233  return rc;
47234}
47235
47236/* This function is only available internally, it is not part of the
47237** external API. It works in a similar way to sqlite3_value_text(),
47238** except the data returned is in the encoding specified by the second
47239** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
47240** SQLITE_UTF8.
47241**
47242** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
47243** If that is the case, then the result must be aligned on an even byte
47244** boundary.
47245*/
47246SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
47247  if( !pVal ) return 0;
47248
47249  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
47250  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
47251  assert( (pVal->flags & MEM_RowSet)==0 );
47252
47253  if( pVal->flags&MEM_Null ){
47254    return 0;
47255  }
47256  assert( (MEM_Blob>>3) == MEM_Str );
47257  pVal->flags |= (pVal->flags & MEM_Blob)>>3;
47258  expandBlob(pVal);
47259  if( pVal->flags&MEM_Str ){
47260    sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
47261    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
47262      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
47263      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
47264        return 0;
47265      }
47266    }
47267    sqlite3VdbeMemNulTerminate(pVal);
47268  }else{
47269    assert( (pVal->flags&MEM_Blob)==0 );
47270    sqlite3VdbeMemStringify(pVal, enc);
47271    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
47272  }
47273  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
47274              || pVal->db->mallocFailed );
47275  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
47276    return pVal->z;
47277  }else{
47278    return 0;
47279  }
47280}
47281
47282/*
47283** Create a new sqlite3_value object.
47284*/
47285SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
47286  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
47287  if( p ){
47288    p->flags = MEM_Null;
47289    p->type = SQLITE_NULL;
47290    p->db = db;
47291  }
47292  return p;
47293}
47294
47295/*
47296** Create a new sqlite3_value object, containing the value of pExpr.
47297**
47298** This only works for very simple expressions that consist of one constant
47299** token (i.e. "5", "5.1", "'a string'"). If the expression can
47300** be converted directly into a value, then the value is allocated and
47301** a pointer written to *ppVal. The caller is responsible for deallocating
47302** the value by passing it to sqlite3ValueFree() later on. If the expression
47303** cannot be converted to a value, then *ppVal is set to NULL.
47304*/
47305SQLITE_PRIVATE int sqlite3ValueFromExpr(
47306  sqlite3 *db,              /* The database connection */
47307  Expr *pExpr,              /* The expression to evaluate */
47308  u8 enc,                   /* Encoding to use */
47309  u8 affinity,              /* Affinity to use */
47310  sqlite3_value **ppVal     /* Write the new value here */
47311){
47312  int op;
47313  char *zVal = 0;
47314  sqlite3_value *pVal = 0;
47315
47316  if( !pExpr ){
47317    *ppVal = 0;
47318    return SQLITE_OK;
47319  }
47320  op = pExpr->op;
47321  if( op==TK_REGISTER ){
47322    op = pExpr->op2;  /* This only happens with SQLITE_ENABLE_STAT2 */
47323  }
47324
47325  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
47326    pVal = sqlite3ValueNew(db);
47327    if( pVal==0 ) goto no_mem;
47328    if( ExprHasProperty(pExpr, EP_IntValue) ){
47329      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue);
47330    }else{
47331      zVal = sqlite3DbStrDup(db, pExpr->u.zToken);
47332      if( zVal==0 ) goto no_mem;
47333      sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
47334      if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
47335    }
47336    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
47337      sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
47338    }else{
47339      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
47340    }
47341    if( enc!=SQLITE_UTF8 ){
47342      sqlite3VdbeChangeEncoding(pVal, enc);
47343    }
47344  }else if( op==TK_UMINUS ) {
47345    if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
47346      pVal->u.i = -1 * pVal->u.i;
47347      /* (double)-1 In case of SQLITE_OMIT_FLOATING_POINT... */
47348      pVal->r = (double)-1 * pVal->r;
47349    }
47350  }
47351#ifndef SQLITE_OMIT_BLOB_LITERAL
47352  else if( op==TK_BLOB ){
47353    int nVal;
47354    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
47355    assert( pExpr->u.zToken[1]=='\'' );
47356    pVal = sqlite3ValueNew(db);
47357    if( !pVal ) goto no_mem;
47358    zVal = &pExpr->u.zToken[2];
47359    nVal = sqlite3Strlen30(zVal)-1;
47360    assert( zVal[nVal]=='\'' );
47361    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
47362                         0, SQLITE_DYNAMIC);
47363  }
47364#endif
47365
47366  if( pVal ){
47367    sqlite3VdbeMemStoreType(pVal);
47368  }
47369  *ppVal = pVal;
47370  return SQLITE_OK;
47371
47372no_mem:
47373  db->mallocFailed = 1;
47374  sqlite3DbFree(db, zVal);
47375  sqlite3ValueFree(pVal);
47376  *ppVal = 0;
47377  return SQLITE_NOMEM;
47378}
47379
47380/*
47381** Change the string value of an sqlite3_value object
47382*/
47383SQLITE_PRIVATE void sqlite3ValueSetStr(
47384  sqlite3_value *v,     /* Value to be set */
47385  int n,                /* Length of string z */
47386  const void *z,        /* Text of the new string */
47387  u8 enc,               /* Encoding to use */
47388  void (*xDel)(void*)   /* Destructor for the string */
47389){
47390  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
47391}
47392
47393/*
47394** Free an sqlite3_value object
47395*/
47396SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
47397  if( !v ) return;
47398  sqlite3VdbeMemRelease((Mem *)v);
47399  sqlite3DbFree(((Mem*)v)->db, v);
47400}
47401
47402/*
47403** Return the number of bytes in the sqlite3_value object assuming
47404** that it uses the encoding "enc"
47405*/
47406SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
47407  Mem *p = (Mem*)pVal;
47408  if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
47409    if( p->flags & MEM_Zero ){
47410      return p->n + p->u.nZero;
47411    }else{
47412      return p->n;
47413    }
47414  }
47415  return 0;
47416}
47417
47418/************** End of vdbemem.c *********************************************/
47419/************** Begin file vdbeaux.c *****************************************/
47420/*
47421** 2003 September 6
47422**
47423** The author disclaims copyright to this source code.  In place of
47424** a legal notice, here is a blessing:
47425**
47426**    May you do good and not evil.
47427**    May you find forgiveness for yourself and forgive others.
47428**    May you share freely, never taking more than you give.
47429**
47430*************************************************************************
47431** This file contains code used for creating, destroying, and populating
47432** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
47433** to version 2.8.7, all this code was combined into the vdbe.c source file.
47434** But that file was getting too big so this subroutines were split out.
47435*/
47436
47437
47438
47439/*
47440** When debugging the code generator in a symbolic debugger, one can
47441** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
47442** as they are added to the instruction stream.
47443*/
47444#ifdef SQLITE_DEBUG
47445SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
47446#endif
47447
47448
47449/*
47450** Create a new virtual database engine.
47451*/
47452SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
47453  Vdbe *p;
47454  p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
47455  if( p==0 ) return 0;
47456  p->db = db;
47457  if( db->pVdbe ){
47458    db->pVdbe->pPrev = p;
47459  }
47460  p->pNext = db->pVdbe;
47461  p->pPrev = 0;
47462  db->pVdbe = p;
47463  p->magic = VDBE_MAGIC_INIT;
47464  return p;
47465}
47466
47467/*
47468** Remember the SQL string for a prepared statement.
47469*/
47470SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
47471  assert( isPrepareV2==1 || isPrepareV2==0 );
47472  if( p==0 ) return;
47473#ifdef SQLITE_OMIT_TRACE
47474  if( !isPrepareV2 ) return;
47475#endif
47476  assert( p->zSql==0 );
47477  p->zSql = sqlite3DbStrNDup(p->db, z, n);
47478  p->isPrepareV2 = (u8)isPrepareV2;
47479}
47480
47481/*
47482** Return the SQL associated with a prepared statement
47483*/
47484SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
47485  Vdbe *p = (Vdbe *)pStmt;
47486  return (p->isPrepareV2 ? p->zSql : 0);
47487}
47488
47489/*
47490** Swap all content between two VDBE structures.
47491*/
47492SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
47493  Vdbe tmp, *pTmp;
47494  char *zTmp;
47495  tmp = *pA;
47496  *pA = *pB;
47497  *pB = tmp;
47498  pTmp = pA->pNext;
47499  pA->pNext = pB->pNext;
47500  pB->pNext = pTmp;
47501  pTmp = pA->pPrev;
47502  pA->pPrev = pB->pPrev;
47503  pB->pPrev = pTmp;
47504  zTmp = pA->zSql;
47505  pA->zSql = pB->zSql;
47506  pB->zSql = zTmp;
47507  pB->isPrepareV2 = pA->isPrepareV2;
47508}
47509
47510#ifdef SQLITE_DEBUG
47511/*
47512** Turn tracing on or off
47513*/
47514SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
47515  p->trace = trace;
47516}
47517#endif
47518
47519/*
47520** Resize the Vdbe.aOp array so that it is at least one op larger than
47521** it was.
47522**
47523** If an out-of-memory error occurs while resizing the array, return
47524** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
47525** unchanged (this is so that any opcodes already allocated can be
47526** correctly deallocated along with the rest of the Vdbe).
47527*/
47528static int growOpArray(Vdbe *p){
47529  VdbeOp *pNew;
47530  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
47531  pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
47532  if( pNew ){
47533    p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
47534    p->aOp = pNew;
47535  }
47536  return (pNew ? SQLITE_OK : SQLITE_NOMEM);
47537}
47538
47539/*
47540** Add a new instruction to the list of instructions current in the
47541** VDBE.  Return the address of the new instruction.
47542**
47543** Parameters:
47544**
47545**    p               Pointer to the VDBE
47546**
47547**    op              The opcode for this instruction
47548**
47549**    p1, p2, p3      Operands
47550**
47551** Use the sqlite3VdbeResolveLabel() function to fix an address and
47552** the sqlite3VdbeChangeP4() function to change the value of the P4
47553** operand.
47554*/
47555SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
47556  int i;
47557  VdbeOp *pOp;
47558
47559  i = p->nOp;
47560  assert( p->magic==VDBE_MAGIC_INIT );
47561  assert( op>0 && op<0xff );
47562  if( p->nOpAlloc<=i ){
47563    if( growOpArray(p) ){
47564      return 1;
47565    }
47566  }
47567  p->nOp++;
47568  pOp = &p->aOp[i];
47569  pOp->opcode = (u8)op;
47570  pOp->p5 = 0;
47571  pOp->p1 = p1;
47572  pOp->p2 = p2;
47573  pOp->p3 = p3;
47574  pOp->p4.p = 0;
47575  pOp->p4type = P4_NOTUSED;
47576  p->expired = 0;
47577#ifdef SQLITE_DEBUG
47578  pOp->zComment = 0;
47579  if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
47580#endif
47581#ifdef VDBE_PROFILE
47582  pOp->cycles = 0;
47583  pOp->cnt = 0;
47584#endif
47585  return i;
47586}
47587SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
47588  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
47589}
47590SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
47591  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
47592}
47593SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
47594  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
47595}
47596
47597
47598/*
47599** Add an opcode that includes the p4 value as a pointer.
47600*/
47601SQLITE_PRIVATE int sqlite3VdbeAddOp4(
47602  Vdbe *p,            /* Add the opcode to this VM */
47603  int op,             /* The new opcode */
47604  int p1,             /* The P1 operand */
47605  int p2,             /* The P2 operand */
47606  int p3,             /* The P3 operand */
47607  const char *zP4,    /* The P4 operand */
47608  int p4type          /* P4 operand type */
47609){
47610  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
47611  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
47612  return addr;
47613}
47614
47615/*
47616** Add an opcode that includes the p4 value as an integer.
47617*/
47618SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
47619  Vdbe *p,            /* Add the opcode to this VM */
47620  int op,             /* The new opcode */
47621  int p1,             /* The P1 operand */
47622  int p2,             /* The P2 operand */
47623  int p3,             /* The P3 operand */
47624  int p4              /* The P4 operand as an integer */
47625){
47626  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
47627  sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
47628  return addr;
47629}
47630
47631/*
47632** Create a new symbolic label for an instruction that has yet to be
47633** coded.  The symbolic label is really just a negative number.  The
47634** label can be used as the P2 value of an operation.  Later, when
47635** the label is resolved to a specific address, the VDBE will scan
47636** through its operation list and change all values of P2 which match
47637** the label into the resolved address.
47638**
47639** The VDBE knows that a P2 value is a label because labels are
47640** always negative and P2 values are suppose to be non-negative.
47641** Hence, a negative P2 value is a label that has yet to be resolved.
47642**
47643** Zero is returned if a malloc() fails.
47644*/
47645SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
47646  int i;
47647  i = p->nLabel++;
47648  assert( p->magic==VDBE_MAGIC_INIT );
47649  if( i>=p->nLabelAlloc ){
47650    int n = p->nLabelAlloc*2 + 5;
47651    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
47652                                       n*sizeof(p->aLabel[0]));
47653    p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
47654  }
47655  if( p->aLabel ){
47656    p->aLabel[i] = -1;
47657  }
47658  return -1-i;
47659}
47660
47661/*
47662** Resolve label "x" to be the address of the next instruction to
47663** be inserted.  The parameter "x" must have been obtained from
47664** a prior call to sqlite3VdbeMakeLabel().
47665*/
47666SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
47667  int j = -1-x;
47668  assert( p->magic==VDBE_MAGIC_INIT );
47669  assert( j>=0 && j<p->nLabel );
47670  if( p->aLabel ){
47671    p->aLabel[j] = p->nOp;
47672  }
47673}
47674
47675/*
47676** Mark the VDBE as one that can only be run one time.
47677*/
47678SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
47679  p->runOnlyOnce = 1;
47680}
47681
47682#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
47683
47684/*
47685** The following type and function are used to iterate through all opcodes
47686** in a Vdbe main program and each of the sub-programs (triggers) it may
47687** invoke directly or indirectly. It should be used as follows:
47688**
47689**   Op *pOp;
47690**   VdbeOpIter sIter;
47691**
47692**   memset(&sIter, 0, sizeof(sIter));
47693**   sIter.v = v;                            // v is of type Vdbe*
47694**   while( (pOp = opIterNext(&sIter)) ){
47695**     // Do something with pOp
47696**   }
47697**   sqlite3DbFree(v->db, sIter.apSub);
47698**
47699*/
47700typedef struct VdbeOpIter VdbeOpIter;
47701struct VdbeOpIter {
47702  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
47703  SubProgram **apSub;        /* Array of subprograms */
47704  int nSub;                  /* Number of entries in apSub */
47705  int iAddr;                 /* Address of next instruction to return */
47706  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
47707};
47708static Op *opIterNext(VdbeOpIter *p){
47709  Vdbe *v = p->v;
47710  Op *pRet = 0;
47711  Op *aOp;
47712  int nOp;
47713
47714  if( p->iSub<=p->nSub ){
47715
47716    if( p->iSub==0 ){
47717      aOp = v->aOp;
47718      nOp = v->nOp;
47719    }else{
47720      aOp = p->apSub[p->iSub-1]->aOp;
47721      nOp = p->apSub[p->iSub-1]->nOp;
47722    }
47723    assert( p->iAddr<nOp );
47724
47725    pRet = &aOp[p->iAddr];
47726    p->iAddr++;
47727    if( p->iAddr==nOp ){
47728      p->iSub++;
47729      p->iAddr = 0;
47730    }
47731
47732    if( pRet->p4type==P4_SUBPROGRAM ){
47733      int nByte = (p->nSub+1)*sizeof(SubProgram*);
47734      int j;
47735      for(j=0; j<p->nSub; j++){
47736        if( p->apSub[j]==pRet->p4.pProgram ) break;
47737      }
47738      if( j==p->nSub ){
47739        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
47740        if( !p->apSub ){
47741          pRet = 0;
47742        }else{
47743          p->apSub[p->nSub++] = pRet->p4.pProgram;
47744        }
47745      }
47746    }
47747  }
47748
47749  return pRet;
47750}
47751
47752/*
47753** Check if the program stored in the VM associated with pParse may
47754** throw an ABORT exception (causing the statement, but not entire transaction
47755** to be rolled back). This condition is true if the main program or any
47756** sub-programs contains any of the following:
47757**
47758**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
47759**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
47760**   *  OP_Destroy
47761**   *  OP_VUpdate
47762**   *  OP_VRename
47763**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
47764**
47765** Then check that the value of Parse.mayAbort is true if an
47766** ABORT may be thrown, or false otherwise. Return true if it does
47767** match, or false otherwise. This function is intended to be used as
47768** part of an assert statement in the compiler. Similar to:
47769**
47770**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
47771*/
47772SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
47773  int hasAbort = 0;
47774  Op *pOp;
47775  VdbeOpIter sIter;
47776  memset(&sIter, 0, sizeof(sIter));
47777  sIter.v = v;
47778
47779  while( (pOp = opIterNext(&sIter))!=0 ){
47780    int opcode = pOp->opcode;
47781    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
47782#ifndef SQLITE_OMIT_FOREIGN_KEY
47783     || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
47784#endif
47785     || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
47786      && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
47787    ){
47788      hasAbort = 1;
47789      break;
47790    }
47791  }
47792  sqlite3DbFree(v->db, sIter.apSub);
47793
47794  /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
47795  ** If malloc failed, then the while() loop above may not have iterated
47796  ** through all opcodes and hasAbort may be set incorrectly. Return
47797  ** true for this case to prevent the assert() in the callers frame
47798  ** from failing.  */
47799  return ( v->db->mallocFailed || hasAbort==mayAbort );
47800}
47801#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
47802
47803/*
47804** Loop through the program looking for P2 values that are negative
47805** on jump instructions.  Each such value is a label.  Resolve the
47806** label by setting the P2 value to its correct non-zero value.
47807**
47808** This routine is called once after all opcodes have been inserted.
47809**
47810** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
47811** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
47812** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
47813**
47814** The Op.opflags field is set on all opcodes.
47815*/
47816static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
47817  int i;
47818  int nMaxArgs = *pMaxFuncArgs;
47819  Op *pOp;
47820  int *aLabel = p->aLabel;
47821  p->readOnly = 1;
47822  for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
47823    u8 opcode = pOp->opcode;
47824
47825    pOp->opflags = sqlite3OpcodeProperty[opcode];
47826    if( opcode==OP_Function || opcode==OP_AggStep ){
47827      if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
47828    }else if( opcode==OP_Transaction && pOp->p2!=0 ){
47829      p->readOnly = 0;
47830#ifndef SQLITE_OMIT_VIRTUALTABLE
47831    }else if( opcode==OP_VUpdate ){
47832      if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
47833    }else if( opcode==OP_VFilter ){
47834      int n;
47835      assert( p->nOp - i >= 3 );
47836      assert( pOp[-1].opcode==OP_Integer );
47837      n = pOp[-1].p1;
47838      if( n>nMaxArgs ) nMaxArgs = n;
47839#endif
47840    }
47841
47842    if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
47843      assert( -1-pOp->p2<p->nLabel );
47844      pOp->p2 = aLabel[-1-pOp->p2];
47845    }
47846  }
47847  sqlite3DbFree(p->db, p->aLabel);
47848  p->aLabel = 0;
47849
47850  *pMaxFuncArgs = nMaxArgs;
47851}
47852
47853/*
47854** Return the address of the next instruction to be inserted.
47855*/
47856SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
47857  assert( p->magic==VDBE_MAGIC_INIT );
47858  return p->nOp;
47859}
47860
47861/*
47862** This function returns a pointer to the array of opcodes associated with
47863** the Vdbe passed as the first argument. It is the callers responsibility
47864** to arrange for the returned array to be eventually freed using the
47865** vdbeFreeOpArray() function.
47866**
47867** Before returning, *pnOp is set to the number of entries in the returned
47868** array. Also, *pnMaxArg is set to the larger of its current value and
47869** the number of entries in the Vdbe.apArg[] array required to execute the
47870** returned program.
47871*/
47872SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
47873  VdbeOp *aOp = p->aOp;
47874  assert( aOp && !p->db->mallocFailed );
47875
47876  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
47877  assert( p->aMutex.nMutex==0 );
47878
47879  resolveP2Values(p, pnMaxArg);
47880  *pnOp = p->nOp;
47881  p->aOp = 0;
47882  return aOp;
47883}
47884
47885/*
47886** Add a whole list of operations to the operation stack.  Return the
47887** address of the first operation added.
47888*/
47889SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
47890  int addr;
47891  assert( p->magic==VDBE_MAGIC_INIT );
47892  if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
47893    return 0;
47894  }
47895  addr = p->nOp;
47896  if( ALWAYS(nOp>0) ){
47897    int i;
47898    VdbeOpList const *pIn = aOp;
47899    for(i=0; i<nOp; i++, pIn++){
47900      int p2 = pIn->p2;
47901      VdbeOp *pOut = &p->aOp[i+addr];
47902      pOut->opcode = pIn->opcode;
47903      pOut->p1 = pIn->p1;
47904      if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
47905        pOut->p2 = addr + ADDR(p2);
47906      }else{
47907        pOut->p2 = p2;
47908      }
47909      pOut->p3 = pIn->p3;
47910      pOut->p4type = P4_NOTUSED;
47911      pOut->p4.p = 0;
47912      pOut->p5 = 0;
47913#ifdef SQLITE_DEBUG
47914      pOut->zComment = 0;
47915      if( sqlite3VdbeAddopTrace ){
47916        sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
47917      }
47918#endif
47919    }
47920    p->nOp += nOp;
47921  }
47922  return addr;
47923}
47924
47925/*
47926** Change the value of the P1 operand for a specific instruction.
47927** This routine is useful when a large program is loaded from a
47928** static array using sqlite3VdbeAddOpList but we want to make a
47929** few minor changes to the program.
47930*/
47931SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
47932  assert( p!=0 );
47933  assert( addr>=0 );
47934  if( p->nOp>addr ){
47935    p->aOp[addr].p1 = val;
47936  }
47937}
47938
47939/*
47940** Change the value of the P2 operand for a specific instruction.
47941** This routine is useful for setting a jump destination.
47942*/
47943SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
47944  assert( p!=0 );
47945  assert( addr>=0 );
47946  if( p->nOp>addr ){
47947    p->aOp[addr].p2 = val;
47948  }
47949}
47950
47951/*
47952** Change the value of the P3 operand for a specific instruction.
47953*/
47954SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
47955  assert( p!=0 );
47956  assert( addr>=0 );
47957  if( p->nOp>addr ){
47958    p->aOp[addr].p3 = val;
47959  }
47960}
47961
47962/*
47963** Change the value of the P5 operand for the most recently
47964** added operation.
47965*/
47966SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
47967  assert( p!=0 );
47968  if( p->aOp ){
47969    assert( p->nOp>0 );
47970    p->aOp[p->nOp-1].p5 = val;
47971  }
47972}
47973
47974/*
47975** Change the P2 operand of instruction addr so that it points to
47976** the address of the next instruction to be coded.
47977*/
47978SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
47979  sqlite3VdbeChangeP2(p, addr, p->nOp);
47980}
47981
47982
47983/*
47984** If the input FuncDef structure is ephemeral, then free it.  If
47985** the FuncDef is not ephermal, then do nothing.
47986*/
47987static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
47988  if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
47989    sqlite3DbFree(db, pDef);
47990  }
47991}
47992
47993/*
47994** Delete a P4 value if necessary.
47995*/
47996static void freeP4(sqlite3 *db, int p4type, void *p4){
47997  if( p4 ){
47998    switch( p4type ){
47999      case P4_REAL:
48000      case P4_INT64:
48001      case P4_MPRINTF:
48002      case P4_DYNAMIC:
48003      case P4_KEYINFO:
48004      case P4_INTARRAY:
48005      case P4_KEYINFO_HANDOFF: {
48006        sqlite3DbFree(db, p4);
48007        break;
48008      }
48009      case P4_VDBEFUNC: {
48010        VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
48011        freeEphemeralFunction(db, pVdbeFunc->pFunc);
48012        sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
48013        sqlite3DbFree(db, pVdbeFunc);
48014        break;
48015      }
48016      case P4_FUNCDEF: {
48017        freeEphemeralFunction(db, (FuncDef*)p4);
48018        break;
48019      }
48020      case P4_MEM: {
48021        sqlite3ValueFree((sqlite3_value*)p4);
48022        break;
48023      }
48024      case P4_VTAB : {
48025        sqlite3VtabUnlock((VTable *)p4);
48026        break;
48027      }
48028      case P4_SUBPROGRAM : {
48029        sqlite3VdbeProgramDelete(db, (SubProgram *)p4, 1);
48030        break;
48031      }
48032    }
48033  }
48034}
48035
48036/*
48037** Free the space allocated for aOp and any p4 values allocated for the
48038** opcodes contained within. If aOp is not NULL it is assumed to contain
48039** nOp entries.
48040*/
48041static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
48042  if( aOp ){
48043    Op *pOp;
48044    for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
48045      freeP4(db, pOp->p4type, pOp->p4.p);
48046#ifdef SQLITE_DEBUG
48047      sqlite3DbFree(db, pOp->zComment);
48048#endif
48049    }
48050  }
48051  sqlite3DbFree(db, aOp);
48052}
48053
48054/*
48055** Decrement the ref-count on the SubProgram structure passed as the
48056** second argument. If the ref-count reaches zero, free the structure.
48057**
48058** The array of VDBE opcodes stored as SubProgram.aOp is freed if
48059** either the ref-count reaches zero or parameter freeop is non-zero.
48060**
48061** Since the array of opcodes pointed to by SubProgram.aOp may directly
48062** or indirectly contain a reference to the SubProgram structure itself.
48063** By passing a non-zero freeop parameter, the caller may ensure that all
48064** SubProgram structures and their aOp arrays are freed, even when there
48065** are such circular references.
48066*/
48067SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *db, SubProgram *p, int freeop){
48068  if( p ){
48069    assert( p->nRef>0 );
48070    if( freeop || p->nRef==1 ){
48071      Op *aOp = p->aOp;
48072      p->aOp = 0;
48073      vdbeFreeOpArray(db, aOp, p->nOp);
48074      p->nOp = 0;
48075    }
48076    p->nRef--;
48077    if( p->nRef==0 ){
48078      sqlite3DbFree(db, p);
48079    }
48080  }
48081}
48082
48083
48084/*
48085** Change N opcodes starting at addr to No-ops.
48086*/
48087SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
48088  if( p->aOp ){
48089    VdbeOp *pOp = &p->aOp[addr];
48090    sqlite3 *db = p->db;
48091    while( N-- ){
48092      freeP4(db, pOp->p4type, pOp->p4.p);
48093      memset(pOp, 0, sizeof(pOp[0]));
48094      pOp->opcode = OP_Noop;
48095      pOp++;
48096    }
48097  }
48098}
48099
48100/*
48101** Change the value of the P4 operand for a specific instruction.
48102** This routine is useful when a large program is loaded from a
48103** static array using sqlite3VdbeAddOpList but we want to make a
48104** few minor changes to the program.
48105**
48106** If n>=0 then the P4 operand is dynamic, meaning that a copy of
48107** the string is made into memory obtained from sqlite3_malloc().
48108** A value of n==0 means copy bytes of zP4 up to and including the
48109** first null byte.  If n>0 then copy n+1 bytes of zP4.
48110**
48111** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
48112** A copy is made of the KeyInfo structure into memory obtained from
48113** sqlite3_malloc, to be freed when the Vdbe is finalized.
48114** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
48115** stored in memory that the caller has obtained from sqlite3_malloc. The
48116** caller should not free the allocation, it will be freed when the Vdbe is
48117** finalized.
48118**
48119** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
48120** to a string or structure that is guaranteed to exist for the lifetime of
48121** the Vdbe. In these cases we can just copy the pointer.
48122**
48123** If addr<0 then change P4 on the most recently inserted instruction.
48124*/
48125SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
48126  Op *pOp;
48127  sqlite3 *db;
48128  assert( p!=0 );
48129  db = p->db;
48130  assert( p->magic==VDBE_MAGIC_INIT );
48131  if( p->aOp==0 || db->mallocFailed ){
48132    if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
48133      freeP4(db, n, (void*)*(char**)&zP4);
48134    }
48135    return;
48136  }
48137  assert( p->nOp>0 );
48138  assert( addr<p->nOp );
48139  if( addr<0 ){
48140    addr = p->nOp - 1;
48141  }
48142  pOp = &p->aOp[addr];
48143  freeP4(db, pOp->p4type, pOp->p4.p);
48144  pOp->p4.p = 0;
48145  if( n==P4_INT32 ){
48146    /* Note: this cast is safe, because the origin data point was an int
48147    ** that was cast to a (const char *). */
48148    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
48149    pOp->p4type = P4_INT32;
48150  }else if( zP4==0 ){
48151    pOp->p4.p = 0;
48152    pOp->p4type = P4_NOTUSED;
48153  }else if( n==P4_KEYINFO ){
48154    KeyInfo *pKeyInfo;
48155    int nField, nByte;
48156
48157    nField = ((KeyInfo*)zP4)->nField;
48158    nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
48159    pKeyInfo = sqlite3Malloc( nByte );
48160    pOp->p4.pKeyInfo = pKeyInfo;
48161    if( pKeyInfo ){
48162      u8 *aSortOrder;
48163      memcpy(pKeyInfo, zP4, nByte);
48164      aSortOrder = pKeyInfo->aSortOrder;
48165      if( aSortOrder ){
48166        pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
48167        memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
48168      }
48169      pOp->p4type = P4_KEYINFO;
48170    }else{
48171      p->db->mallocFailed = 1;
48172      pOp->p4type = P4_NOTUSED;
48173    }
48174  }else if( n==P4_KEYINFO_HANDOFF ){
48175    pOp->p4.p = (void*)zP4;
48176    pOp->p4type = P4_KEYINFO;
48177  }else if( n==P4_VTAB ){
48178    pOp->p4.p = (void*)zP4;
48179    pOp->p4type = P4_VTAB;
48180    sqlite3VtabLock((VTable *)zP4);
48181    assert( ((VTable *)zP4)->db==p->db );
48182  }else if( n<0 ){
48183    pOp->p4.p = (void*)zP4;
48184    pOp->p4type = (signed char)n;
48185  }else{
48186    if( n==0 ) n = sqlite3Strlen30(zP4);
48187    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
48188    pOp->p4type = P4_DYNAMIC;
48189  }
48190}
48191
48192#ifndef NDEBUG
48193/*
48194** Change the comment on the the most recently coded instruction.  Or
48195** insert a No-op and add the comment to that new instruction.  This
48196** makes the code easier to read during debugging.  None of this happens
48197** in a production build.
48198*/
48199SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
48200  va_list ap;
48201  if( !p ) return;
48202  assert( p->nOp>0 || p->aOp==0 );
48203  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
48204  if( p->nOp ){
48205    char **pz = &p->aOp[p->nOp-1].zComment;
48206    va_start(ap, zFormat);
48207    sqlite3DbFree(p->db, *pz);
48208    *pz = sqlite3VMPrintf(p->db, zFormat, ap);
48209    va_end(ap);
48210  }
48211}
48212SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
48213  va_list ap;
48214  if( !p ) return;
48215  sqlite3VdbeAddOp0(p, OP_Noop);
48216  assert( p->nOp>0 || p->aOp==0 );
48217  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
48218  if( p->nOp ){
48219    char **pz = &p->aOp[p->nOp-1].zComment;
48220    va_start(ap, zFormat);
48221    sqlite3DbFree(p->db, *pz);
48222    *pz = sqlite3VMPrintf(p->db, zFormat, ap);
48223    va_end(ap);
48224  }
48225}
48226#endif  /* NDEBUG */
48227
48228/*
48229** Return the opcode for a given address.  If the address is -1, then
48230** return the most recently inserted opcode.
48231**
48232** If a memory allocation error has occurred prior to the calling of this
48233** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
48234** is readable and writable, but it has no effect.  The return of a dummy
48235** opcode allows the call to continue functioning after a OOM fault without
48236** having to check to see if the return from this routine is a valid pointer.
48237**
48238** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
48239** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
48240** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
48241** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
48242** having to double-check to make sure that the result is non-negative. But
48243** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
48244** check the value of p->nOp-1 before continuing.
48245*/
48246SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
48247  static VdbeOp dummy;
48248  assert( p->magic==VDBE_MAGIC_INIT );
48249  if( addr<0 ){
48250#ifdef SQLITE_OMIT_TRACE
48251    if( p->nOp==0 ) return &dummy;
48252#endif
48253    addr = p->nOp - 1;
48254  }
48255  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
48256  if( p->db->mallocFailed ){
48257    return &dummy;
48258  }else{
48259    return &p->aOp[addr];
48260  }
48261}
48262
48263#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
48264     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
48265/*
48266** Compute a string that describes the P4 parameter for an opcode.
48267** Use zTemp for any required temporary buffer space.
48268*/
48269static char *displayP4(Op *pOp, char *zTemp, int nTemp){
48270  char *zP4 = zTemp;
48271  assert( nTemp>=20 );
48272  switch( pOp->p4type ){
48273    case P4_KEYINFO_STATIC:
48274    case P4_KEYINFO: {
48275      int i, j;
48276      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
48277      sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
48278      i = sqlite3Strlen30(zTemp);
48279      for(j=0; j<pKeyInfo->nField; j++){
48280        CollSeq *pColl = pKeyInfo->aColl[j];
48281        if( pColl ){
48282          int n = sqlite3Strlen30(pColl->zName);
48283          if( i+n>nTemp-6 ){
48284            memcpy(&zTemp[i],",...",4);
48285            break;
48286          }
48287          zTemp[i++] = ',';
48288          if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
48289            zTemp[i++] = '-';
48290          }
48291          memcpy(&zTemp[i], pColl->zName,n+1);
48292          i += n;
48293        }else if( i+4<nTemp-6 ){
48294          memcpy(&zTemp[i],",nil",4);
48295          i += 4;
48296        }
48297      }
48298      zTemp[i++] = ')';
48299      zTemp[i] = 0;
48300      assert( i<nTemp );
48301      break;
48302    }
48303    case P4_COLLSEQ: {
48304      CollSeq *pColl = pOp->p4.pColl;
48305      sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
48306      break;
48307    }
48308    case P4_FUNCDEF: {
48309      FuncDef *pDef = pOp->p4.pFunc;
48310      sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
48311      break;
48312    }
48313    case P4_INT64: {
48314      sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
48315      break;
48316    }
48317    case P4_INT32: {
48318      sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
48319      break;
48320    }
48321    case P4_REAL: {
48322      sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
48323      break;
48324    }
48325    case P4_MEM: {
48326      Mem *pMem = pOp->p4.pMem;
48327      assert( (pMem->flags & MEM_Null)==0 );
48328      if( pMem->flags & MEM_Str ){
48329        zP4 = pMem->z;
48330      }else if( pMem->flags & MEM_Int ){
48331        sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
48332      }else if( pMem->flags & MEM_Real ){
48333        sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
48334      }else{
48335        assert( pMem->flags & MEM_Blob );
48336        zP4 = "(blob)";
48337      }
48338      break;
48339    }
48340#ifndef SQLITE_OMIT_VIRTUALTABLE
48341    case P4_VTAB: {
48342      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
48343      sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
48344      break;
48345    }
48346#endif
48347    case P4_INTARRAY: {
48348      sqlite3_snprintf(nTemp, zTemp, "intarray");
48349      break;
48350    }
48351    case P4_SUBPROGRAM: {
48352      sqlite3_snprintf(nTemp, zTemp, "program");
48353      break;
48354    }
48355    default: {
48356      zP4 = pOp->p4.z;
48357      if( zP4==0 ){
48358        zP4 = zTemp;
48359        zTemp[0] = 0;
48360      }
48361    }
48362  }
48363  assert( zP4!=0 );
48364  return zP4;
48365}
48366#endif
48367
48368/*
48369** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
48370*/
48371SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
48372  int mask;
48373  assert( i>=0 && i<p->db->nDb && i<sizeof(u32)*8 );
48374  assert( i<(int)sizeof(p->btreeMask)*8 );
48375  mask = ((u32)1)<<i;
48376  if( (p->btreeMask & mask)==0 ){
48377    p->btreeMask |= mask;
48378    sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
48379  }
48380}
48381
48382
48383#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
48384/*
48385** Print a single opcode.  This routine is used for debugging only.
48386*/
48387SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
48388  char *zP4;
48389  char zPtr[50];
48390  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
48391  if( pOut==0 ) pOut = stdout;
48392  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
48393  fprintf(pOut, zFormat1, pc,
48394      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
48395#ifdef SQLITE_DEBUG
48396      pOp->zComment ? pOp->zComment : ""
48397#else
48398      ""
48399#endif
48400  );
48401  fflush(pOut);
48402}
48403#endif
48404
48405/*
48406** Release an array of N Mem elements
48407*/
48408static void releaseMemArray(Mem *p, int N){
48409  if( p && N ){
48410    Mem *pEnd;
48411    sqlite3 *db = p->db;
48412    u8 malloc_failed = db->mallocFailed;
48413    for(pEnd=&p[N]; p<pEnd; p++){
48414      assert( (&p[1])==pEnd || p[0].db==p[1].db );
48415
48416      /* This block is really an inlined version of sqlite3VdbeMemRelease()
48417      ** that takes advantage of the fact that the memory cell value is
48418      ** being set to NULL after releasing any dynamic resources.
48419      **
48420      ** The justification for duplicating code is that according to
48421      ** callgrind, this causes a certain test case to hit the CPU 4.7
48422      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
48423      ** sqlite3MemRelease() were called from here. With -O2, this jumps
48424      ** to 6.6 percent. The test case is inserting 1000 rows into a table
48425      ** with no indexes using a single prepared INSERT statement, bind()
48426      ** and reset(). Inserts are grouped into a transaction.
48427      */
48428      if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
48429        sqlite3VdbeMemRelease(p);
48430      }else if( p->zMalloc ){
48431        sqlite3DbFree(db, p->zMalloc);
48432        p->zMalloc = 0;
48433      }
48434
48435      p->flags = MEM_Null;
48436    }
48437    db->mallocFailed = malloc_failed;
48438  }
48439}
48440
48441/*
48442** Delete a VdbeFrame object and its contents. VdbeFrame objects are
48443** allocated by the OP_Program opcode in sqlite3VdbeExec().
48444*/
48445SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
48446  int i;
48447  Mem *aMem = VdbeFrameMem(p);
48448  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
48449  for(i=0; i<p->nChildCsr; i++){
48450    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
48451  }
48452  releaseMemArray(aMem, p->nChildMem);
48453  sqlite3DbFree(p->v->db, p);
48454}
48455
48456#ifndef SQLITE_OMIT_EXPLAIN
48457/*
48458** Give a listing of the program in the virtual machine.
48459**
48460** The interface is the same as sqlite3VdbeExec().  But instead of
48461** running the code, it invokes the callback once for each instruction.
48462** This feature is used to implement "EXPLAIN".
48463**
48464** When p->explain==1, each instruction is listed.  When
48465** p->explain==2, only OP_Explain instructions are listed and these
48466** are shown in a different format.  p->explain==2 is used to implement
48467** EXPLAIN QUERY PLAN.
48468**
48469** When p->explain==1, first the main program is listed, then each of
48470** the trigger subprograms are listed one by one.
48471*/
48472SQLITE_PRIVATE int sqlite3VdbeList(
48473  Vdbe *p                   /* The VDBE */
48474){
48475  int nRow;                            /* Stop when row count reaches this */
48476  int nSub = 0;                        /* Number of sub-vdbes seen so far */
48477  SubProgram **apSub = 0;              /* Array of sub-vdbes */
48478  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
48479  sqlite3 *db = p->db;                 /* The database connection */
48480  int i;                               /* Loop counter */
48481  int rc = SQLITE_OK;                  /* Return code */
48482  Mem *pMem = p->pResultSet = &p->aMem[1];  /* First Mem of result set */
48483
48484  assert( p->explain );
48485  assert( p->magic==VDBE_MAGIC_RUN );
48486  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
48487
48488  /* Even though this opcode does not use dynamic strings for
48489  ** the result, result columns may become dynamic if the user calls
48490  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
48491  */
48492  releaseMemArray(pMem, 8);
48493
48494  if( p->rc==SQLITE_NOMEM ){
48495    /* This happens if a malloc() inside a call to sqlite3_column_text() or
48496    ** sqlite3_column_text16() failed.  */
48497    db->mallocFailed = 1;
48498    return SQLITE_ERROR;
48499  }
48500
48501  /* When the number of output rows reaches nRow, that means the
48502  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
48503  ** nRow is the sum of the number of rows in the main program, plus
48504  ** the sum of the number of rows in all trigger subprograms encountered
48505  ** so far.  The nRow value will increase as new trigger subprograms are
48506  ** encountered, but p->pc will eventually catch up to nRow.
48507  */
48508  nRow = p->nOp;
48509  if( p->explain==1 ){
48510    /* The first 8 memory cells are used for the result set.  So we will
48511    ** commandeer the 9th cell to use as storage for an array of pointers
48512    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
48513    ** cells.  */
48514    assert( p->nMem>9 );
48515    pSub = &p->aMem[9];
48516    if( pSub->flags&MEM_Blob ){
48517      /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
48518      ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
48519      nSub = pSub->n/sizeof(Vdbe*);
48520      apSub = (SubProgram **)pSub->z;
48521    }
48522    for(i=0; i<nSub; i++){
48523      nRow += apSub[i]->nOp;
48524    }
48525  }
48526
48527  do{
48528    i = p->pc++;
48529  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
48530  if( i>=nRow ){
48531    p->rc = SQLITE_OK;
48532    rc = SQLITE_DONE;
48533  }else if( db->u1.isInterrupted ){
48534    p->rc = SQLITE_INTERRUPT;
48535    rc = SQLITE_ERROR;
48536    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
48537  }else{
48538    char *z;
48539    Op *pOp;
48540    if( i<p->nOp ){
48541      /* The output line number is small enough that we are still in the
48542      ** main program. */
48543      pOp = &p->aOp[i];
48544    }else{
48545      /* We are currently listing subprograms.  Figure out which one and
48546      ** pick up the appropriate opcode. */
48547      int j;
48548      i -= p->nOp;
48549      for(j=0; i>=apSub[j]->nOp; j++){
48550        i -= apSub[j]->nOp;
48551      }
48552      pOp = &apSub[j]->aOp[i];
48553    }
48554    if( p->explain==1 ){
48555      pMem->flags = MEM_Int;
48556      pMem->type = SQLITE_INTEGER;
48557      pMem->u.i = i;                                /* Program counter */
48558      pMem++;
48559
48560      pMem->flags = MEM_Static|MEM_Str|MEM_Term;
48561      pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
48562      assert( pMem->z!=0 );
48563      pMem->n = sqlite3Strlen30(pMem->z);
48564      pMem->type = SQLITE_TEXT;
48565      pMem->enc = SQLITE_UTF8;
48566      pMem++;
48567
48568      /* When an OP_Program opcode is encounter (the only opcode that has
48569      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
48570      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
48571      ** has not already been seen.
48572      */
48573      if( pOp->p4type==P4_SUBPROGRAM ){
48574        int nByte = (nSub+1)*sizeof(SubProgram*);
48575        int j;
48576        for(j=0; j<nSub; j++){
48577          if( apSub[j]==pOp->p4.pProgram ) break;
48578        }
48579        if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
48580          apSub = (SubProgram **)pSub->z;
48581          apSub[nSub++] = pOp->p4.pProgram;
48582          pSub->flags |= MEM_Blob;
48583          pSub->n = nSub*sizeof(SubProgram*);
48584        }
48585      }
48586    }
48587
48588    pMem->flags = MEM_Int;
48589    pMem->u.i = pOp->p1;                          /* P1 */
48590    pMem->type = SQLITE_INTEGER;
48591    pMem++;
48592
48593    pMem->flags = MEM_Int;
48594    pMem->u.i = pOp->p2;                          /* P2 */
48595    pMem->type = SQLITE_INTEGER;
48596    pMem++;
48597
48598    if( p->explain==1 ){
48599      pMem->flags = MEM_Int;
48600      pMem->u.i = pOp->p3;                          /* P3 */
48601      pMem->type = SQLITE_INTEGER;
48602      pMem++;
48603    }
48604
48605    if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
48606      assert( p->db->mallocFailed );
48607      return SQLITE_ERROR;
48608    }
48609    pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
48610    z = displayP4(pOp, pMem->z, 32);
48611    if( z!=pMem->z ){
48612      sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
48613    }else{
48614      assert( pMem->z!=0 );
48615      pMem->n = sqlite3Strlen30(pMem->z);
48616      pMem->enc = SQLITE_UTF8;
48617    }
48618    pMem->type = SQLITE_TEXT;
48619    pMem++;
48620
48621    if( p->explain==1 ){
48622      if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
48623        assert( p->db->mallocFailed );
48624        return SQLITE_ERROR;
48625      }
48626      pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
48627      pMem->n = 2;
48628      sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
48629      pMem->type = SQLITE_TEXT;
48630      pMem->enc = SQLITE_UTF8;
48631      pMem++;
48632
48633#ifdef SQLITE_DEBUG
48634      if( pOp->zComment ){
48635        pMem->flags = MEM_Str|MEM_Term;
48636        pMem->z = pOp->zComment;
48637        pMem->n = sqlite3Strlen30(pMem->z);
48638        pMem->enc = SQLITE_UTF8;
48639        pMem->type = SQLITE_TEXT;
48640      }else
48641#endif
48642      {
48643        pMem->flags = MEM_Null;                       /* Comment */
48644        pMem->type = SQLITE_NULL;
48645      }
48646    }
48647
48648    p->nResColumn = 8 - 5*(p->explain-1);
48649    p->rc = SQLITE_OK;
48650    rc = SQLITE_ROW;
48651  }
48652  return rc;
48653}
48654#endif /* SQLITE_OMIT_EXPLAIN */
48655
48656#ifdef SQLITE_DEBUG
48657/*
48658** Print the SQL that was used to generate a VDBE program.
48659*/
48660SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
48661  int nOp = p->nOp;
48662  VdbeOp *pOp;
48663  if( nOp<1 ) return;
48664  pOp = &p->aOp[0];
48665  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
48666    const char *z = pOp->p4.z;
48667    while( sqlite3Isspace(*z) ) z++;
48668    printf("SQL: [%s]\n", z);
48669  }
48670}
48671#endif
48672
48673#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
48674/*
48675** Print an IOTRACE message showing SQL content.
48676*/
48677SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
48678  int nOp = p->nOp;
48679  VdbeOp *pOp;
48680  if( sqlite3IoTrace==0 ) return;
48681  if( nOp<1 ) return;
48682  pOp = &p->aOp[0];
48683  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
48684    int i, j;
48685    char z[1000];
48686    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
48687    for(i=0; sqlite3Isspace(z[i]); i++){}
48688    for(j=0; z[i]; i++){
48689      if( sqlite3Isspace(z[i]) ){
48690        if( z[i-1]!=' ' ){
48691          z[j++] = ' ';
48692        }
48693      }else{
48694        z[j++] = z[i];
48695      }
48696    }
48697    z[j] = 0;
48698    sqlite3IoTrace("SQL %s\n", z);
48699  }
48700}
48701#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
48702
48703/*
48704** Allocate space from a fixed size buffer and return a pointer to
48705** that space.  If insufficient space is available, return NULL.
48706**
48707** The pBuf parameter is the initial value of a pointer which will
48708** receive the new memory.  pBuf is normally NULL.  If pBuf is not
48709** NULL, it means that memory space has already been allocated and that
48710** this routine should not allocate any new memory.  When pBuf is not
48711** NULL simply return pBuf.  Only allocate new memory space when pBuf
48712** is NULL.
48713**
48714** nByte is the number of bytes of space needed.
48715**
48716** *ppFrom points to available space and pEnd points to the end of the
48717** available space.  When space is allocated, *ppFrom is advanced past
48718** the end of the allocated space.
48719**
48720** *pnByte is a counter of the number of bytes of space that have failed
48721** to allocate.  If there is insufficient space in *ppFrom to satisfy the
48722** request, then increment *pnByte by the amount of the request.
48723*/
48724static void *allocSpace(
48725  void *pBuf,          /* Where return pointer will be stored */
48726  int nByte,           /* Number of bytes to allocate */
48727  u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
48728  u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
48729  int *pnByte          /* If allocation cannot be made, increment *pnByte */
48730){
48731  assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
48732  if( pBuf ) return pBuf;
48733  nByte = ROUND8(nByte);
48734  if( &(*ppFrom)[nByte] <= pEnd ){
48735    pBuf = (void*)*ppFrom;
48736    *ppFrom += nByte;
48737  }else{
48738    *pnByte += nByte;
48739  }
48740  return pBuf;
48741}
48742
48743/*
48744** Prepare a virtual machine for execution.  This involves things such
48745** as allocating stack space and initializing the program counter.
48746** After the VDBE has be prepped, it can be executed by one or more
48747** calls to sqlite3VdbeExec().
48748**
48749** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
48750** VDBE_MAGIC_RUN.
48751**
48752** This function may be called more than once on a single virtual machine.
48753** The first call is made while compiling the SQL statement. Subsequent
48754** calls are made as part of the process of resetting a statement to be
48755** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor
48756** and isExplain parameters are only passed correct values the first time
48757** the function is called. On subsequent calls, from sqlite3_reset(), nVar
48758** is passed -1 and nMem, nCursor and isExplain are all passed zero.
48759*/
48760SQLITE_PRIVATE void sqlite3VdbeMakeReady(
48761  Vdbe *p,                       /* The VDBE */
48762  int nVar,                      /* Number of '?' see in the SQL statement */
48763  int nMem,                      /* Number of memory cells to allocate */
48764  int nCursor,                   /* Number of cursors to allocate */
48765  int nArg,                      /* Maximum number of args in SubPrograms */
48766  int isExplain,                 /* True if the EXPLAIN keywords is present */
48767  int usesStmtJournal            /* True to set Vdbe.usesStmtJournal */
48768){
48769  int n;
48770  sqlite3 *db = p->db;
48771
48772  assert( p!=0 );
48773  assert( p->magic==VDBE_MAGIC_INIT );
48774
48775  /* There should be at least one opcode.
48776  */
48777  assert( p->nOp>0 );
48778
48779  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
48780  p->magic = VDBE_MAGIC_RUN;
48781
48782  /* For each cursor required, also allocate a memory cell. Memory
48783  ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
48784  ** the vdbe program. Instead they are used to allocate space for
48785  ** VdbeCursor/BtCursor structures. The blob of memory associated with
48786  ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
48787  ** stores the blob of memory associated with cursor 1, etc.
48788  **
48789  ** See also: allocateCursor().
48790  */
48791  nMem += nCursor;
48792
48793  /* Allocate space for memory registers, SQL variables, VDBE cursors and
48794  ** an array to marshal SQL function arguments in. This is only done the
48795  ** first time this function is called for a given VDBE, not when it is
48796  ** being called from sqlite3_reset() to reset the virtual machine.
48797  */
48798  if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
48799    u8 *zCsr = (u8 *)&p->aOp[p->nOp];       /* Memory avaliable for alloation */
48800    u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];  /* First byte past available mem */
48801    int nByte;                              /* How much extra memory needed */
48802
48803    resolveP2Values(p, &nArg);
48804    p->usesStmtJournal = (u8)usesStmtJournal;
48805    if( isExplain && nMem<10 ){
48806      nMem = 10;
48807    }
48808    memset(zCsr, 0, zEnd-zCsr);
48809    zCsr += (zCsr - (u8*)0)&7;
48810    assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
48811
48812    /* Memory for registers, parameters, cursor, etc, is allocated in two
48813    ** passes.  On the first pass, we try to reuse unused space at the
48814    ** end of the opcode array.  If we are unable to satisfy all memory
48815    ** requirements by reusing the opcode array tail, then the second
48816    ** pass will fill in the rest using a fresh allocation.
48817    **
48818    ** This two-pass approach that reuses as much memory as possible from
48819    ** the leftover space at the end of the opcode array can significantly
48820    ** reduce the amount of memory held by a prepared statement.
48821    */
48822    do {
48823      nByte = 0;
48824      p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
48825      p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
48826      p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
48827      p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
48828      p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
48829                            &zCsr, zEnd, &nByte);
48830      if( nByte ){
48831        p->pFree = sqlite3DbMallocZero(db, nByte);
48832      }
48833      zCsr = p->pFree;
48834      zEnd = &zCsr[nByte];
48835    }while( nByte && !db->mallocFailed );
48836
48837    p->nCursor = (u16)nCursor;
48838    if( p->aVar ){
48839      p->nVar = (ynVar)nVar;
48840      for(n=0; n<nVar; n++){
48841        p->aVar[n].flags = MEM_Null;
48842        p->aVar[n].db = db;
48843      }
48844    }
48845    if( p->aMem ){
48846      p->aMem--;                      /* aMem[] goes from 1..nMem */
48847      p->nMem = nMem;                 /*       not from 0..nMem-1 */
48848      for(n=1; n<=nMem; n++){
48849        p->aMem[n].flags = MEM_Null;
48850        p->aMem[n].db = db;
48851      }
48852    }
48853  }
48854#ifdef SQLITE_DEBUG
48855  for(n=1; n<p->nMem; n++){
48856    assert( p->aMem[n].db==db );
48857  }
48858#endif
48859
48860  p->pc = -1;
48861  p->rc = SQLITE_OK;
48862  p->errorAction = OE_Abort;
48863  p->explain |= isExplain;
48864  p->magic = VDBE_MAGIC_RUN;
48865  p->nChange = 0;
48866  p->cacheCtr = 1;
48867  p->minWriteFileFormat = 255;
48868  p->iStatement = 0;
48869#ifdef VDBE_PROFILE
48870  {
48871    int i;
48872    for(i=0; i<p->nOp; i++){
48873      p->aOp[i].cnt = 0;
48874      p->aOp[i].cycles = 0;
48875    }
48876  }
48877#endif
48878}
48879
48880/*
48881** Close a VDBE cursor and release all the resources that cursor
48882** happens to hold.
48883*/
48884SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
48885  if( pCx==0 ){
48886    return;
48887  }
48888  if( pCx->pBt ){
48889    sqlite3BtreeClose(pCx->pBt);
48890    /* The pCx->pCursor will be close automatically, if it exists, by
48891    ** the call above. */
48892  }else if( pCx->pCursor ){
48893    sqlite3BtreeCloseCursor(pCx->pCursor);
48894  }
48895#ifndef SQLITE_OMIT_VIRTUALTABLE
48896  if( pCx->pVtabCursor ){
48897    sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
48898    const sqlite3_module *pModule = pCx->pModule;
48899    p->inVtabMethod = 1;
48900    pModule->xClose(pVtabCursor);
48901    p->inVtabMethod = 0;
48902  }
48903#endif
48904}
48905
48906/*
48907** Copy the values stored in the VdbeFrame structure to its Vdbe. This
48908** is used, for example, when a trigger sub-program is halted to restore
48909** control to the main program.
48910*/
48911SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
48912  Vdbe *v = pFrame->v;
48913  v->aOp = pFrame->aOp;
48914  v->nOp = pFrame->nOp;
48915  v->aMem = pFrame->aMem;
48916  v->nMem = pFrame->nMem;
48917  v->apCsr = pFrame->apCsr;
48918  v->nCursor = pFrame->nCursor;
48919  v->db->lastRowid = pFrame->lastRowid;
48920  v->nChange = pFrame->nChange;
48921  return pFrame->pc;
48922}
48923
48924/*
48925** Close all cursors.
48926**
48927** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
48928** cell array. This is necessary as the memory cell array may contain
48929** pointers to VdbeFrame objects, which may in turn contain pointers to
48930** open cursors.
48931*/
48932static void closeAllCursors(Vdbe *p){
48933  if( p->pFrame ){
48934    VdbeFrame *pFrame = p->pFrame;
48935    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
48936    sqlite3VdbeFrameRestore(pFrame);
48937  }
48938  p->pFrame = 0;
48939  p->nFrame = 0;
48940
48941  if( p->apCsr ){
48942    int i;
48943    for(i=0; i<p->nCursor; i++){
48944      VdbeCursor *pC = p->apCsr[i];
48945      if( pC ){
48946        sqlite3VdbeFreeCursor(p, pC);
48947        p->apCsr[i] = 0;
48948      }
48949    }
48950  }
48951  if( p->aMem ){
48952    releaseMemArray(&p->aMem[1], p->nMem);
48953  }
48954}
48955
48956/*
48957** Clean up the VM after execution.
48958**
48959** This routine will automatically close any cursors, lists, and/or
48960** sorters that were left open.  It also deletes the values of
48961** variables in the aVar[] array.
48962*/
48963static void Cleanup(Vdbe *p){
48964  sqlite3 *db = p->db;
48965
48966#ifdef SQLITE_DEBUG
48967  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
48968  ** Vdbe.aMem[] arrays have already been cleaned up.  */
48969  int i;
48970  for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
48971  for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
48972#endif
48973
48974  sqlite3DbFree(db, p->zErrMsg);
48975  p->zErrMsg = 0;
48976  p->pResultSet = 0;
48977}
48978
48979/*
48980** Set the number of result columns that will be returned by this SQL
48981** statement. This is now set at compile time, rather than during
48982** execution of the vdbe program so that sqlite3_column_count() can
48983** be called on an SQL statement before sqlite3_step().
48984*/
48985SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
48986  Mem *pColName;
48987  int n;
48988  sqlite3 *db = p->db;
48989
48990  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
48991  sqlite3DbFree(db, p->aColName);
48992  n = nResColumn*COLNAME_N;
48993  p->nResColumn = (u16)nResColumn;
48994  p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
48995  if( p->aColName==0 ) return;
48996  while( n-- > 0 ){
48997    pColName->flags = MEM_Null;
48998    pColName->db = p->db;
48999    pColName++;
49000  }
49001}
49002
49003/*
49004** Set the name of the idx'th column to be returned by the SQL statement.
49005** zName must be a pointer to a nul terminated string.
49006**
49007** This call must be made after a call to sqlite3VdbeSetNumCols().
49008**
49009** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
49010** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
49011** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
49012*/
49013SQLITE_PRIVATE int sqlite3VdbeSetColName(
49014  Vdbe *p,                         /* Vdbe being configured */
49015  int idx,                         /* Index of column zName applies to */
49016  int var,                         /* One of the COLNAME_* constants */
49017  const char *zName,               /* Pointer to buffer containing name */
49018  void (*xDel)(void*)              /* Memory management strategy for zName */
49019){
49020  int rc;
49021  Mem *pColName;
49022  assert( idx<p->nResColumn );
49023  assert( var<COLNAME_N );
49024  if( p->db->mallocFailed ){
49025    assert( !zName || xDel!=SQLITE_DYNAMIC );
49026    return SQLITE_NOMEM;
49027  }
49028  assert( p->aColName!=0 );
49029  pColName = &(p->aColName[idx+var*p->nResColumn]);
49030  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
49031  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
49032  return rc;
49033}
49034
49035/*
49036** A read or write transaction may or may not be active on database handle
49037** db. If a transaction is active, commit it. If there is a
49038** write-transaction spanning more than one database file, this routine
49039** takes care of the master journal trickery.
49040*/
49041static int vdbeCommit(sqlite3 *db, Vdbe *p){
49042  int i;
49043  int nTrans = 0;  /* Number of databases with an active write-transaction */
49044  int rc = SQLITE_OK;
49045  int needXcommit = 0;
49046
49047#ifdef SQLITE_OMIT_VIRTUALTABLE
49048  /* With this option, sqlite3VtabSync() is defined to be simply
49049  ** SQLITE_OK so p is not used.
49050  */
49051  UNUSED_PARAMETER(p);
49052#endif
49053
49054  /* Before doing anything else, call the xSync() callback for any
49055  ** virtual module tables written in this transaction. This has to
49056  ** be done before determining whether a master journal file is
49057  ** required, as an xSync() callback may add an attached database
49058  ** to the transaction.
49059  */
49060  rc = sqlite3VtabSync(db, &p->zErrMsg);
49061  if( rc!=SQLITE_OK ){
49062    return rc;
49063  }
49064
49065  /* This loop determines (a) if the commit hook should be invoked and
49066  ** (b) how many database files have open write transactions, not
49067  ** including the temp database. (b) is important because if more than
49068  ** one database file has an open write transaction, a master journal
49069  ** file is required for an atomic commit.
49070  */
49071  for(i=0; i<db->nDb; i++){
49072    Btree *pBt = db->aDb[i].pBt;
49073    if( sqlite3BtreeIsInTrans(pBt) ){
49074      needXcommit = 1;
49075      if( i!=1 ) nTrans++;
49076    }
49077  }
49078
49079  /* If there are any write-transactions at all, invoke the commit hook */
49080  if( needXcommit && db->xCommitCallback ){
49081    rc = db->xCommitCallback(db->pCommitArg);
49082    if( rc ){
49083      return SQLITE_CONSTRAINT;
49084    }
49085  }
49086
49087  /* The simple case - no more than one database file (not counting the
49088  ** TEMP database) has a transaction active.   There is no need for the
49089  ** master-journal.
49090  **
49091  ** If the return value of sqlite3BtreeGetFilename() is a zero length
49092  ** string, it means the main database is :memory: or a temp file.  In
49093  ** that case we do not support atomic multi-file commits, so use the
49094  ** simple case then too.
49095  */
49096  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
49097   || nTrans<=1
49098  ){
49099    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
49100      Btree *pBt = db->aDb[i].pBt;
49101      if( pBt ){
49102        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
49103      }
49104    }
49105
49106    /* Do the commit only if all databases successfully complete phase 1.
49107    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
49108    ** IO error while deleting or truncating a journal file. It is unlikely,
49109    ** but could happen. In this case abandon processing and return the error.
49110    */
49111    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
49112      Btree *pBt = db->aDb[i].pBt;
49113      if( pBt ){
49114        rc = sqlite3BtreeCommitPhaseTwo(pBt);
49115      }
49116    }
49117    if( rc==SQLITE_OK ){
49118      sqlite3VtabCommit(db);
49119    }
49120  }
49121
49122  /* The complex case - There is a multi-file write-transaction active.
49123  ** This requires a master journal file to ensure the transaction is
49124  ** committed atomicly.
49125  */
49126#ifndef SQLITE_OMIT_DISKIO
49127  else{
49128    sqlite3_vfs *pVfs = db->pVfs;
49129    int needSync = 0;
49130    char *zMaster = 0;   /* File-name for the master journal */
49131    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
49132    sqlite3_file *pMaster = 0;
49133    i64 offset = 0;
49134    int res;
49135
49136    /* Select a master journal file name */
49137    do {
49138      u32 iRandom;
49139      sqlite3DbFree(db, zMaster);
49140      sqlite3_randomness(sizeof(iRandom), &iRandom);
49141      zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
49142      if( !zMaster ){
49143        return SQLITE_NOMEM;
49144      }
49145      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
49146    }while( rc==SQLITE_OK && res );
49147    if( rc==SQLITE_OK ){
49148      /* Open the master journal. */
49149      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
49150          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
49151          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
49152      );
49153    }
49154    if( rc!=SQLITE_OK ){
49155      sqlite3DbFree(db, zMaster);
49156      return rc;
49157    }
49158
49159    /* Write the name of each database file in the transaction into the new
49160    ** master journal file. If an error occurs at this point close
49161    ** and delete the master journal file. All the individual journal files
49162    ** still have 'null' as the master journal pointer, so they will roll
49163    ** back independently if a failure occurs.
49164    */
49165    for(i=0; i<db->nDb; i++){
49166      Btree *pBt = db->aDb[i].pBt;
49167      if( sqlite3BtreeIsInTrans(pBt) ){
49168        char const *zFile = sqlite3BtreeGetJournalname(pBt);
49169        if( zFile==0 || zFile[0]==0 ){
49170          continue;  /* Ignore TEMP and :memory: databases */
49171        }
49172        if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
49173          needSync = 1;
49174        }
49175        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
49176        offset += sqlite3Strlen30(zFile)+1;
49177        if( rc!=SQLITE_OK ){
49178          sqlite3OsCloseFree(pMaster);
49179          sqlite3OsDelete(pVfs, zMaster, 0);
49180          sqlite3DbFree(db, zMaster);
49181          return rc;
49182        }
49183      }
49184    }
49185
49186    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
49187    ** flag is set this is not required.
49188    */
49189    if( needSync
49190     && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
49191     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
49192    ){
49193      sqlite3OsCloseFree(pMaster);
49194      sqlite3OsDelete(pVfs, zMaster, 0);
49195      sqlite3DbFree(db, zMaster);
49196      return rc;
49197    }
49198
49199    /* Sync all the db files involved in the transaction. The same call
49200    ** sets the master journal pointer in each individual journal. If
49201    ** an error occurs here, do not delete the master journal file.
49202    **
49203    ** If the error occurs during the first call to
49204    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
49205    ** master journal file will be orphaned. But we cannot delete it,
49206    ** in case the master journal file name was written into the journal
49207    ** file before the failure occurred.
49208    */
49209    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
49210      Btree *pBt = db->aDb[i].pBt;
49211      if( pBt ){
49212        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
49213      }
49214    }
49215    sqlite3OsCloseFree(pMaster);
49216    if( rc!=SQLITE_OK ){
49217      sqlite3DbFree(db, zMaster);
49218      return rc;
49219    }
49220
49221    /* Delete the master journal file. This commits the transaction. After
49222    ** doing this the directory is synced again before any individual
49223    ** transaction files are deleted.
49224    */
49225    rc = sqlite3OsDelete(pVfs, zMaster, 1);
49226    sqlite3DbFree(db, zMaster);
49227    zMaster = 0;
49228    if( rc ){
49229      return rc;
49230    }
49231
49232    /* All files and directories have already been synced, so the following
49233    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
49234    ** deleting or truncating journals. If something goes wrong while
49235    ** this is happening we don't really care. The integrity of the
49236    ** transaction is already guaranteed, but some stray 'cold' journals
49237    ** may be lying around. Returning an error code won't help matters.
49238    */
49239    disable_simulated_io_errors();
49240    sqlite3BeginBenignMalloc();
49241    for(i=0; i<db->nDb; i++){
49242      Btree *pBt = db->aDb[i].pBt;
49243      if( pBt ){
49244        sqlite3BtreeCommitPhaseTwo(pBt);
49245      }
49246    }
49247    sqlite3EndBenignMalloc();
49248    enable_simulated_io_errors();
49249
49250    sqlite3VtabCommit(db);
49251  }
49252#endif
49253
49254  return rc;
49255}
49256
49257/*
49258** This routine checks that the sqlite3.activeVdbeCnt count variable
49259** matches the number of vdbe's in the list sqlite3.pVdbe that are
49260** currently active. An assertion fails if the two counts do not match.
49261** This is an internal self-check only - it is not an essential processing
49262** step.
49263**
49264** This is a no-op if NDEBUG is defined.
49265*/
49266#ifndef NDEBUG
49267static void checkActiveVdbeCnt(sqlite3 *db){
49268  Vdbe *p;
49269  int cnt = 0;
49270  int nWrite = 0;
49271  p = db->pVdbe;
49272  while( p ){
49273    if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
49274      cnt++;
49275      if( p->readOnly==0 ) nWrite++;
49276    }
49277    p = p->pNext;
49278  }
49279  assert( cnt==db->activeVdbeCnt );
49280  assert( nWrite==db->writeVdbeCnt );
49281}
49282#else
49283#define checkActiveVdbeCnt(x)
49284#endif
49285
49286/*
49287** For every Btree that in database connection db which
49288** has been modified, "trip" or invalidate each cursor in
49289** that Btree might have been modified so that the cursor
49290** can never be used again.  This happens when a rollback
49291*** occurs.  We have to trip all the other cursors, even
49292** cursor from other VMs in different database connections,
49293** so that none of them try to use the data at which they
49294** were pointing and which now may have been changed due
49295** to the rollback.
49296**
49297** Remember that a rollback can delete tables complete and
49298** reorder rootpages.  So it is not sufficient just to save
49299** the state of the cursor.  We have to invalidate the cursor
49300** so that it is never used again.
49301*/
49302static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
49303  int i;
49304  for(i=0; i<db->nDb; i++){
49305    Btree *p = db->aDb[i].pBt;
49306    if( p && sqlite3BtreeIsInTrans(p) ){
49307      sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
49308    }
49309  }
49310}
49311
49312/*
49313** If the Vdbe passed as the first argument opened a statement-transaction,
49314** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
49315** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
49316** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
49317** statement transaction is commtted.
49318**
49319** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
49320** Otherwise SQLITE_OK.
49321*/
49322SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
49323  sqlite3 *const db = p->db;
49324  int rc = SQLITE_OK;
49325
49326  /* If p->iStatement is greater than zero, then this Vdbe opened a
49327  ** statement transaction that should be closed here. The only exception
49328  ** is that an IO error may have occured, causing an emergency rollback.
49329  ** In this case (db->nStatement==0), and there is nothing to do.
49330  */
49331  if( db->nStatement && p->iStatement ){
49332    int i;
49333    const int iSavepoint = p->iStatement-1;
49334
49335    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
49336    assert( db->nStatement>0 );
49337    assert( p->iStatement==(db->nStatement+db->nSavepoint) );
49338
49339    for(i=0; i<db->nDb; i++){
49340      int rc2 = SQLITE_OK;
49341      Btree *pBt = db->aDb[i].pBt;
49342      if( pBt ){
49343        if( eOp==SAVEPOINT_ROLLBACK ){
49344          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
49345        }
49346        if( rc2==SQLITE_OK ){
49347          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
49348        }
49349        if( rc==SQLITE_OK ){
49350          rc = rc2;
49351        }
49352      }
49353    }
49354    db->nStatement--;
49355    p->iStatement = 0;
49356
49357    /* If the statement transaction is being rolled back, also restore the
49358    ** database handles deferred constraint counter to the value it had when
49359    ** the statement transaction was opened.  */
49360    if( eOp==SAVEPOINT_ROLLBACK ){
49361      db->nDeferredCons = p->nStmtDefCons;
49362    }
49363  }
49364  return rc;
49365}
49366
49367/*
49368** If SQLite is compiled to support shared-cache mode and to be threadsafe,
49369** this routine obtains the mutex associated with each BtShared structure
49370** that may be accessed by the VM passed as an argument. In doing so it
49371** sets the BtShared.db member of each of the BtShared structures, ensuring
49372** that the correct busy-handler callback is invoked if required.
49373**
49374** If SQLite is not threadsafe but does support shared-cache mode, then
49375** sqlite3BtreeEnterAll() is invoked to set the BtShared.db variables
49376** of all of BtShared structures accessible via the database handle
49377** associated with the VM. Of course only a subset of these structures
49378** will be accessed by the VM, and we could use Vdbe.btreeMask to figure
49379** that subset out, but there is no advantage to doing so.
49380**
49381** If SQLite is not threadsafe and does not support shared-cache mode, this
49382** function is a no-op.
49383*/
49384#ifndef SQLITE_OMIT_SHARED_CACHE
49385SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p){
49386#if SQLITE_THREADSAFE
49387  sqlite3BtreeMutexArrayEnter(&p->aMutex);
49388#else
49389  sqlite3BtreeEnterAll(p->db);
49390#endif
49391}
49392#endif
49393
49394/*
49395** This function is called when a transaction opened by the database
49396** handle associated with the VM passed as an argument is about to be
49397** committed. If there are outstanding deferred foreign key constraint
49398** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
49399**
49400** If there are outstanding FK violations and this function returns
49401** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
49402** an error message to it. Then return SQLITE_ERROR.
49403*/
49404#ifndef SQLITE_OMIT_FOREIGN_KEY
49405SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
49406  sqlite3 *db = p->db;
49407  if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
49408    p->rc = SQLITE_CONSTRAINT;
49409    p->errorAction = OE_Abort;
49410    sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
49411    return SQLITE_ERROR;
49412  }
49413  return SQLITE_OK;
49414}
49415#endif
49416
49417/*
49418** This routine is called the when a VDBE tries to halt.  If the VDBE
49419** has made changes and is in autocommit mode, then commit those
49420** changes.  If a rollback is needed, then do the rollback.
49421**
49422** This routine is the only way to move the state of a VM from
49423** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
49424** call this on a VM that is in the SQLITE_MAGIC_HALT state.
49425**
49426** Return an error code.  If the commit could not complete because of
49427** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
49428** means the close did not happen and needs to be repeated.
49429*/
49430SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
49431  int rc;                         /* Used to store transient return codes */
49432  sqlite3 *db = p->db;
49433
49434  /* This function contains the logic that determines if a statement or
49435  ** transaction will be committed or rolled back as a result of the
49436  ** execution of this virtual machine.
49437  **
49438  ** If any of the following errors occur:
49439  **
49440  **     SQLITE_NOMEM
49441  **     SQLITE_IOERR
49442  **     SQLITE_FULL
49443  **     SQLITE_INTERRUPT
49444  **
49445  ** Then the internal cache might have been left in an inconsistent
49446  ** state.  We need to rollback the statement transaction, if there is
49447  ** one, or the complete transaction if there is no statement transaction.
49448  */
49449
49450  if( p->db->mallocFailed ){
49451    p->rc = SQLITE_NOMEM;
49452  }
49453  closeAllCursors(p);
49454  if( p->magic!=VDBE_MAGIC_RUN ){
49455    return SQLITE_OK;
49456  }
49457  checkActiveVdbeCnt(db);
49458
49459  /* No commit or rollback needed if the program never started */
49460  if( p->pc>=0 ){
49461    int mrc;   /* Primary error code from p->rc */
49462    int eStatementOp = 0;
49463    int isSpecialError;            /* Set to true if a 'special' error */
49464
49465    /* Lock all btrees used by the statement */
49466    sqlite3VdbeMutexArrayEnter(p);
49467
49468    /* Check for one of the special errors */
49469    mrc = p->rc & 0xff;
49470    assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
49471    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
49472                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
49473    if( isSpecialError ){
49474      /* If the query was read-only, we need do no rollback at all. Otherwise,
49475      ** proceed with the special handling.
49476      */
49477      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
49478        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
49479          eStatementOp = SAVEPOINT_ROLLBACK;
49480        }else{
49481          /* We are forced to roll back the active transaction. Before doing
49482          ** so, abort any other statements this handle currently has active.
49483          */
49484          invalidateCursorsOnModifiedBtrees(db);
49485          sqlite3RollbackAll(db);
49486          sqlite3CloseSavepoints(db);
49487          db->autoCommit = 1;
49488        }
49489      }
49490    }
49491
49492    /* Check for immediate foreign key violations. */
49493    if( p->rc==SQLITE_OK ){
49494      sqlite3VdbeCheckFk(p, 0);
49495    }
49496
49497    /* If the auto-commit flag is set and this is the only active writer
49498    ** VM, then we do either a commit or rollback of the current transaction.
49499    **
49500    ** Note: This block also runs if one of the special errors handled
49501    ** above has occurred.
49502    */
49503    if( !sqlite3VtabInSync(db)
49504     && db->autoCommit
49505     && db->writeVdbeCnt==(p->readOnly==0)
49506    ){
49507      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
49508        if( sqlite3VdbeCheckFk(p, 1) ){
49509          sqlite3BtreeMutexArrayLeave(&p->aMutex);
49510          return SQLITE_ERROR;
49511        }
49512        /* The auto-commit flag is true, the vdbe program was successful
49513        ** or hit an 'OR FAIL' constraint and there are no deferred foreign
49514        ** key constraints to hold up the transaction. This means a commit
49515        ** is required.  */
49516        rc = vdbeCommit(db, p);
49517        if( rc==SQLITE_BUSY ){
49518          sqlite3BtreeMutexArrayLeave(&p->aMutex);
49519          return SQLITE_BUSY;
49520        }else if( rc!=SQLITE_OK ){
49521          p->rc = rc;
49522          sqlite3RollbackAll(db);
49523        }else{
49524          db->nDeferredCons = 0;
49525          sqlite3CommitInternalChanges(db);
49526        }
49527      }else{
49528        sqlite3RollbackAll(db);
49529      }
49530      db->nStatement = 0;
49531    }else if( eStatementOp==0 ){
49532      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
49533        eStatementOp = SAVEPOINT_RELEASE;
49534      }else if( p->errorAction==OE_Abort ){
49535        eStatementOp = SAVEPOINT_ROLLBACK;
49536      }else{
49537        invalidateCursorsOnModifiedBtrees(db);
49538        sqlite3RollbackAll(db);
49539        sqlite3CloseSavepoints(db);
49540        db->autoCommit = 1;
49541      }
49542    }
49543
49544    /* If eStatementOp is non-zero, then a statement transaction needs to
49545    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
49546    ** do so. If this operation returns an error, and the current statement
49547    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then set the error
49548    ** code to the new value.
49549    */
49550    if( eStatementOp ){
49551      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
49552      if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
49553        p->rc = rc;
49554        sqlite3DbFree(db, p->zErrMsg);
49555        p->zErrMsg = 0;
49556      }
49557    }
49558
49559    /* If this was an INSERT, UPDATE or DELETE and no statement transaction
49560    ** has been rolled back, update the database connection change-counter.
49561    */
49562    if( p->changeCntOn ){
49563      if( eStatementOp!=SAVEPOINT_ROLLBACK ){
49564        sqlite3VdbeSetChanges(db, p->nChange);
49565      }else{
49566        sqlite3VdbeSetChanges(db, 0);
49567      }
49568      p->nChange = 0;
49569    }
49570
49571    /* Rollback or commit any schema changes that occurred. */
49572    if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
49573      sqlite3ResetInternalSchema(db, 0);
49574      db->flags = (db->flags | SQLITE_InternChanges);
49575    }
49576
49577    /* Release the locks */
49578    sqlite3BtreeMutexArrayLeave(&p->aMutex);
49579  }
49580
49581  /* We have successfully halted and closed the VM.  Record this fact. */
49582  if( p->pc>=0 ){
49583    db->activeVdbeCnt--;
49584    if( !p->readOnly ){
49585      db->writeVdbeCnt--;
49586    }
49587    assert( db->activeVdbeCnt>=db->writeVdbeCnt );
49588  }
49589  p->magic = VDBE_MAGIC_HALT;
49590  checkActiveVdbeCnt(db);
49591  if( p->db->mallocFailed ){
49592    p->rc = SQLITE_NOMEM;
49593  }
49594
49595  /* If the auto-commit flag is set to true, then any locks that were held
49596  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
49597  ** to invoke any required unlock-notify callbacks.
49598  */
49599  if( db->autoCommit ){
49600    sqlite3ConnectionUnlocked(db);
49601  }
49602
49603  assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
49604  return SQLITE_OK;
49605}
49606
49607
49608/*
49609** Each VDBE holds the result of the most recent sqlite3_step() call
49610** in p->rc.  This routine sets that result back to SQLITE_OK.
49611*/
49612SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
49613  p->rc = SQLITE_OK;
49614}
49615
49616/*
49617** Clean up a VDBE after execution but do not delete the VDBE just yet.
49618** Write any error messages into *pzErrMsg.  Return the result code.
49619**
49620** After this routine is run, the VDBE should be ready to be executed
49621** again.
49622**
49623** To look at it another way, this routine resets the state of the
49624** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
49625** VDBE_MAGIC_INIT.
49626*/
49627SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
49628  sqlite3 *db;
49629  db = p->db;
49630
49631  /* If the VM did not run to completion or if it encountered an
49632  ** error, then it might not have been halted properly.  So halt
49633  ** it now.
49634  */
49635  sqlite3VdbeHalt(p);
49636
49637  /* If the VDBE has be run even partially, then transfer the error code
49638  ** and error message from the VDBE into the main database structure.  But
49639  ** if the VDBE has just been set to run but has not actually executed any
49640  ** instructions yet, leave the main database error information unchanged.
49641  */
49642  if( p->pc>=0 ){
49643    if( p->zErrMsg ){
49644      sqlite3BeginBenignMalloc();
49645      sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
49646      sqlite3EndBenignMalloc();
49647      db->errCode = p->rc;
49648      sqlite3DbFree(db, p->zErrMsg);
49649      p->zErrMsg = 0;
49650    }else if( p->rc ){
49651      sqlite3Error(db, p->rc, 0);
49652    }else{
49653      sqlite3Error(db, SQLITE_OK, 0);
49654    }
49655    if( p->runOnlyOnce ) p->expired = 1;
49656  }else if( p->rc && p->expired ){
49657    /* The expired flag was set on the VDBE before the first call
49658    ** to sqlite3_step(). For consistency (since sqlite3_step() was
49659    ** called), set the database error in this case as well.
49660    */
49661    sqlite3Error(db, p->rc, 0);
49662    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
49663    sqlite3DbFree(db, p->zErrMsg);
49664    p->zErrMsg = 0;
49665  }
49666
49667  /* Reclaim all memory used by the VDBE
49668  */
49669  Cleanup(p);
49670
49671  /* Save profiling information from this VDBE run.
49672  */
49673#ifdef VDBE_PROFILE
49674  {
49675    FILE *out = fopen("vdbe_profile.out", "a");
49676    if( out ){
49677      int i;
49678      fprintf(out, "---- ");
49679      for(i=0; i<p->nOp; i++){
49680        fprintf(out, "%02x", p->aOp[i].opcode);
49681      }
49682      fprintf(out, "\n");
49683      for(i=0; i<p->nOp; i++){
49684        fprintf(out, "%6d %10lld %8lld ",
49685           p->aOp[i].cnt,
49686           p->aOp[i].cycles,
49687           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
49688        );
49689        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
49690      }
49691      fclose(out);
49692    }
49693  }
49694#endif
49695  p->magic = VDBE_MAGIC_INIT;
49696  return p->rc & db->errMask;
49697}
49698
49699/*
49700** Clean up and delete a VDBE after execution.  Return an integer which is
49701** the result code.  Write any error message text into *pzErrMsg.
49702*/
49703SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
49704  int rc = SQLITE_OK;
49705  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
49706    rc = sqlite3VdbeReset(p);
49707    assert( (rc & p->db->errMask)==rc );
49708  }
49709  sqlite3VdbeDelete(p);
49710  return rc;
49711}
49712
49713/*
49714** Call the destructor for each auxdata entry in pVdbeFunc for which
49715** the corresponding bit in mask is clear.  Auxdata entries beyond 31
49716** are always destroyed.  To destroy all auxdata entries, call this
49717** routine with mask==0.
49718*/
49719SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
49720  int i;
49721  for(i=0; i<pVdbeFunc->nAux; i++){
49722    struct AuxData *pAux = &pVdbeFunc->apAux[i];
49723    if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
49724      if( pAux->xDelete ){
49725        pAux->xDelete(pAux->pAux);
49726      }
49727      pAux->pAux = 0;
49728    }
49729  }
49730}
49731
49732/*
49733** Delete an entire VDBE.
49734*/
49735SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
49736  sqlite3 *db;
49737
49738  if( NEVER(p==0) ) return;
49739  db = p->db;
49740  if( p->pPrev ){
49741    p->pPrev->pNext = p->pNext;
49742  }else{
49743    assert( db->pVdbe==p );
49744    db->pVdbe = p->pNext;
49745  }
49746  if( p->pNext ){
49747    p->pNext->pPrev = p->pPrev;
49748  }
49749  releaseMemArray(p->aVar, p->nVar);
49750  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
49751  vdbeFreeOpArray(db, p->aOp, p->nOp);
49752  sqlite3DbFree(db, p->aLabel);
49753  sqlite3DbFree(db, p->aColName);
49754  sqlite3DbFree(db, p->zSql);
49755  p->magic = VDBE_MAGIC_DEAD;
49756  sqlite3DbFree(db, p->pFree);
49757  sqlite3DbFree(db, p);
49758}
49759
49760/*
49761** Make sure the cursor p is ready to read or write the row to which it
49762** was last positioned.  Return an error code if an OOM fault or I/O error
49763** prevents us from positioning the cursor to its correct position.
49764**
49765** If a MoveTo operation is pending on the given cursor, then do that
49766** MoveTo now.  If no move is pending, check to see if the row has been
49767** deleted out from under the cursor and if it has, mark the row as
49768** a NULL row.
49769**
49770** If the cursor is already pointing to the correct row and that row has
49771** not been deleted out from under the cursor, then this routine is a no-op.
49772*/
49773SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
49774  if( p->deferredMoveto ){
49775    int res, rc;
49776#ifdef SQLITE_TEST
49777    extern int sqlite3_search_count;
49778#endif
49779    assert( p->isTable );
49780    rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
49781    if( rc ) return rc;
49782    p->lastRowid = p->movetoTarget;
49783    p->rowidIsValid = ALWAYS(res==0) ?1:0;
49784    if( NEVER(res<0) ){
49785      rc = sqlite3BtreeNext(p->pCursor, &res);
49786      if( rc ) return rc;
49787    }
49788#ifdef SQLITE_TEST
49789    sqlite3_search_count++;
49790#endif
49791    p->deferredMoveto = 0;
49792    p->cacheStatus = CACHE_STALE;
49793  }else if( ALWAYS(p->pCursor) ){
49794    int hasMoved;
49795    int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
49796    if( rc ) return rc;
49797    if( hasMoved ){
49798      p->cacheStatus = CACHE_STALE;
49799      p->nullRow = 1;
49800    }
49801  }
49802  return SQLITE_OK;
49803}
49804
49805/*
49806** The following functions:
49807**
49808** sqlite3VdbeSerialType()
49809** sqlite3VdbeSerialTypeLen()
49810** sqlite3VdbeSerialLen()
49811** sqlite3VdbeSerialPut()
49812** sqlite3VdbeSerialGet()
49813**
49814** encapsulate the code that serializes values for storage in SQLite
49815** data and index records. Each serialized value consists of a
49816** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
49817** integer, stored as a varint.
49818**
49819** In an SQLite index record, the serial type is stored directly before
49820** the blob of data that it corresponds to. In a table record, all serial
49821** types are stored at the start of the record, and the blobs of data at
49822** the end. Hence these functions allow the caller to handle the
49823** serial-type and data blob seperately.
49824**
49825** The following table describes the various storage classes for data:
49826**
49827**   serial type        bytes of data      type
49828**   --------------     ---------------    ---------------
49829**      0                     0            NULL
49830**      1                     1            signed integer
49831**      2                     2            signed integer
49832**      3                     3            signed integer
49833**      4                     4            signed integer
49834**      5                     6            signed integer
49835**      6                     8            signed integer
49836**      7                     8            IEEE float
49837**      8                     0            Integer constant 0
49838**      9                     0            Integer constant 1
49839**     10,11                               reserved for expansion
49840**    N>=12 and even       (N-12)/2        BLOB
49841**    N>=13 and odd        (N-13)/2        text
49842**
49843** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
49844** of SQLite will not understand those serial types.
49845*/
49846
49847/*
49848** Return the serial-type for the value stored in pMem.
49849*/
49850SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
49851  int flags = pMem->flags;
49852  int n;
49853
49854  if( flags&MEM_Null ){
49855    return 0;
49856  }
49857  if( flags&MEM_Int ){
49858    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
49859#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
49860    i64 i = pMem->u.i;
49861    u64 u;
49862    if( file_format>=4 && (i&1)==i ){
49863      return 8+(u32)i;
49864    }
49865    u = i<0 ? -i : i;
49866    if( u<=127 ) return 1;
49867    if( u<=32767 ) return 2;
49868    if( u<=8388607 ) return 3;
49869    if( u<=2147483647 ) return 4;
49870    if( u<=MAX_6BYTE ) return 5;
49871    return 6;
49872  }
49873  if( flags&MEM_Real ){
49874    return 7;
49875  }
49876  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
49877  n = pMem->n;
49878  if( flags & MEM_Zero ){
49879    n += pMem->u.nZero;
49880  }
49881  assert( n>=0 );
49882  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
49883}
49884
49885/*
49886** Return the length of the data corresponding to the supplied serial-type.
49887*/
49888SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
49889  if( serial_type>=12 ){
49890    return (serial_type-12)/2;
49891  }else{
49892    static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
49893    return aSize[serial_type];
49894  }
49895}
49896
49897/*
49898** If we are on an architecture with mixed-endian floating
49899** points (ex: ARM7) then swap the lower 4 bytes with the
49900** upper 4 bytes.  Return the result.
49901**
49902** For most architectures, this is a no-op.
49903**
49904** (later):  It is reported to me that the mixed-endian problem
49905** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
49906** that early versions of GCC stored the two words of a 64-bit
49907** float in the wrong order.  And that error has been propagated
49908** ever since.  The blame is not necessarily with GCC, though.
49909** GCC might have just copying the problem from a prior compiler.
49910** I am also told that newer versions of GCC that follow a different
49911** ABI get the byte order right.
49912**
49913** Developers using SQLite on an ARM7 should compile and run their
49914** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
49915** enabled, some asserts below will ensure that the byte order of
49916** floating point values is correct.
49917**
49918** (2007-08-30)  Frank van Vugt has studied this problem closely
49919** and has send his findings to the SQLite developers.  Frank
49920** writes that some Linux kernels offer floating point hardware
49921** emulation that uses only 32-bit mantissas instead of a full
49922** 48-bits as required by the IEEE standard.  (This is the
49923** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
49924** byte swapping becomes very complicated.  To avoid problems,
49925** the necessary byte swapping is carried out using a 64-bit integer
49926** rather than a 64-bit float.  Frank assures us that the code here
49927** works for him.  We, the developers, have no way to independently
49928** verify this, but Frank seems to know what he is talking about
49929** so we trust him.
49930*/
49931#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
49932static u64 floatSwap(u64 in){
49933  union {
49934    u64 r;
49935    u32 i[2];
49936  } u;
49937  u32 t;
49938
49939  u.r = in;
49940  t = u.i[0];
49941  u.i[0] = u.i[1];
49942  u.i[1] = t;
49943  return u.r;
49944}
49945# define swapMixedEndianFloat(X)  X = floatSwap(X)
49946#else
49947# define swapMixedEndianFloat(X)
49948#endif
49949
49950/*
49951** Write the serialized data blob for the value stored in pMem into
49952** buf. It is assumed that the caller has allocated sufficient space.
49953** Return the number of bytes written.
49954**
49955** nBuf is the amount of space left in buf[].  nBuf must always be
49956** large enough to hold the entire field.  Except, if the field is
49957** a blob with a zero-filled tail, then buf[] might be just the right
49958** size to hold everything except for the zero-filled tail.  If buf[]
49959** is only big enough to hold the non-zero prefix, then only write that
49960** prefix into buf[].  But if buf[] is large enough to hold both the
49961** prefix and the tail then write the prefix and set the tail to all
49962** zeros.
49963**
49964** Return the number of bytes actually written into buf[].  The number
49965** of bytes in the zero-filled tail is included in the return value only
49966** if those bytes were zeroed in buf[].
49967*/
49968SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
49969  u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
49970  u32 len;
49971
49972  /* Integer and Real */
49973  if( serial_type<=7 && serial_type>0 ){
49974    u64 v;
49975    u32 i;
49976    if( serial_type==7 ){
49977      assert( sizeof(v)==sizeof(pMem->r) );
49978      memcpy(&v, &pMem->r, sizeof(v));
49979      swapMixedEndianFloat(v);
49980    }else{
49981      v = pMem->u.i;
49982    }
49983    len = i = sqlite3VdbeSerialTypeLen(serial_type);
49984    assert( len<=(u32)nBuf );
49985    while( i-- ){
49986      buf[i] = (u8)(v&0xFF);
49987      v >>= 8;
49988    }
49989    return len;
49990  }
49991
49992  /* String or blob */
49993  if( serial_type>=12 ){
49994    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
49995             == (int)sqlite3VdbeSerialTypeLen(serial_type) );
49996    assert( pMem->n<=nBuf );
49997    len = pMem->n;
49998    memcpy(buf, pMem->z, len);
49999    if( pMem->flags & MEM_Zero ){
50000      len += pMem->u.nZero;
50001      assert( nBuf>=0 );
50002      if( len > (u32)nBuf ){
50003        len = (u32)nBuf;
50004      }
50005      memset(&buf[pMem->n], 0, len-pMem->n);
50006    }
50007    return len;
50008  }
50009
50010  /* NULL or constants 0 or 1 */
50011  return 0;
50012}
50013
50014/*
50015** Deserialize the data blob pointed to by buf as serial type serial_type
50016** and store the result in pMem.  Return the number of bytes read.
50017*/
50018SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
50019  const unsigned char *buf,     /* Buffer to deserialize from */
50020  u32 serial_type,              /* Serial type to deserialize */
50021  Mem *pMem                     /* Memory cell to write value into */
50022){
50023  switch( serial_type ){
50024    case 10:   /* Reserved for future use */
50025    case 11:   /* Reserved for future use */
50026    case 0: {  /* NULL */
50027      pMem->flags = MEM_Null;
50028      break;
50029    }
50030    case 1: { /* 1-byte signed integer */
50031      pMem->u.i = (signed char)buf[0];
50032      pMem->flags = MEM_Int;
50033      return 1;
50034    }
50035    case 2: { /* 2-byte signed integer */
50036      pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
50037      pMem->flags = MEM_Int;
50038      return 2;
50039    }
50040    case 3: { /* 3-byte signed integer */
50041      pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
50042      pMem->flags = MEM_Int;
50043      return 3;
50044    }
50045    case 4: { /* 4-byte signed integer */
50046      pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
50047      pMem->flags = MEM_Int;
50048      return 4;
50049    }
50050    case 5: { /* 6-byte signed integer */
50051      u64 x = (((signed char)buf[0])<<8) | buf[1];
50052      u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
50053      x = (x<<32) | y;
50054      pMem->u.i = *(i64*)&x;
50055      pMem->flags = MEM_Int;
50056      return 6;
50057    }
50058    case 6:   /* 8-byte signed integer */
50059    case 7: { /* IEEE floating point */
50060      u64 x;
50061      u32 y;
50062#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
50063      /* Verify that integers and floating point values use the same
50064      ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
50065      ** defined that 64-bit floating point values really are mixed
50066      ** endian.
50067      */
50068      static const u64 t1 = ((u64)0x3ff00000)<<32;
50069      static const double r1 = 1.0;
50070      u64 t2 = t1;
50071      swapMixedEndianFloat(t2);
50072      assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
50073#endif
50074
50075      x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
50076      y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
50077      x = (x<<32) | y;
50078      if( serial_type==6 ){
50079        pMem->u.i = *(i64*)&x;
50080        pMem->flags = MEM_Int;
50081      }else{
50082        assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
50083        swapMixedEndianFloat(x);
50084        memcpy(&pMem->r, &x, sizeof(x));
50085        pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
50086      }
50087      return 8;
50088    }
50089    case 8:    /* Integer 0 */
50090    case 9: {  /* Integer 1 */
50091      pMem->u.i = serial_type-8;
50092      pMem->flags = MEM_Int;
50093      return 0;
50094    }
50095    default: {
50096      u32 len = (serial_type-12)/2;
50097      pMem->z = (char *)buf;
50098      pMem->n = len;
50099      pMem->xDel = 0;
50100      if( serial_type&0x01 ){
50101        pMem->flags = MEM_Str | MEM_Ephem;
50102      }else{
50103        pMem->flags = MEM_Blob | MEM_Ephem;
50104      }
50105      return len;
50106    }
50107  }
50108  return 0;
50109}
50110
50111
50112/*
50113** Given the nKey-byte encoding of a record in pKey[], parse the
50114** record into a UnpackedRecord structure.  Return a pointer to
50115** that structure.
50116**
50117** The calling function might provide szSpace bytes of memory
50118** space at pSpace.  This space can be used to hold the returned
50119** VDbeParsedRecord structure if it is large enough.  If it is
50120** not big enough, space is obtained from sqlite3_malloc().
50121**
50122** The returned structure should be closed by a call to
50123** sqlite3VdbeDeleteUnpackedRecord().
50124*/
50125SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
50126  KeyInfo *pKeyInfo,     /* Information about the record format */
50127  int nKey,              /* Size of the binary record */
50128  const void *pKey,      /* The binary record */
50129  char *pSpace,          /* Unaligned space available to hold the object */
50130  int szSpace            /* Size of pSpace[] in bytes */
50131){
50132  const unsigned char *aKey = (const unsigned char *)pKey;
50133  UnpackedRecord *p;  /* The unpacked record that we will return */
50134  int nByte;          /* Memory space needed to hold p, in bytes */
50135  int d;
50136  u32 idx;
50137  u16 u;              /* Unsigned loop counter */
50138  u32 szHdr;
50139  Mem *pMem;
50140  int nOff;           /* Increase pSpace by this much to 8-byte align it */
50141
50142  /*
50143  ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
50144  ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
50145  ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
50146  */
50147  nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
50148  pSpace += nOff;
50149  szSpace -= nOff;
50150  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
50151  if( nByte>szSpace ){
50152    p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
50153    if( p==0 ) return 0;
50154    p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
50155  }else{
50156    p = (UnpackedRecord*)pSpace;
50157    p->flags = UNPACKED_NEED_DESTROY;
50158  }
50159  p->pKeyInfo = pKeyInfo;
50160  p->nField = pKeyInfo->nField + 1;
50161  p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
50162  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
50163  idx = getVarint32(aKey, szHdr);
50164  d = szHdr;
50165  u = 0;
50166  while( idx<szHdr && u<p->nField && d<=nKey ){
50167    u32 serial_type;
50168
50169    idx += getVarint32(&aKey[idx], serial_type);
50170    pMem->enc = pKeyInfo->enc;
50171    pMem->db = pKeyInfo->db;
50172    pMem->flags = 0;
50173    pMem->zMalloc = 0;
50174    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
50175    pMem++;
50176    u++;
50177  }
50178  assert( u<=pKeyInfo->nField + 1 );
50179  p->nField = u;
50180  return (void*)p;
50181}
50182
50183/*
50184** This routine destroys a UnpackedRecord object.
50185*/
50186SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
50187  int i;
50188  Mem *pMem;
50189
50190  assert( p!=0 );
50191  assert( p->flags & UNPACKED_NEED_DESTROY );
50192  for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
50193    /* The unpacked record is always constructed by the
50194    ** sqlite3VdbeUnpackRecord() function above, which makes all
50195    ** strings and blobs static.  And none of the elements are
50196    ** ever transformed, so there is never anything to delete.
50197    */
50198    if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
50199  }
50200  if( p->flags & UNPACKED_NEED_FREE ){
50201    sqlite3DbFree(p->pKeyInfo->db, p);
50202  }
50203}
50204
50205/*
50206** This function compares the two table rows or index records
50207** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
50208** or positive integer if key1 is less than, equal to or
50209** greater than key2.  The {nKey1, pKey1} key must be a blob
50210** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
50211** key must be a parsed key such as obtained from
50212** sqlite3VdbeParseRecord.
50213**
50214** Key1 and Key2 do not have to contain the same number of fields.
50215** The key with fewer fields is usually compares less than the
50216** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
50217** and the common prefixes are equal, then key1 is less than key2.
50218** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
50219** equal, then the keys are considered to be equal and
50220** the parts beyond the common prefix are ignored.
50221**
50222** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
50223** the header of pKey1 is ignored.  It is assumed that pKey1 is
50224** an index key, and thus ends with a rowid value.  The last byte
50225** of the header will therefore be the serial type of the rowid:
50226** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
50227** The serial type of the final rowid will always be a single byte.
50228** By ignoring this last byte of the header, we force the comparison
50229** to ignore the rowid at the end of key1.
50230*/
50231SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
50232  int nKey1, const void *pKey1, /* Left key */
50233  UnpackedRecord *pPKey2        /* Right key */
50234){
50235  int d1;            /* Offset into aKey[] of next data element */
50236  u32 idx1;          /* Offset into aKey[] of next header element */
50237  u32 szHdr1;        /* Number of bytes in header */
50238  int i = 0;
50239  int nField;
50240  int rc = 0;
50241  const unsigned char *aKey1 = (const unsigned char *)pKey1;
50242  KeyInfo *pKeyInfo;
50243  Mem mem1;
50244
50245  pKeyInfo = pPKey2->pKeyInfo;
50246  mem1.enc = pKeyInfo->enc;
50247  mem1.db = pKeyInfo->db;
50248  /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
50249  VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
50250
50251  /* Compilers may complain that mem1.u.i is potentially uninitialized.
50252  ** We could initialize it, as shown here, to silence those complaints.
50253  ** But in fact, mem1.u.i will never actually be used initialized, and doing
50254  ** the unnecessary initialization has a measurable negative performance
50255  ** impact, since this routine is a very high runner.  And so, we choose
50256  ** to ignore the compiler warnings and leave this variable uninitialized.
50257  */
50258  /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
50259
50260  idx1 = getVarint32(aKey1, szHdr1);
50261  d1 = szHdr1;
50262  if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
50263    szHdr1--;
50264  }
50265  nField = pKeyInfo->nField;
50266  while( idx1<szHdr1 && i<pPKey2->nField ){
50267    u32 serial_type1;
50268
50269    /* Read the serial types for the next element in each key. */
50270    idx1 += getVarint32( aKey1+idx1, serial_type1 );
50271    if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
50272
50273    /* Extract the values to be compared.
50274    */
50275    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
50276
50277    /* Do the comparison
50278    */
50279    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
50280                           i<nField ? pKeyInfo->aColl[i] : 0);
50281    if( rc!=0 ){
50282      assert( mem1.zMalloc==0 );  /* See comment below */
50283
50284      /* Invert the result if we are using DESC sort order. */
50285      if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
50286        rc = -rc;
50287      }
50288
50289      /* If the PREFIX_SEARCH flag is set and all fields except the final
50290      ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
50291      ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
50292      ** This is used by the OP_IsUnique opcode.
50293      */
50294      if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
50295        assert( idx1==szHdr1 && rc );
50296        assert( mem1.flags & MEM_Int );
50297        pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
50298        pPKey2->rowid = mem1.u.i;
50299      }
50300
50301      return rc;
50302    }
50303    i++;
50304  }
50305
50306  /* No memory allocation is ever used on mem1.  Prove this using
50307  ** the following assert().  If the assert() fails, it indicates a
50308  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
50309  */
50310  assert( mem1.zMalloc==0 );
50311
50312  /* rc==0 here means that one of the keys ran out of fields and
50313  ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
50314  ** flag is set, then break the tie by treating key2 as larger.
50315  ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
50316  ** are considered to be equal.  Otherwise, the longer key is the
50317  ** larger.  As it happens, the pPKey2 will always be the longer
50318  ** if there is a difference.
50319  */
50320  assert( rc==0 );
50321  if( pPKey2->flags & UNPACKED_INCRKEY ){
50322    rc = -1;
50323  }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
50324    /* Leave rc==0 */
50325  }else if( idx1<szHdr1 ){
50326    rc = 1;
50327  }
50328  return rc;
50329}
50330
50331
50332/*
50333** pCur points at an index entry created using the OP_MakeRecord opcode.
50334** Read the rowid (the last field in the record) and store it in *rowid.
50335** Return SQLITE_OK if everything works, or an error code otherwise.
50336**
50337** pCur might be pointing to text obtained from a corrupt database file.
50338** So the content cannot be trusted.  Do appropriate checks on the content.
50339*/
50340SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
50341  i64 nCellKey = 0;
50342  int rc;
50343  u32 szHdr;        /* Size of the header */
50344  u32 typeRowid;    /* Serial type of the rowid */
50345  u32 lenRowid;     /* Size of the rowid */
50346  Mem m, v;
50347
50348  UNUSED_PARAMETER(db);
50349
50350  /* Get the size of the index entry.  Only indices entries of less
50351  ** than 2GiB are support - anything large must be database corruption.
50352  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
50353  ** this code can safely assume that nCellKey is 32-bits
50354  */
50355  assert( sqlite3BtreeCursorIsValid(pCur) );
50356  rc = sqlite3BtreeKeySize(pCur, &nCellKey);
50357  assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
50358  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
50359
50360  /* Read in the complete content of the index entry */
50361  memset(&m, 0, sizeof(m));
50362  rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
50363  if( rc ){
50364    return rc;
50365  }
50366
50367  /* The index entry must begin with a header size */
50368  (void)getVarint32((u8*)m.z, szHdr);
50369  testcase( szHdr==3 );
50370  testcase( szHdr==m.n );
50371  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
50372    goto idx_rowid_corruption;
50373  }
50374
50375  /* The last field of the index should be an integer - the ROWID.
50376  ** Verify that the last entry really is an integer. */
50377  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
50378  testcase( typeRowid==1 );
50379  testcase( typeRowid==2 );
50380  testcase( typeRowid==3 );
50381  testcase( typeRowid==4 );
50382  testcase( typeRowid==5 );
50383  testcase( typeRowid==6 );
50384  testcase( typeRowid==8 );
50385  testcase( typeRowid==9 );
50386  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
50387    goto idx_rowid_corruption;
50388  }
50389  lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
50390  testcase( (u32)m.n==szHdr+lenRowid );
50391  if( unlikely((u32)m.n<szHdr+lenRowid) ){
50392    goto idx_rowid_corruption;
50393  }
50394
50395  /* Fetch the integer off the end of the index record */
50396  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
50397  *rowid = v.u.i;
50398  sqlite3VdbeMemRelease(&m);
50399  return SQLITE_OK;
50400
50401  /* Jump here if database corruption is detected after m has been
50402  ** allocated.  Free the m object and return SQLITE_CORRUPT. */
50403idx_rowid_corruption:
50404  testcase( m.zMalloc!=0 );
50405  sqlite3VdbeMemRelease(&m);
50406  return SQLITE_CORRUPT_BKPT;
50407}
50408
50409/*
50410** Compare the key of the index entry that cursor pC is pointing to against
50411** the key string in pUnpacked.  Write into *pRes a number
50412** that is negative, zero, or positive if pC is less than, equal to,
50413** or greater than pUnpacked.  Return SQLITE_OK on success.
50414**
50415** pUnpacked is either created without a rowid or is truncated so that it
50416** omits the rowid at the end.  The rowid at the end of the index entry
50417** is ignored as well.  Hence, this routine only compares the prefixes
50418** of the keys prior to the final rowid, not the entire key.
50419*/
50420SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
50421  VdbeCursor *pC,             /* The cursor to compare against */
50422  UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
50423  int *res                    /* Write the comparison result here */
50424){
50425  i64 nCellKey = 0;
50426  int rc;
50427  BtCursor *pCur = pC->pCursor;
50428  Mem m;
50429
50430  assert( sqlite3BtreeCursorIsValid(pCur) );
50431  rc = sqlite3BtreeKeySize(pCur, &nCellKey);
50432  assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
50433  /* nCellKey will always be between 0 and 0xffffffff because of the say
50434  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
50435  if( nCellKey<=0 || nCellKey>0x7fffffff ){
50436    *res = 0;
50437    return SQLITE_CORRUPT_BKPT;
50438  }
50439  memset(&m, 0, sizeof(m));
50440  rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
50441  if( rc ){
50442    return rc;
50443  }
50444  assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
50445  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
50446  sqlite3VdbeMemRelease(&m);
50447  return SQLITE_OK;
50448}
50449
50450/*
50451** This routine sets the value to be returned by subsequent calls to
50452** sqlite3_changes() on the database handle 'db'.
50453*/
50454SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
50455  assert( sqlite3_mutex_held(db->mutex) );
50456  db->nChange = nChange;
50457  db->nTotalChange += nChange;
50458}
50459
50460/*
50461** Set a flag in the vdbe to update the change counter when it is finalised
50462** or reset.
50463*/
50464SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
50465  v->changeCntOn = 1;
50466}
50467
50468/*
50469** Mark every prepared statement associated with a database connection
50470** as expired.
50471**
50472** An expired statement means that recompilation of the statement is
50473** recommend.  Statements expire when things happen that make their
50474** programs obsolete.  Removing user-defined functions or collating
50475** sequences, or changing an authorization function are the types of
50476** things that make prepared statements obsolete.
50477*/
50478SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
50479  Vdbe *p;
50480  for(p = db->pVdbe; p; p=p->pNext){
50481    p->expired = 1;
50482  }
50483}
50484
50485/*
50486** Return the database associated with the Vdbe.
50487*/
50488SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
50489  return v->db;
50490}
50491
50492/*
50493** Return a pointer to an sqlite3_value structure containing the value bound
50494** parameter iVar of VM v. Except, if the value is an SQL NULL, return
50495** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
50496** constants) to the value before returning it.
50497**
50498** The returned value must be freed by the caller using sqlite3ValueFree().
50499*/
50500SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
50501  assert( iVar>0 );
50502  if( v ){
50503    Mem *pMem = &v->aVar[iVar-1];
50504    if( 0==(pMem->flags & MEM_Null) ){
50505      sqlite3_value *pRet = sqlite3ValueNew(v->db);
50506      if( pRet ){
50507        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
50508        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
50509        sqlite3VdbeMemStoreType((Mem *)pRet);
50510      }
50511      return pRet;
50512    }
50513  }
50514  return 0;
50515}
50516
50517/*
50518** Configure SQL variable iVar so that binding a new value to it signals
50519** to sqlite3_reoptimize() that re-preparing the statement may result
50520** in a better query plan.
50521*/
50522SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
50523  assert( iVar>0 );
50524  if( iVar>32 ){
50525    v->expmask = 0xffffffff;
50526  }else{
50527    v->expmask |= ((u32)1 << (iVar-1));
50528  }
50529}
50530
50531/************** End of vdbeaux.c *********************************************/
50532/************** Begin file vdbeapi.c *****************************************/
50533/*
50534** 2004 May 26
50535**
50536** The author disclaims copyright to this source code.  In place of
50537** a legal notice, here is a blessing:
50538**
50539**    May you do good and not evil.
50540**    May you find forgiveness for yourself and forgive others.
50541**    May you share freely, never taking more than you give.
50542**
50543*************************************************************************
50544**
50545** This file contains code use to implement APIs that are part of the
50546** VDBE.
50547*/
50548
50549#ifndef SQLITE_OMIT_DEPRECATED
50550/*
50551** Return TRUE (non-zero) of the statement supplied as an argument needs
50552** to be recompiled.  A statement needs to be recompiled whenever the
50553** execution environment changes in a way that would alter the program
50554** that sqlite3_prepare() generates.  For example, if new functions or
50555** collating sequences are registered or if an authorizer function is
50556** added or changed.
50557*/
50558SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
50559  Vdbe *p = (Vdbe*)pStmt;
50560  return p==0 || p->expired;
50561}
50562#endif
50563
50564/*
50565** Check on a Vdbe to make sure it has not been finalized.  Log
50566** an error and return true if it has been finalized (or is otherwise
50567** invalid).  Return false if it is ok.
50568*/
50569static int vdbeSafety(Vdbe *p){
50570  if( p->db==0 ){
50571    sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
50572    return 1;
50573  }else{
50574    return 0;
50575  }
50576}
50577static int vdbeSafetyNotNull(Vdbe *p){
50578  if( p==0 ){
50579    sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
50580    return 1;
50581  }else{
50582    return vdbeSafety(p);
50583  }
50584}
50585
50586/*
50587** The following routine destroys a virtual machine that is created by
50588** the sqlite3_compile() routine. The integer returned is an SQLITE_
50589** success/failure code that describes the result of executing the virtual
50590** machine.
50591**
50592** This routine sets the error code and string returned by
50593** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
50594*/
50595SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
50596  int rc;
50597  if( pStmt==0 ){
50598    rc = SQLITE_OK;
50599  }else{
50600    Vdbe *v = (Vdbe*)pStmt;
50601    sqlite3 *db = v->db;
50602#if SQLITE_THREADSAFE
50603    sqlite3_mutex *mutex;
50604#endif
50605    if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
50606#if SQLITE_THREADSAFE
50607    mutex = v->db->mutex;
50608#endif
50609    sqlite3_mutex_enter(mutex);
50610    rc = sqlite3VdbeFinalize(v);
50611    rc = sqlite3ApiExit(db, rc);
50612    sqlite3_mutex_leave(mutex);
50613  }
50614  return rc;
50615}
50616
50617/*
50618** Terminate the current execution of an SQL statement and reset it
50619** back to its starting state so that it can be reused. A success code from
50620** the prior execution is returned.
50621**
50622** This routine sets the error code and string returned by
50623** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
50624*/
50625SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
50626  int rc;
50627  if( pStmt==0 ){
50628    rc = SQLITE_OK;
50629  }else{
50630    Vdbe *v = (Vdbe*)pStmt;
50631    sqlite3_mutex_enter(v->db->mutex);
50632    rc = sqlite3VdbeReset(v);
50633    sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
50634    assert( (rc & (v->db->errMask))==rc );
50635    rc = sqlite3ApiExit(v->db, rc);
50636    sqlite3_mutex_leave(v->db->mutex);
50637  }
50638  return rc;
50639}
50640
50641/*
50642** Set all the parameters in the compiled SQL statement to NULL.
50643*/
50644SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
50645  int i;
50646  int rc = SQLITE_OK;
50647  Vdbe *p = (Vdbe*)pStmt;
50648#if SQLITE_THREADSAFE
50649  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
50650#endif
50651  sqlite3_mutex_enter(mutex);
50652  for(i=0; i<p->nVar; i++){
50653    sqlite3VdbeMemRelease(&p->aVar[i]);
50654    p->aVar[i].flags = MEM_Null;
50655  }
50656  if( p->isPrepareV2 && p->expmask ){
50657    p->expired = 1;
50658  }
50659  sqlite3_mutex_leave(mutex);
50660  return rc;
50661}
50662
50663
50664/**************************** sqlite3_value_  *******************************
50665** The following routines extract information from a Mem or sqlite3_value
50666** structure.
50667*/
50668SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
50669  Mem *p = (Mem*)pVal;
50670  if( p->flags & (MEM_Blob|MEM_Str) ){
50671    sqlite3VdbeMemExpandBlob(p);
50672    p->flags &= ~MEM_Str;
50673    p->flags |= MEM_Blob;
50674    return p->z;
50675  }else{
50676    return sqlite3_value_text(pVal);
50677  }
50678}
50679SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
50680  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
50681}
50682SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
50683  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
50684}
50685SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
50686  return sqlite3VdbeRealValue((Mem*)pVal);
50687}
50688SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
50689  return (int)sqlite3VdbeIntValue((Mem*)pVal);
50690}
50691SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
50692  return sqlite3VdbeIntValue((Mem*)pVal);
50693}
50694SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
50695  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
50696}
50697#ifndef SQLITE_OMIT_UTF16
50698SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
50699  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
50700}
50701SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
50702  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
50703}
50704SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
50705  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
50706}
50707#endif /* SQLITE_OMIT_UTF16 */
50708SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
50709  return pVal->type;
50710}
50711
50712/**************************** sqlite3_result_  *******************************
50713** The following routines are used by user-defined functions to specify
50714** the function result.
50715**
50716** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
50717** result as a string or blob but if the string or blob is too large, it
50718** then sets the error code to SQLITE_TOOBIG
50719*/
50720static void setResultStrOrError(
50721  sqlite3_context *pCtx,  /* Function context */
50722  const char *z,          /* String pointer */
50723  int n,                  /* Bytes in string, or negative */
50724  u8 enc,                 /* Encoding of z.  0 for BLOBs */
50725  void (*xDel)(void*)     /* Destructor function */
50726){
50727  if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
50728    sqlite3_result_error_toobig(pCtx);
50729  }
50730}
50731SQLITE_API void sqlite3_result_blob(
50732  sqlite3_context *pCtx,
50733  const void *z,
50734  int n,
50735  void (*xDel)(void *)
50736){
50737  assert( n>=0 );
50738  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50739  setResultStrOrError(pCtx, z, n, 0, xDel);
50740}
50741SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
50742  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50743  sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
50744}
50745SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
50746  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50747  pCtx->isError = SQLITE_ERROR;
50748  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
50749}
50750#ifndef SQLITE_OMIT_UTF16
50751SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
50752  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50753  pCtx->isError = SQLITE_ERROR;
50754  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
50755}
50756#endif
50757SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
50758  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50759  sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
50760}
50761SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
50762  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50763  sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
50764}
50765SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
50766  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50767  sqlite3VdbeMemSetNull(&pCtx->s);
50768}
50769SQLITE_API void sqlite3_result_text(
50770  sqlite3_context *pCtx,
50771  const char *z,
50772  int n,
50773  void (*xDel)(void *)
50774){
50775  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50776  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
50777}
50778#ifndef SQLITE_OMIT_UTF16
50779SQLITE_API void sqlite3_result_text16(
50780  sqlite3_context *pCtx,
50781  const void *z,
50782  int n,
50783  void (*xDel)(void *)
50784){
50785  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50786  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
50787}
50788SQLITE_API void sqlite3_result_text16be(
50789  sqlite3_context *pCtx,
50790  const void *z,
50791  int n,
50792  void (*xDel)(void *)
50793){
50794  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50795  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
50796}
50797SQLITE_API void sqlite3_result_text16le(
50798  sqlite3_context *pCtx,
50799  const void *z,
50800  int n,
50801  void (*xDel)(void *)
50802){
50803  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50804  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
50805}
50806#endif /* SQLITE_OMIT_UTF16 */
50807SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
50808  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50809  sqlite3VdbeMemCopy(&pCtx->s, pValue);
50810}
50811SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
50812  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50813  sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
50814}
50815SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
50816  pCtx->isError = errCode;
50817  if( pCtx->s.flags & MEM_Null ){
50818    sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
50819                         SQLITE_UTF8, SQLITE_STATIC);
50820  }
50821}
50822
50823/* Force an SQLITE_TOOBIG error. */
50824SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
50825  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50826  pCtx->isError = SQLITE_TOOBIG;
50827  sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
50828                       SQLITE_UTF8, SQLITE_STATIC);
50829}
50830
50831/* An SQLITE_NOMEM error. */
50832SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
50833  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50834  sqlite3VdbeMemSetNull(&pCtx->s);
50835  pCtx->isError = SQLITE_NOMEM;
50836  pCtx->s.db->mallocFailed = 1;
50837}
50838
50839/*
50840** Execute the statement pStmt, either until a row of data is ready, the
50841** statement is completely executed or an error occurs.
50842**
50843** This routine implements the bulk of the logic behind the sqlite_step()
50844** API.  The only thing omitted is the automatic recompile if a
50845** schema change has occurred.  That detail is handled by the
50846** outer sqlite3_step() wrapper procedure.
50847*/
50848static int sqlite3Step(Vdbe *p){
50849  sqlite3 *db;
50850  int rc;
50851
50852  assert(p);
50853  if( p->magic!=VDBE_MAGIC_RUN ){
50854    sqlite3_log(SQLITE_MISUSE,
50855          "attempt to step a halted statement: [%s]", p->zSql);
50856    return SQLITE_MISUSE_BKPT;
50857  }
50858
50859  /* Assert that malloc() has not failed */
50860  db = p->db;
50861  if( db->mallocFailed ){
50862    return SQLITE_NOMEM;
50863  }
50864
50865  if( p->pc<=0 && p->expired ){
50866    if( p->rc==SQLITE_OK ){
50867      p->rc = SQLITE_SCHEMA;
50868    }
50869    rc = SQLITE_ERROR;
50870    goto end_of_step;
50871  }
50872  if( p->pc<0 ){
50873    /* If there are no other statements currently running, then
50874    ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
50875    ** from interrupting a statement that has not yet started.
50876    */
50877    if( db->activeVdbeCnt==0 ){
50878      db->u1.isInterrupted = 0;
50879    }
50880
50881    assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
50882
50883#ifndef SQLITE_OMIT_TRACE
50884    if( db->xProfile && !db->init.busy ){
50885      double rNow;
50886      sqlite3OsCurrentTime(db->pVfs, &rNow);
50887      p->startTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
50888    }
50889#endif
50890
50891    db->activeVdbeCnt++;
50892    if( p->readOnly==0 ) db->writeVdbeCnt++;
50893    p->pc = 0;
50894  }
50895#ifndef SQLITE_OMIT_EXPLAIN
50896  if( p->explain ){
50897    rc = sqlite3VdbeList(p);
50898  }else
50899#endif /* SQLITE_OMIT_EXPLAIN */
50900  {
50901    rc = sqlite3VdbeExec(p);
50902  }
50903
50904#ifndef SQLITE_OMIT_TRACE
50905  /* Invoke the profile callback if there is one
50906  */
50907  if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
50908    double rNow;
50909    u64 elapseTime;
50910
50911    sqlite3OsCurrentTime(db->pVfs, &rNow);
50912    elapseTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
50913    elapseTime -= p->startTime;
50914    db->xProfile(db->pProfileArg, p->zSql, elapseTime);
50915  }
50916#endif
50917
50918  db->errCode = rc;
50919  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
50920    p->rc = SQLITE_NOMEM;
50921  }
50922end_of_step:
50923  /* At this point local variable rc holds the value that should be
50924  ** returned if this statement was compiled using the legacy
50925  ** sqlite3_prepare() interface. According to the docs, this can only
50926  ** be one of the values in the first assert() below. Variable p->rc
50927  ** contains the value that would be returned if sqlite3_finalize()
50928  ** were called on statement p.
50929  */
50930  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
50931       || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
50932  );
50933  assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
50934  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
50935    /* If this statement was prepared using sqlite3_prepare_v2(), and an
50936    ** error has occured, then return the error code in p->rc to the
50937    ** caller. Set the error code in the database handle to the same value.
50938    */
50939    rc = db->errCode = p->rc;
50940  }
50941  return (rc&db->errMask);
50942}
50943
50944/*
50945** This is the top-level implementation of sqlite3_step().  Call
50946** sqlite3Step() to do most of the work.  If a schema error occurs,
50947** call sqlite3Reprepare() and try again.
50948*/
50949SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
50950  int rc = SQLITE_OK;      /* Result from sqlite3Step() */
50951  int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
50952  Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
50953  int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
50954  sqlite3 *db;             /* The database connection */
50955
50956  if( vdbeSafetyNotNull(v) ){
50957    return SQLITE_MISUSE_BKPT;
50958  }
50959  db = v->db;
50960  sqlite3_mutex_enter(db->mutex);
50961  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
50962         && cnt++ < 5
50963         && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
50964    sqlite3_reset(pStmt);
50965    v->expired = 0;
50966  }
50967  if( rc2!=SQLITE_OK && v->isPrepareV2 && db->pErr ){
50968    /* This case occurs after failing to recompile an sql statement.
50969    ** The error message from the SQL compiler has already been loaded
50970    ** into the database handle. This block copies the error message
50971    ** from the database handle into the statement and sets the statement
50972    ** program counter to 0 to ensure that when the statement is
50973    ** finalized or reset the parser error message is available via
50974    ** sqlite3_errmsg() and sqlite3_errcode().
50975    */
50976    const char *zErr = (const char *)sqlite3_value_text(db->pErr);
50977    sqlite3DbFree(db, v->zErrMsg);
50978    if( !db->mallocFailed ){
50979      v->zErrMsg = sqlite3DbStrDup(db, zErr);
50980      v->rc = rc2;
50981    } else {
50982      v->zErrMsg = 0;
50983      v->rc = rc = SQLITE_NOMEM;
50984    }
50985  }
50986  rc = sqlite3ApiExit(db, rc);
50987  sqlite3_mutex_leave(db->mutex);
50988  return rc;
50989}
50990
50991/*
50992** Extract the user data from a sqlite3_context structure and return a
50993** pointer to it.
50994*/
50995SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
50996  assert( p && p->pFunc );
50997  return p->pFunc->pUserData;
50998}
50999
51000/*
51001** Extract the user data from a sqlite3_context structure and return a
51002** pointer to it.
51003*/
51004SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
51005  assert( p && p->pFunc );
51006  return p->s.db;
51007}
51008
51009/*
51010** The following is the implementation of an SQL function that always
51011** fails with an error message stating that the function is used in the
51012** wrong context.  The sqlite3_overload_function() API might construct
51013** SQL function that use this routine so that the functions will exist
51014** for name resolution but are actually overloaded by the xFindFunction
51015** method of virtual tables.
51016*/
51017SQLITE_PRIVATE void sqlite3InvalidFunction(
51018  sqlite3_context *context,  /* The function calling context */
51019  int NotUsed,               /* Number of arguments to the function */
51020  sqlite3_value **NotUsed2   /* Value of each argument */
51021){
51022  const char *zName = context->pFunc->zName;
51023  char *zErr;
51024  UNUSED_PARAMETER2(NotUsed, NotUsed2);
51025  zErr = sqlite3_mprintf(
51026      "unable to use function %s in the requested context", zName);
51027  sqlite3_result_error(context, zErr, -1);
51028  sqlite3_free(zErr);
51029}
51030
51031/*
51032** Allocate or return the aggregate context for a user function.  A new
51033** context is allocated on the first call.  Subsequent calls return the
51034** same context that was returned on prior calls.
51035*/
51036SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
51037  Mem *pMem;
51038  assert( p && p->pFunc && p->pFunc->xStep );
51039  assert( sqlite3_mutex_held(p->s.db->mutex) );
51040  pMem = p->pMem;
51041  testcase( nByte<0 );
51042  if( (pMem->flags & MEM_Agg)==0 ){
51043    if( nByte<=0 ){
51044      sqlite3VdbeMemReleaseExternal(pMem);
51045      pMem->flags = MEM_Null;
51046      pMem->z = 0;
51047    }else{
51048      sqlite3VdbeMemGrow(pMem, nByte, 0);
51049      pMem->flags = MEM_Agg;
51050      pMem->u.pDef = p->pFunc;
51051      if( pMem->z ){
51052        memset(pMem->z, 0, nByte);
51053      }
51054    }
51055  }
51056  return (void*)pMem->z;
51057}
51058
51059/*
51060** Return the auxilary data pointer, if any, for the iArg'th argument to
51061** the user-function defined by pCtx.
51062*/
51063SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
51064  VdbeFunc *pVdbeFunc;
51065
51066  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
51067  pVdbeFunc = pCtx->pVdbeFunc;
51068  if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
51069    return 0;
51070  }
51071  return pVdbeFunc->apAux[iArg].pAux;
51072}
51073
51074/*
51075** Set the auxilary data pointer and delete function, for the iArg'th
51076** argument to the user-function defined by pCtx. Any previous value is
51077** deleted by calling the delete function specified when it was set.
51078*/
51079SQLITE_API void sqlite3_set_auxdata(
51080  sqlite3_context *pCtx,
51081  int iArg,
51082  void *pAux,
51083  void (*xDelete)(void*)
51084){
51085  struct AuxData *pAuxData;
51086  VdbeFunc *pVdbeFunc;
51087  if( iArg<0 ) goto failed;
51088
51089  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
51090  pVdbeFunc = pCtx->pVdbeFunc;
51091  if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
51092    int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
51093    int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
51094    pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
51095    if( !pVdbeFunc ){
51096      goto failed;
51097    }
51098    pCtx->pVdbeFunc = pVdbeFunc;
51099    memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
51100    pVdbeFunc->nAux = iArg+1;
51101    pVdbeFunc->pFunc = pCtx->pFunc;
51102  }
51103
51104  pAuxData = &pVdbeFunc->apAux[iArg];
51105  if( pAuxData->pAux && pAuxData->xDelete ){
51106    pAuxData->xDelete(pAuxData->pAux);
51107  }
51108  pAuxData->pAux = pAux;
51109  pAuxData->xDelete = xDelete;
51110  return;
51111
51112failed:
51113  if( xDelete ){
51114    xDelete(pAux);
51115  }
51116}
51117
51118#ifndef SQLITE_OMIT_DEPRECATED
51119/*
51120** Return the number of times the Step function of a aggregate has been
51121** called.
51122**
51123** This function is deprecated.  Do not use it for new code.  It is
51124** provide only to avoid breaking legacy code.  New aggregate function
51125** implementations should keep their own counts within their aggregate
51126** context.
51127*/
51128SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
51129  assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
51130  return p->pMem->n;
51131}
51132#endif
51133
51134/*
51135** Return the number of columns in the result set for the statement pStmt.
51136*/
51137SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
51138  Vdbe *pVm = (Vdbe *)pStmt;
51139  return pVm ? pVm->nResColumn : 0;
51140}
51141
51142/*
51143** Return the number of values available from the current row of the
51144** currently executing statement pStmt.
51145*/
51146SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
51147  Vdbe *pVm = (Vdbe *)pStmt;
51148  if( pVm==0 || pVm->pResultSet==0 ) return 0;
51149  return pVm->nResColumn;
51150}
51151
51152
51153/*
51154** Check to see if column iCol of the given statement is valid.  If
51155** it is, return a pointer to the Mem for the value of that column.
51156** If iCol is not valid, return a pointer to a Mem which has a value
51157** of NULL.
51158*/
51159static Mem *columnMem(sqlite3_stmt *pStmt, int i){
51160  Vdbe *pVm;
51161  int vals;
51162  Mem *pOut;
51163
51164  pVm = (Vdbe *)pStmt;
51165  if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
51166    sqlite3_mutex_enter(pVm->db->mutex);
51167    vals = sqlite3_data_count(pStmt);
51168    pOut = &pVm->pResultSet[i];
51169  }else{
51170    /* If the value passed as the second argument is out of range, return
51171    ** a pointer to the following static Mem object which contains the
51172    ** value SQL NULL. Even though the Mem structure contains an element
51173    ** of type i64, on certain architecture (x86) with certain compiler
51174    ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
51175    ** instead of an 8-byte one. This all works fine, except that when
51176    ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
51177    ** that a Mem structure is located on an 8-byte boundary. To prevent
51178    ** this assert() from failing, when building with SQLITE_DEBUG defined
51179    ** using gcc, force nullMem to be 8-byte aligned using the magical
51180    ** __attribute__((aligned(8))) macro.  */
51181    static const Mem nullMem
51182#if defined(SQLITE_DEBUG) && defined(__GNUC__)
51183      __attribute__((aligned(8)))
51184#endif
51185      = {{0}, (double)0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
51186
51187    if( pVm && ALWAYS(pVm->db) ){
51188      sqlite3_mutex_enter(pVm->db->mutex);
51189      sqlite3Error(pVm->db, SQLITE_RANGE, 0);
51190    }
51191    pOut = (Mem*)&nullMem;
51192  }
51193  return pOut;
51194}
51195
51196/*
51197** This function is called after invoking an sqlite3_value_XXX function on a
51198** column value (i.e. a value returned by evaluating an SQL expression in the
51199** select list of a SELECT statement) that may cause a malloc() failure. If
51200** malloc() has failed, the threads mallocFailed flag is cleared and the result
51201** code of statement pStmt set to SQLITE_NOMEM.
51202**
51203** Specifically, this is called from within:
51204**
51205**     sqlite3_column_int()
51206**     sqlite3_column_int64()
51207**     sqlite3_column_text()
51208**     sqlite3_column_text16()
51209**     sqlite3_column_real()
51210**     sqlite3_column_bytes()
51211**     sqlite3_column_bytes16()
51212**
51213** But not for sqlite3_column_blob(), which never calls malloc().
51214*/
51215static void columnMallocFailure(sqlite3_stmt *pStmt)
51216{
51217  /* If malloc() failed during an encoding conversion within an
51218  ** sqlite3_column_XXX API, then set the return code of the statement to
51219  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
51220  ** and _finalize() will return NOMEM.
51221  */
51222  Vdbe *p = (Vdbe *)pStmt;
51223  if( p ){
51224    p->rc = sqlite3ApiExit(p->db, p->rc);
51225    sqlite3_mutex_leave(p->db->mutex);
51226  }
51227}
51228
51229/**************************** sqlite3_column_  *******************************
51230** The following routines are used to access elements of the current row
51231** in the result set.
51232*/
51233SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
51234  const void *val;
51235  val = sqlite3_value_blob( columnMem(pStmt,i) );
51236  /* Even though there is no encoding conversion, value_blob() might
51237  ** need to call malloc() to expand the result of a zeroblob()
51238  ** expression.
51239  */
51240  columnMallocFailure(pStmt);
51241  return val;
51242}
51243SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
51244  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
51245  columnMallocFailure(pStmt);
51246  return val;
51247}
51248SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
51249  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
51250  columnMallocFailure(pStmt);
51251  return val;
51252}
51253SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
51254  double val = sqlite3_value_double( columnMem(pStmt,i) );
51255  columnMallocFailure(pStmt);
51256  return val;
51257}
51258SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
51259  int val = sqlite3_value_int( columnMem(pStmt,i) );
51260  columnMallocFailure(pStmt);
51261  return val;
51262}
51263SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
51264  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
51265  columnMallocFailure(pStmt);
51266  return val;
51267}
51268SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
51269  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
51270  columnMallocFailure(pStmt);
51271  return val;
51272}
51273SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
51274  Mem *pOut = columnMem(pStmt, i);
51275  if( pOut->flags&MEM_Static ){
51276    pOut->flags &= ~MEM_Static;
51277    pOut->flags |= MEM_Ephem;
51278  }
51279  columnMallocFailure(pStmt);
51280  return (sqlite3_value *)pOut;
51281}
51282#ifndef SQLITE_OMIT_UTF16
51283SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
51284  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
51285  columnMallocFailure(pStmt);
51286  return val;
51287}
51288#endif /* SQLITE_OMIT_UTF16 */
51289SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
51290  int iType = sqlite3_value_type( columnMem(pStmt,i) );
51291  columnMallocFailure(pStmt);
51292  return iType;
51293}
51294
51295/* The following function is experimental and subject to change or
51296** removal */
51297/*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
51298**  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
51299**}
51300*/
51301
51302/*
51303** Convert the N-th element of pStmt->pColName[] into a string using
51304** xFunc() then return that string.  If N is out of range, return 0.
51305**
51306** There are up to 5 names for each column.  useType determines which
51307** name is returned.  Here are the names:
51308**
51309**    0      The column name as it should be displayed for output
51310**    1      The datatype name for the column
51311**    2      The name of the database that the column derives from
51312**    3      The name of the table that the column derives from
51313**    4      The name of the table column that the result column derives from
51314**
51315** If the result is not a simple column reference (if it is an expression
51316** or a constant) then useTypes 2, 3, and 4 return NULL.
51317*/
51318static const void *columnName(
51319  sqlite3_stmt *pStmt,
51320  int N,
51321  const void *(*xFunc)(Mem*),
51322  int useType
51323){
51324  const void *ret = 0;
51325  Vdbe *p = (Vdbe *)pStmt;
51326  int n;
51327  sqlite3 *db = p->db;
51328
51329  assert( db!=0 );
51330  n = sqlite3_column_count(pStmt);
51331  if( N<n && N>=0 ){
51332    N += useType*n;
51333    sqlite3_mutex_enter(db->mutex);
51334    assert( db->mallocFailed==0 );
51335    ret = xFunc(&p->aColName[N]);
51336     /* A malloc may have failed inside of the xFunc() call. If this
51337    ** is the case, clear the mallocFailed flag and return NULL.
51338    */
51339    if( db->mallocFailed ){
51340      db->mallocFailed = 0;
51341      ret = 0;
51342    }
51343    sqlite3_mutex_leave(db->mutex);
51344  }
51345  return ret;
51346}
51347
51348/*
51349** Return the name of the Nth column of the result set returned by SQL
51350** statement pStmt.
51351*/
51352SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
51353  return columnName(
51354      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
51355}
51356#ifndef SQLITE_OMIT_UTF16
51357SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
51358  return columnName(
51359      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
51360}
51361#endif
51362
51363/*
51364** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
51365** not define OMIT_DECLTYPE.
51366*/
51367#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
51368# error "Must not define both SQLITE_OMIT_DECLTYPE \
51369         and SQLITE_ENABLE_COLUMN_METADATA"
51370#endif
51371
51372#ifndef SQLITE_OMIT_DECLTYPE
51373/*
51374** Return the column declaration type (if applicable) of the 'i'th column
51375** of the result set of SQL statement pStmt.
51376*/
51377SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
51378  return columnName(
51379      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
51380}
51381#ifndef SQLITE_OMIT_UTF16
51382SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
51383  return columnName(
51384      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
51385}
51386#endif /* SQLITE_OMIT_UTF16 */
51387#endif /* SQLITE_OMIT_DECLTYPE */
51388
51389#ifdef SQLITE_ENABLE_COLUMN_METADATA
51390/*
51391** Return the name of the database from which a result column derives.
51392** NULL is returned if the result column is an expression or constant or
51393** anything else which is not an unabiguous reference to a database column.
51394*/
51395SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
51396  return columnName(
51397      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
51398}
51399#ifndef SQLITE_OMIT_UTF16
51400SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
51401  return columnName(
51402      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
51403}
51404#endif /* SQLITE_OMIT_UTF16 */
51405
51406/*
51407** Return the name of the table from which a result column derives.
51408** NULL is returned if the result column is an expression or constant or
51409** anything else which is not an unabiguous reference to a database column.
51410*/
51411SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
51412  return columnName(
51413      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
51414}
51415#ifndef SQLITE_OMIT_UTF16
51416SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
51417  return columnName(
51418      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
51419}
51420#endif /* SQLITE_OMIT_UTF16 */
51421
51422/*
51423** Return the name of the table column from which a result column derives.
51424** NULL is returned if the result column is an expression or constant or
51425** anything else which is not an unabiguous reference to a database column.
51426*/
51427SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
51428  return columnName(
51429      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
51430}
51431#ifndef SQLITE_OMIT_UTF16
51432SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
51433  return columnName(
51434      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
51435}
51436#endif /* SQLITE_OMIT_UTF16 */
51437#endif /* SQLITE_ENABLE_COLUMN_METADATA */
51438
51439
51440/******************************* sqlite3_bind_  ***************************
51441**
51442** Routines used to attach values to wildcards in a compiled SQL statement.
51443*/
51444/*
51445** Unbind the value bound to variable i in virtual machine p. This is the
51446** the same as binding a NULL value to the column. If the "i" parameter is
51447** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
51448**
51449** A successful evaluation of this routine acquires the mutex on p.
51450** the mutex is released if any kind of error occurs.
51451**
51452** The error code stored in database p->db is overwritten with the return
51453** value in any case.
51454*/
51455static int vdbeUnbind(Vdbe *p, int i){
51456  Mem *pVar;
51457  if( vdbeSafetyNotNull(p) ){
51458    return SQLITE_MISUSE_BKPT;
51459  }
51460  sqlite3_mutex_enter(p->db->mutex);
51461  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
51462    sqlite3Error(p->db, SQLITE_MISUSE, 0);
51463    sqlite3_mutex_leave(p->db->mutex);
51464    sqlite3_log(SQLITE_MISUSE,
51465        "bind on a busy prepared statement: [%s]", p->zSql);
51466    return SQLITE_MISUSE_BKPT;
51467  }
51468  if( i<1 || i>p->nVar ){
51469    sqlite3Error(p->db, SQLITE_RANGE, 0);
51470    sqlite3_mutex_leave(p->db->mutex);
51471    return SQLITE_RANGE;
51472  }
51473  i--;
51474  pVar = &p->aVar[i];
51475  sqlite3VdbeMemRelease(pVar);
51476  pVar->flags = MEM_Null;
51477  sqlite3Error(p->db, SQLITE_OK, 0);
51478
51479  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
51480  ** binding a new value to this variable invalidates the current query plan.
51481  */
51482  if( p->isPrepareV2 &&
51483     ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
51484  ){
51485    p->expired = 1;
51486  }
51487  return SQLITE_OK;
51488}
51489
51490/*
51491** Bind a text or BLOB value.
51492*/
51493static int bindText(
51494  sqlite3_stmt *pStmt,   /* The statement to bind against */
51495  int i,                 /* Index of the parameter to bind */
51496  const void *zData,     /* Pointer to the data to be bound */
51497  int nData,             /* Number of bytes of data to be bound */
51498  void (*xDel)(void*),   /* Destructor for the data */
51499  u8 encoding            /* Encoding for the data */
51500){
51501  Vdbe *p = (Vdbe *)pStmt;
51502  Mem *pVar;
51503  int rc;
51504
51505  rc = vdbeUnbind(p, i);
51506  if( rc==SQLITE_OK ){
51507    if( zData!=0 ){
51508      pVar = &p->aVar[i-1];
51509      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
51510      if( rc==SQLITE_OK && encoding!=0 ){
51511        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
51512      }
51513      sqlite3Error(p->db, rc, 0);
51514      rc = sqlite3ApiExit(p->db, rc);
51515    }
51516    sqlite3_mutex_leave(p->db->mutex);
51517  }
51518  return rc;
51519}
51520
51521
51522/*
51523** Bind a blob value to an SQL statement variable.
51524*/
51525SQLITE_API int sqlite3_bind_blob(
51526  sqlite3_stmt *pStmt,
51527  int i,
51528  const void *zData,
51529  int nData,
51530  void (*xDel)(void*)
51531){
51532  return bindText(pStmt, i, zData, nData, xDel, 0);
51533}
51534SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
51535  int rc;
51536  Vdbe *p = (Vdbe *)pStmt;
51537  rc = vdbeUnbind(p, i);
51538  if( rc==SQLITE_OK ){
51539    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
51540    sqlite3_mutex_leave(p->db->mutex);
51541  }
51542  return rc;
51543}
51544SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
51545  return sqlite3_bind_int64(p, i, (i64)iValue);
51546}
51547SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
51548  int rc;
51549  Vdbe *p = (Vdbe *)pStmt;
51550  rc = vdbeUnbind(p, i);
51551  if( rc==SQLITE_OK ){
51552    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
51553    sqlite3_mutex_leave(p->db->mutex);
51554  }
51555  return rc;
51556}
51557SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
51558  int rc;
51559  Vdbe *p = (Vdbe*)pStmt;
51560  rc = vdbeUnbind(p, i);
51561  if( rc==SQLITE_OK ){
51562    sqlite3_mutex_leave(p->db->mutex);
51563  }
51564  return rc;
51565}
51566SQLITE_API int sqlite3_bind_text(
51567  sqlite3_stmt *pStmt,
51568  int i,
51569  const char *zData,
51570  int nData,
51571  void (*xDel)(void*)
51572){
51573  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
51574}
51575#ifndef SQLITE_OMIT_UTF16
51576SQLITE_API int sqlite3_bind_text16(
51577  sqlite3_stmt *pStmt,
51578  int i,
51579  const void *zData,
51580  int nData,
51581  void (*xDel)(void*)
51582){
51583  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
51584}
51585#endif /* SQLITE_OMIT_UTF16 */
51586SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
51587  int rc;
51588  switch( pValue->type ){
51589    case SQLITE_INTEGER: {
51590      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
51591      break;
51592    }
51593    case SQLITE_FLOAT: {
51594      rc = sqlite3_bind_double(pStmt, i, pValue->r);
51595      break;
51596    }
51597    case SQLITE_BLOB: {
51598      if( pValue->flags & MEM_Zero ){
51599        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
51600      }else{
51601        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
51602      }
51603      break;
51604    }
51605    case SQLITE_TEXT: {
51606      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
51607                              pValue->enc);
51608      break;
51609    }
51610    default: {
51611      rc = sqlite3_bind_null(pStmt, i);
51612      break;
51613    }
51614  }
51615  return rc;
51616}
51617SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
51618  int rc;
51619  Vdbe *p = (Vdbe *)pStmt;
51620  rc = vdbeUnbind(p, i);
51621  if( rc==SQLITE_OK ){
51622    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
51623    sqlite3_mutex_leave(p->db->mutex);
51624  }
51625  return rc;
51626}
51627
51628/*
51629** Return the number of wildcards that can be potentially bound to.
51630** This routine is added to support DBD::SQLite.
51631*/
51632SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
51633  Vdbe *p = (Vdbe*)pStmt;
51634  return p ? p->nVar : 0;
51635}
51636
51637/*
51638** Create a mapping from variable numbers to variable names
51639** in the Vdbe.azVar[] array, if such a mapping does not already
51640** exist.
51641*/
51642static void createVarMap(Vdbe *p){
51643  if( !p->okVar ){
51644    int j;
51645    Op *pOp;
51646    sqlite3_mutex_enter(p->db->mutex);
51647    /* The race condition here is harmless.  If two threads call this
51648    ** routine on the same Vdbe at the same time, they both might end
51649    ** up initializing the Vdbe.azVar[] array.  That is a little extra
51650    ** work but it results in the same answer.
51651    */
51652    for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
51653      if( pOp->opcode==OP_Variable ){
51654        assert( pOp->p1>0 && pOp->p1<=p->nVar );
51655        p->azVar[pOp->p1-1] = pOp->p4.z;
51656      }
51657    }
51658    p->okVar = 1;
51659    sqlite3_mutex_leave(p->db->mutex);
51660  }
51661}
51662
51663/*
51664** Return the name of a wildcard parameter.  Return NULL if the index
51665** is out of range or if the wildcard is unnamed.
51666**
51667** The result is always UTF-8.
51668*/
51669SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
51670  Vdbe *p = (Vdbe*)pStmt;
51671  if( p==0 || i<1 || i>p->nVar ){
51672    return 0;
51673  }
51674  createVarMap(p);
51675  return p->azVar[i-1];
51676}
51677
51678/*
51679** Given a wildcard parameter name, return the index of the variable
51680** with that name.  If there is no variable with the given name,
51681** return 0.
51682*/
51683SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
51684  int i;
51685  if( p==0 ){
51686    return 0;
51687  }
51688  createVarMap(p);
51689  if( zName ){
51690    for(i=0; i<p->nVar; i++){
51691      const char *z = p->azVar[i];
51692      if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
51693        return i+1;
51694      }
51695    }
51696  }
51697  return 0;
51698}
51699SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
51700  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
51701}
51702
51703/*
51704** Transfer all bindings from the first statement over to the second.
51705*/
51706SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
51707  Vdbe *pFrom = (Vdbe*)pFromStmt;
51708  Vdbe *pTo = (Vdbe*)pToStmt;
51709  int i;
51710  assert( pTo->db==pFrom->db );
51711  assert( pTo->nVar==pFrom->nVar );
51712  sqlite3_mutex_enter(pTo->db->mutex);
51713  for(i=0; i<pFrom->nVar; i++){
51714    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
51715  }
51716  sqlite3_mutex_leave(pTo->db->mutex);
51717  return SQLITE_OK;
51718}
51719
51720#ifndef SQLITE_OMIT_DEPRECATED
51721/*
51722** Deprecated external interface.  Internal/core SQLite code
51723** should call sqlite3TransferBindings.
51724**
51725** Is is misuse to call this routine with statements from different
51726** database connections.  But as this is a deprecated interface, we
51727** will not bother to check for that condition.
51728**
51729** If the two statements contain a different number of bindings, then
51730** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
51731** SQLITE_OK is returned.
51732*/
51733SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
51734  Vdbe *pFrom = (Vdbe*)pFromStmt;
51735  Vdbe *pTo = (Vdbe*)pToStmt;
51736  if( pFrom->nVar!=pTo->nVar ){
51737    return SQLITE_ERROR;
51738  }
51739  if( pTo->isPrepareV2 && pTo->expmask ){
51740    pTo->expired = 1;
51741  }
51742  if( pFrom->isPrepareV2 && pFrom->expmask ){
51743    pFrom->expired = 1;
51744  }
51745  return sqlite3TransferBindings(pFromStmt, pToStmt);
51746}
51747#endif
51748
51749/*
51750** Return the sqlite3* database handle to which the prepared statement given
51751** in the argument belongs.  This is the same database handle that was
51752** the first argument to the sqlite3_prepare() that was used to create
51753** the statement in the first place.
51754*/
51755SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
51756  return pStmt ? ((Vdbe*)pStmt)->db : 0;
51757}
51758
51759/*
51760** Return a pointer to the next prepared statement after pStmt associated
51761** with database connection pDb.  If pStmt is NULL, return the first
51762** prepared statement for the database connection.  Return NULL if there
51763** are no more.
51764*/
51765SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
51766  sqlite3_stmt *pNext;
51767  sqlite3_mutex_enter(pDb->mutex);
51768  if( pStmt==0 ){
51769    pNext = (sqlite3_stmt*)pDb->pVdbe;
51770  }else{
51771    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
51772  }
51773  sqlite3_mutex_leave(pDb->mutex);
51774  return pNext;
51775}
51776
51777/*
51778** Return the value of a status counter for a prepared statement
51779*/
51780SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
51781  Vdbe *pVdbe = (Vdbe*)pStmt;
51782  int v = pVdbe->aCounter[op-1];
51783  if( resetFlag ) pVdbe->aCounter[op-1] = 0;
51784  return v;
51785}
51786
51787/************** End of vdbeapi.c *********************************************/
51788/************** Begin file vdbetrace.c ***************************************/
51789/*
51790** 2009 November 25
51791**
51792** The author disclaims copyright to this source code.  In place of
51793** a legal notice, here is a blessing:
51794**
51795**    May you do good and not evil.
51796**    May you find forgiveness for yourself and forgive others.
51797**    May you share freely, never taking more than you give.
51798**
51799*************************************************************************
51800**
51801** This file contains code used to insert the values of host parameters
51802** (aka "wildcards") into the SQL text output by sqlite3_trace().
51803*/
51804
51805#ifndef SQLITE_OMIT_TRACE
51806
51807/*
51808** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
51809** bytes in this text up to but excluding the first character in
51810** a host parameter.  If the text contains no host parameters, return
51811** the total number of bytes in the text.
51812*/
51813static int findNextHostParameter(const char *zSql, int *pnToken){
51814  int tokenType;
51815  int nTotal = 0;
51816  int n;
51817
51818  *pnToken = 0;
51819  while( zSql[0] ){
51820    n = sqlite3GetToken((u8*)zSql, &tokenType);
51821    assert( n>0 && tokenType!=TK_ILLEGAL );
51822    if( tokenType==TK_VARIABLE ){
51823      *pnToken = n;
51824      break;
51825    }
51826    nTotal += n;
51827    zSql += n;
51828  }
51829  return nTotal;
51830}
51831
51832/*
51833** Return a pointer to a string in memory obtained form sqlite3DbMalloc() which
51834** holds a copy of zRawSql but with host parameters expanded to their
51835** current bindings.
51836**
51837** The calling function is responsible for making sure the memory returned
51838** is eventually freed.
51839**
51840** ALGORITHM:  Scan the input string looking for host parameters in any of
51841** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
51842** string literals, quoted identifier names, and comments.  For text forms,
51843** the host parameter index is found by scanning the perpared
51844** statement for the corresponding OP_Variable opcode.  Once the host
51845** parameter index is known, locate the value in p->aVar[].  Then render
51846** the value as a literal in place of the host parameter name.
51847*/
51848SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
51849  Vdbe *p,                 /* The prepared statement being evaluated */
51850  const char *zRawSql      /* Raw text of the SQL statement */
51851){
51852  sqlite3 *db;             /* The database connection */
51853  int idx = 0;             /* Index of a host parameter */
51854  int nextIndex = 1;       /* Index of next ? host parameter */
51855  int n;                   /* Length of a token prefix */
51856  int nToken;              /* Length of the parameter token */
51857  int i;                   /* Loop counter */
51858  Mem *pVar;               /* Value of a host parameter */
51859  StrAccum out;            /* Accumulate the output here */
51860  char zBase[100];         /* Initial working space */
51861
51862  db = p->db;
51863  sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
51864                      db->aLimit[SQLITE_LIMIT_LENGTH]);
51865  out.db = db;
51866  while( zRawSql[0] ){
51867    n = findNextHostParameter(zRawSql, &nToken);
51868    assert( n>0 );
51869    sqlite3StrAccumAppend(&out, zRawSql, n);
51870    zRawSql += n;
51871    assert( zRawSql[0] || nToken==0 );
51872    if( nToken==0 ) break;
51873    if( zRawSql[0]=='?' ){
51874      if( nToken>1 ){
51875        assert( sqlite3Isdigit(zRawSql[1]) );
51876        sqlite3GetInt32(&zRawSql[1], &idx);
51877      }else{
51878        idx = nextIndex;
51879      }
51880    }else{
51881      assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
51882      testcase( zRawSql[0]==':' );
51883      testcase( zRawSql[0]=='$' );
51884      testcase( zRawSql[0]=='@' );
51885      idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
51886      assert( idx>0 );
51887    }
51888    zRawSql += nToken;
51889    nextIndex = idx + 1;
51890    assert( idx>0 && idx<=p->nVar );
51891    pVar = &p->aVar[idx-1];
51892    if( pVar->flags & MEM_Null ){
51893      sqlite3StrAccumAppend(&out, "NULL", 4);
51894    }else if( pVar->flags & MEM_Int ){
51895      sqlite3XPrintf(&out, "%lld", pVar->u.i);
51896    }else if( pVar->flags & MEM_Real ){
51897      sqlite3XPrintf(&out, "%!.15g", pVar->r);
51898    }else if( pVar->flags & MEM_Str ){
51899#ifndef SQLITE_OMIT_UTF16
51900      u8 enc = ENC(db);
51901      if( enc!=SQLITE_UTF8 ){
51902        Mem utf8;
51903        memset(&utf8, 0, sizeof(utf8));
51904        utf8.db = db;
51905        sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
51906        sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
51907        sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
51908        sqlite3VdbeMemRelease(&utf8);
51909      }else
51910#endif
51911      {
51912        sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
51913      }
51914    }else if( pVar->flags & MEM_Zero ){
51915      sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
51916    }else{
51917      assert( pVar->flags & MEM_Blob );
51918      sqlite3StrAccumAppend(&out, "x'", 2);
51919      for(i=0; i<pVar->n; i++){
51920        sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
51921      }
51922      sqlite3StrAccumAppend(&out, "'", 1);
51923    }
51924  }
51925  return sqlite3StrAccumFinish(&out);
51926}
51927
51928#endif /* #ifndef SQLITE_OMIT_TRACE */
51929
51930/************** End of vdbetrace.c *******************************************/
51931/************** Begin file vdbe.c ********************************************/
51932/*
51933** 2001 September 15
51934**
51935** The author disclaims copyright to this source code.  In place of
51936** a legal notice, here is a blessing:
51937**
51938**    May you do good and not evil.
51939**    May you find forgiveness for yourself and forgive others.
51940**    May you share freely, never taking more than you give.
51941**
51942*************************************************************************
51943** The code in this file implements execution method of the
51944** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
51945** handles housekeeping details such as creating and deleting
51946** VDBE instances.  This file is solely interested in executing
51947** the VDBE program.
51948**
51949** In the external interface, an "sqlite3_stmt*" is an opaque pointer
51950** to a VDBE.
51951**
51952** The SQL parser generates a program which is then executed by
51953** the VDBE to do the work of the SQL statement.  VDBE programs are
51954** similar in form to assembly language.  The program consists of
51955** a linear sequence of operations.  Each operation has an opcode
51956** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4
51957** is a null-terminated string.  Operand P5 is an unsigned character.
51958** Few opcodes use all 5 operands.
51959**
51960** Computation results are stored on a set of registers numbered beginning
51961** with 1 and going up to Vdbe.nMem.  Each register can store
51962** either an integer, a null-terminated string, a floating point
51963** number, or the SQL "NULL" value.  An implicit conversion from one
51964** type to the other occurs as necessary.
51965**
51966** Most of the code in this file is taken up by the sqlite3VdbeExec()
51967** function which does the work of interpreting a VDBE program.
51968** But other routines are also provided to help in building up
51969** a program instruction by instruction.
51970**
51971** Various scripts scan this source file in order to generate HTML
51972** documentation, headers files, or other derived files.  The formatting
51973** of the code in this file is, therefore, important.  See other comments
51974** in this file for details.  If in doubt, do not deviate from existing
51975** commenting and indentation practices when changing or adding code.
51976*/
51977
51978/*
51979** The following global variable is incremented every time a cursor
51980** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
51981** procedures use this information to make sure that indices are
51982** working correctly.  This variable has no function other than to
51983** help verify the correct operation of the library.
51984*/
51985#ifdef SQLITE_TEST
51986SQLITE_API int sqlite3_search_count = 0;
51987#endif
51988
51989/*
51990** When this global variable is positive, it gets decremented once before
51991** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
51992** field of the sqlite3 structure is set in order to simulate and interrupt.
51993**
51994** This facility is used for testing purposes only.  It does not function
51995** in an ordinary build.
51996*/
51997#ifdef SQLITE_TEST
51998SQLITE_API int sqlite3_interrupt_count = 0;
51999#endif
52000
52001/*
52002** The next global variable is incremented each type the OP_Sort opcode
52003** is executed.  The test procedures use this information to make sure that
52004** sorting is occurring or not occurring at appropriate times.   This variable
52005** has no function other than to help verify the correct operation of the
52006** library.
52007*/
52008#ifdef SQLITE_TEST
52009SQLITE_API int sqlite3_sort_count = 0;
52010#endif
52011
52012/*
52013** The next global variable records the size of the largest MEM_Blob
52014** or MEM_Str that has been used by a VDBE opcode.  The test procedures
52015** use this information to make sure that the zero-blob functionality
52016** is working correctly.   This variable has no function other than to
52017** help verify the correct operation of the library.
52018*/
52019#ifdef SQLITE_TEST
52020SQLITE_API int sqlite3_max_blobsize = 0;
52021static void updateMaxBlobsize(Mem *p){
52022  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
52023    sqlite3_max_blobsize = p->n;
52024  }
52025}
52026#endif
52027
52028/*
52029** The next global variable is incremented each type the OP_Found opcode
52030** is executed. This is used to test whether or not the foreign key
52031** operation implemented using OP_FkIsZero is working. This variable
52032** has no function other than to help verify the correct operation of the
52033** library.
52034*/
52035#ifdef SQLITE_TEST
52036SQLITE_API int sqlite3_found_count = 0;
52037#endif
52038
52039/*
52040** Test a register to see if it exceeds the current maximum blob size.
52041** If it does, record the new maximum blob size.
52042*/
52043#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
52044# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
52045#else
52046# define UPDATE_MAX_BLOBSIZE(P)
52047#endif
52048
52049/*
52050** Convert the given register into a string if it isn't one
52051** already. Return non-zero if a malloc() fails.
52052*/
52053#define Stringify(P, enc) \
52054   if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
52055     { goto no_mem; }
52056
52057/*
52058** An ephemeral string value (signified by the MEM_Ephem flag) contains
52059** a pointer to a dynamically allocated string where some other entity
52060** is responsible for deallocating that string.  Because the register
52061** does not control the string, it might be deleted without the register
52062** knowing it.
52063**
52064** This routine converts an ephemeral string into a dynamically allocated
52065** string that the register itself controls.  In other words, it
52066** converts an MEM_Ephem string into an MEM_Dyn string.
52067*/
52068#define Deephemeralize(P) \
52069   if( ((P)->flags&MEM_Ephem)!=0 \
52070       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
52071
52072/*
52073** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
52074** P if required.
52075*/
52076#define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
52077
52078/*
52079** Argument pMem points at a register that will be passed to a
52080** user-defined function or returned to the user as the result of a query.
52081** This routine sets the pMem->type variable used by the sqlite3_value_*()
52082** routines.
52083*/
52084SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
52085  int flags = pMem->flags;
52086  if( flags & MEM_Null ){
52087    pMem->type = SQLITE_NULL;
52088  }
52089  else if( flags & MEM_Int ){
52090    pMem->type = SQLITE_INTEGER;
52091  }
52092  else if( flags & MEM_Real ){
52093    pMem->type = SQLITE_FLOAT;
52094  }
52095  else if( flags & MEM_Str ){
52096    pMem->type = SQLITE_TEXT;
52097  }else{
52098    pMem->type = SQLITE_BLOB;
52099  }
52100}
52101
52102/*
52103** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
52104** if we run out of memory.
52105*/
52106static VdbeCursor *allocateCursor(
52107  Vdbe *p,              /* The virtual machine */
52108  int iCur,             /* Index of the new VdbeCursor */
52109  int nField,           /* Number of fields in the table or index */
52110  int iDb,              /* When database the cursor belongs to, or -1 */
52111  int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
52112){
52113  /* Find the memory cell that will be used to store the blob of memory
52114  ** required for this VdbeCursor structure. It is convenient to use a
52115  ** vdbe memory cell to manage the memory allocation required for a
52116  ** VdbeCursor structure for the following reasons:
52117  **
52118  **   * Sometimes cursor numbers are used for a couple of different
52119  **     purposes in a vdbe program. The different uses might require
52120  **     different sized allocations. Memory cells provide growable
52121  **     allocations.
52122  **
52123  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
52124  **     be freed lazily via the sqlite3_release_memory() API. This
52125  **     minimizes the number of malloc calls made by the system.
52126  **
52127  ** Memory cells for cursors are allocated at the top of the address
52128  ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
52129  ** cursor 1 is managed by memory cell (p->nMem-1), etc.
52130  */
52131  Mem *pMem = &p->aMem[p->nMem-iCur];
52132
52133  int nByte;
52134  VdbeCursor *pCx = 0;
52135  nByte =
52136      ROUND8(sizeof(VdbeCursor)) +
52137      (isBtreeCursor?sqlite3BtreeCursorSize():0) +
52138      2*nField*sizeof(u32);
52139
52140  assert( iCur<p->nCursor );
52141  if( p->apCsr[iCur] ){
52142    sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
52143    p->apCsr[iCur] = 0;
52144  }
52145  if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
52146    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
52147    memset(pCx, 0, sizeof(VdbeCursor));
52148    pCx->iDb = iDb;
52149    pCx->nField = nField;
52150    if( nField ){
52151      pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
52152    }
52153    if( isBtreeCursor ){
52154      pCx->pCursor = (BtCursor*)
52155          &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
52156      sqlite3BtreeCursorZero(pCx->pCursor);
52157    }
52158  }
52159  return pCx;
52160}
52161
52162/*
52163** Try to convert a value into a numeric representation if we can
52164** do so without loss of information.  In other words, if the string
52165** looks like a number, convert it into a number.  If it does not
52166** look like a number, leave it alone.
52167*/
52168static void applyNumericAffinity(Mem *pRec){
52169  if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
52170    int realnum;
52171    sqlite3VdbeMemNulTerminate(pRec);
52172    if( (pRec->flags&MEM_Str)
52173         && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
52174      i64 value;
52175      sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
52176      if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
52177        pRec->u.i = value;
52178        MemSetTypeFlag(pRec, MEM_Int);
52179      }else{
52180        sqlite3VdbeMemRealify(pRec);
52181      }
52182    }
52183  }
52184}
52185
52186/*
52187** Processing is determine by the affinity parameter:
52188**
52189** SQLITE_AFF_INTEGER:
52190** SQLITE_AFF_REAL:
52191** SQLITE_AFF_NUMERIC:
52192**    Try to convert pRec to an integer representation or a
52193**    floating-point representation if an integer representation
52194**    is not possible.  Note that the integer representation is
52195**    always preferred, even if the affinity is REAL, because
52196**    an integer representation is more space efficient on disk.
52197**
52198** SQLITE_AFF_TEXT:
52199**    Convert pRec to a text representation.
52200**
52201** SQLITE_AFF_NONE:
52202**    No-op.  pRec is unchanged.
52203*/
52204static void applyAffinity(
52205  Mem *pRec,          /* The value to apply affinity to */
52206  char affinity,      /* The affinity to be applied */
52207  u8 enc              /* Use this text encoding */
52208){
52209  if( affinity==SQLITE_AFF_TEXT ){
52210    /* Only attempt the conversion to TEXT if there is an integer or real
52211    ** representation (blob and NULL do not get converted) but no string
52212    ** representation.
52213    */
52214    if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
52215      sqlite3VdbeMemStringify(pRec, enc);
52216    }
52217    pRec->flags &= ~(MEM_Real|MEM_Int);
52218  }else if( affinity!=SQLITE_AFF_NONE ){
52219    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
52220             || affinity==SQLITE_AFF_NUMERIC );
52221    applyNumericAffinity(pRec);
52222    if( pRec->flags & MEM_Real ){
52223      sqlite3VdbeIntegerAffinity(pRec);
52224    }
52225  }
52226}
52227
52228/*
52229** Try to convert the type of a function argument or a result column
52230** into a numeric representation.  Use either INTEGER or REAL whichever
52231** is appropriate.  But only do the conversion if it is possible without
52232** loss of information and return the revised type of the argument.
52233**
52234** This is an EXPERIMENTAL api and is subject to change or removal.
52235*/
52236SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
52237  Mem *pMem = (Mem*)pVal;
52238  applyNumericAffinity(pMem);
52239  sqlite3VdbeMemStoreType(pMem);
52240  return pMem->type;
52241}
52242
52243/*
52244** Exported version of applyAffinity(). This one works on sqlite3_value*,
52245** not the internal Mem* type.
52246*/
52247SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
52248  sqlite3_value *pVal,
52249  u8 affinity,
52250  u8 enc
52251){
52252  applyAffinity((Mem *)pVal, affinity, enc);
52253}
52254
52255#ifdef SQLITE_DEBUG
52256/*
52257** Write a nice string representation of the contents of cell pMem
52258** into buffer zBuf, length nBuf.
52259*/
52260SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
52261  char *zCsr = zBuf;
52262  int f = pMem->flags;
52263
52264  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
52265
52266  if( f&MEM_Blob ){
52267    int i;
52268    char c;
52269    if( f & MEM_Dyn ){
52270      c = 'z';
52271      assert( (f & (MEM_Static|MEM_Ephem))==0 );
52272    }else if( f & MEM_Static ){
52273      c = 't';
52274      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
52275    }else if( f & MEM_Ephem ){
52276      c = 'e';
52277      assert( (f & (MEM_Static|MEM_Dyn))==0 );
52278    }else{
52279      c = 's';
52280    }
52281
52282    sqlite3_snprintf(100, zCsr, "%c", c);
52283    zCsr += sqlite3Strlen30(zCsr);
52284    sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
52285    zCsr += sqlite3Strlen30(zCsr);
52286    for(i=0; i<16 && i<pMem->n; i++){
52287      sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
52288      zCsr += sqlite3Strlen30(zCsr);
52289    }
52290    for(i=0; i<16 && i<pMem->n; i++){
52291      char z = pMem->z[i];
52292      if( z<32 || z>126 ) *zCsr++ = '.';
52293      else *zCsr++ = z;
52294    }
52295
52296    sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
52297    zCsr += sqlite3Strlen30(zCsr);
52298    if( f & MEM_Zero ){
52299      sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
52300      zCsr += sqlite3Strlen30(zCsr);
52301    }
52302    *zCsr = '\0';
52303  }else if( f & MEM_Str ){
52304    int j, k;
52305    zBuf[0] = ' ';
52306    if( f & MEM_Dyn ){
52307      zBuf[1] = 'z';
52308      assert( (f & (MEM_Static|MEM_Ephem))==0 );
52309    }else if( f & MEM_Static ){
52310      zBuf[1] = 't';
52311      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
52312    }else if( f & MEM_Ephem ){
52313      zBuf[1] = 'e';
52314      assert( (f & (MEM_Static|MEM_Dyn))==0 );
52315    }else{
52316      zBuf[1] = 's';
52317    }
52318    k = 2;
52319    sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
52320    k += sqlite3Strlen30(&zBuf[k]);
52321    zBuf[k++] = '[';
52322    for(j=0; j<15 && j<pMem->n; j++){
52323      u8 c = pMem->z[j];
52324      if( c>=0x20 && c<0x7f ){
52325        zBuf[k++] = c;
52326      }else{
52327        zBuf[k++] = '.';
52328      }
52329    }
52330    zBuf[k++] = ']';
52331    sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
52332    k += sqlite3Strlen30(&zBuf[k]);
52333    zBuf[k++] = 0;
52334  }
52335}
52336#endif
52337
52338#ifdef SQLITE_DEBUG
52339/*
52340** Print the value of a register for tracing purposes:
52341*/
52342static void memTracePrint(FILE *out, Mem *p){
52343  if( p->flags & MEM_Null ){
52344    fprintf(out, " NULL");
52345  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
52346    fprintf(out, " si:%lld", p->u.i);
52347  }else if( p->flags & MEM_Int ){
52348    fprintf(out, " i:%lld", p->u.i);
52349#ifndef SQLITE_OMIT_FLOATING_POINT
52350  }else if( p->flags & MEM_Real ){
52351    fprintf(out, " r:%g", p->r);
52352#endif
52353  }else if( p->flags & MEM_RowSet ){
52354    fprintf(out, " (rowset)");
52355  }else{
52356    char zBuf[200];
52357    sqlite3VdbeMemPrettyPrint(p, zBuf);
52358    fprintf(out, " ");
52359    fprintf(out, "%s", zBuf);
52360  }
52361}
52362static void registerTrace(FILE *out, int iReg, Mem *p){
52363  fprintf(out, "REG[%d] = ", iReg);
52364  memTracePrint(out, p);
52365  fprintf(out, "\n");
52366}
52367#endif
52368
52369#ifdef SQLITE_DEBUG
52370#  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
52371#else
52372#  define REGISTER_TRACE(R,M)
52373#endif
52374
52375
52376#ifdef VDBE_PROFILE
52377
52378/*
52379** hwtime.h contains inline assembler code for implementing
52380** high-performance timing routines.
52381*/
52382/************** Include hwtime.h in the middle of vdbe.c *********************/
52383/************** Begin file hwtime.h ******************************************/
52384/*
52385** 2008 May 27
52386**
52387** The author disclaims copyright to this source code.  In place of
52388** a legal notice, here is a blessing:
52389**
52390**    May you do good and not evil.
52391**    May you find forgiveness for yourself and forgive others.
52392**    May you share freely, never taking more than you give.
52393**
52394******************************************************************************
52395**
52396** This file contains inline asm code for retrieving "high-performance"
52397** counters for x86 class CPUs.
52398*/
52399#ifndef _HWTIME_H_
52400#define _HWTIME_H_
52401
52402/*
52403** The following routine only works on pentium-class (or newer) processors.
52404** It uses the RDTSC opcode to read the cycle count value out of the
52405** processor and returns that value.  This can be used for high-res
52406** profiling.
52407*/
52408#if (defined(__GNUC__) || defined(_MSC_VER)) && \
52409      (defined(i386) || defined(__i386__) || defined(_M_IX86))
52410
52411  #if defined(__GNUC__)
52412
52413  __inline__ sqlite_uint64 sqlite3Hwtime(void){
52414     unsigned int lo, hi;
52415     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
52416     return (sqlite_uint64)hi << 32 | lo;
52417  }
52418
52419  #elif defined(_MSC_VER)
52420
52421  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
52422     __asm {
52423        rdtsc
52424        ret       ; return value at EDX:EAX
52425     }
52426  }
52427
52428  #endif
52429
52430#elif (defined(__GNUC__) && defined(__x86_64__))
52431
52432  __inline__ sqlite_uint64 sqlite3Hwtime(void){
52433      unsigned long val;
52434      __asm__ __volatile__ ("rdtsc" : "=A" (val));
52435      return val;
52436  }
52437
52438#elif (defined(__GNUC__) && defined(__ppc__))
52439
52440  __inline__ sqlite_uint64 sqlite3Hwtime(void){
52441      unsigned long long retval;
52442      unsigned long junk;
52443      __asm__ __volatile__ ("\n\
52444          1:      mftbu   %1\n\
52445                  mftb    %L0\n\
52446                  mftbu   %0\n\
52447                  cmpw    %0,%1\n\
52448                  bne     1b"
52449                  : "=r" (retval), "=r" (junk));
52450      return retval;
52451  }
52452
52453#else
52454
52455  #error Need implementation of sqlite3Hwtime() for your platform.
52456
52457  /*
52458  ** To compile without implementing sqlite3Hwtime() for your platform,
52459  ** you can remove the above #error and use the following
52460  ** stub function.  You will lose timing support for many
52461  ** of the debugging and testing utilities, but it should at
52462  ** least compile and run.
52463  */
52464SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
52465
52466#endif
52467
52468#endif /* !defined(_HWTIME_H_) */
52469
52470/************** End of hwtime.h **********************************************/
52471/************** Continuing where we left off in vdbe.c ***********************/
52472
52473#endif
52474
52475/*
52476** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
52477** sqlite3_interrupt() routine has been called.  If it has been, then
52478** processing of the VDBE program is interrupted.
52479**
52480** This macro added to every instruction that does a jump in order to
52481** implement a loop.  This test used to be on every single instruction,
52482** but that meant we more testing that we needed.  By only testing the
52483** flag on jump instructions, we get a (small) speed improvement.
52484*/
52485#define CHECK_FOR_INTERRUPT \
52486   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
52487
52488#ifdef SQLITE_DEBUG
52489static int fileExists(sqlite3 *db, const char *zFile){
52490  int res = 0;
52491  int rc = SQLITE_OK;
52492#ifdef SQLITE_TEST
52493  /* If we are currently testing IO errors, then do not call OsAccess() to
52494  ** test for the presence of zFile. This is because any IO error that
52495  ** occurs here will not be reported, causing the test to fail.
52496  */
52497  extern int sqlite3_io_error_pending;
52498  if( sqlite3_io_error_pending<=0 )
52499#endif
52500    rc = sqlite3OsAccess(db->pVfs, zFile, SQLITE_ACCESS_EXISTS, &res);
52501  return (res && rc==SQLITE_OK);
52502}
52503#endif
52504
52505#ifndef NDEBUG
52506/*
52507** This function is only called from within an assert() expression. It
52508** checks that the sqlite3.nTransaction variable is correctly set to
52509** the number of non-transaction savepoints currently in the
52510** linked list starting at sqlite3.pSavepoint.
52511**
52512** Usage:
52513**
52514**     assert( checkSavepointCount(db) );
52515*/
52516static int checkSavepointCount(sqlite3 *db){
52517  int n = 0;
52518  Savepoint *p;
52519  for(p=db->pSavepoint; p; p=p->pNext) n++;
52520  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
52521  return 1;
52522}
52523#endif
52524
52525/*
52526** Execute as much of a VDBE program as we can then return.
52527**
52528** sqlite3VdbeMakeReady() must be called before this routine in order to
52529** close the program with a final OP_Halt and to set up the callbacks
52530** and the error message pointer.
52531**
52532** Whenever a row or result data is available, this routine will either
52533** invoke the result callback (if there is one) or return with
52534** SQLITE_ROW.
52535**
52536** If an attempt is made to open a locked database, then this routine
52537** will either invoke the busy callback (if there is one) or it will
52538** return SQLITE_BUSY.
52539**
52540** If an error occurs, an error message is written to memory obtained
52541** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
52542** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
52543**
52544** If the callback ever returns non-zero, then the program exits
52545** immediately.  There will be no error message but the p->rc field is
52546** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
52547**
52548** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
52549** routine to return SQLITE_ERROR.
52550**
52551** Other fatal errors return SQLITE_ERROR.
52552**
52553** After this routine has finished, sqlite3VdbeFinalize() should be
52554** used to clean up the mess that was left behind.
52555*/
52556SQLITE_PRIVATE int sqlite3VdbeExec(
52557  Vdbe *p                    /* The VDBE */
52558){
52559  int pc;                    /* The program counter */
52560  Op *aOp = p->aOp;          /* Copy of p->aOp */
52561  Op *pOp;                   /* Current operation */
52562  int rc = SQLITE_OK;        /* Value to return */
52563  sqlite3 *db = p->db;       /* The database */
52564  u8 resetSchemaOnFault = 0; /* Reset schema after an error if true */
52565  u8 encoding = ENC(db);     /* The database encoding */
52566#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
52567  int checkProgress;         /* True if progress callbacks are enabled */
52568  int nProgressOps = 0;      /* Opcodes executed since progress callback. */
52569#endif
52570  Mem *aMem = p->aMem;       /* Copy of p->aMem */
52571  Mem *pIn1 = 0;             /* 1st input operand */
52572  Mem *pIn2 = 0;             /* 2nd input operand */
52573  Mem *pIn3 = 0;             /* 3rd input operand */
52574  Mem *pOut = 0;             /* Output operand */
52575  int iCompare = 0;          /* Result of last OP_Compare operation */
52576  int *aPermute = 0;         /* Permutation of columns for OP_Compare */
52577#ifdef VDBE_PROFILE
52578  u64 start;                 /* CPU clock count at start of opcode */
52579  int origPc;                /* Program counter at start of opcode */
52580#endif
52581  /********************************************************************
52582  ** Automatically generated code
52583  **
52584  ** The following union is automatically generated by the
52585  ** vdbe-compress.tcl script.  The purpose of this union is to
52586  ** reduce the amount of stack space required by this function.
52587  ** See comments in the vdbe-compress.tcl script for details.
52588  */
52589  union vdbeExecUnion {
52590    struct OP_Yield_stack_vars {
52591      int pcDest;
52592    } aa;
52593    struct OP_Variable_stack_vars {
52594      int p1;          /* Variable to copy from */
52595      int p2;          /* Register to copy to */
52596      int n;           /* Number of values left to copy */
52597      Mem *pVar;       /* Value being transferred */
52598    } ab;
52599    struct OP_Move_stack_vars {
52600      char *zMalloc;   /* Holding variable for allocated memory */
52601      int n;           /* Number of registers left to copy */
52602      int p1;          /* Register to copy from */
52603      int p2;          /* Register to copy to */
52604    } ac;
52605    struct OP_ResultRow_stack_vars {
52606      Mem *pMem;
52607      int i;
52608    } ad;
52609    struct OP_Concat_stack_vars {
52610      i64 nByte;
52611    } ae;
52612    struct OP_Remainder_stack_vars {
52613      int flags;      /* Combined MEM_* flags from both inputs */
52614      i64 iA;         /* Integer value of left operand */
52615      i64 iB;         /* Integer value of right operand */
52616      double rA;      /* Real value of left operand */
52617      double rB;      /* Real value of right operand */
52618    } af;
52619    struct OP_Function_stack_vars {
52620      int i;
52621      Mem *pArg;
52622      sqlite3_context ctx;
52623      sqlite3_value **apVal;
52624      int n;
52625    } ag;
52626    struct OP_ShiftRight_stack_vars {
52627      i64 a;
52628      i64 b;
52629    } ah;
52630    struct OP_Ge_stack_vars {
52631      int res;            /* Result of the comparison of pIn1 against pIn3 */
52632      char affinity;      /* Affinity to use for comparison */
52633    } ai;
52634    struct OP_Compare_stack_vars {
52635      int n;
52636      int i;
52637      int p1;
52638      int p2;
52639      const KeyInfo *pKeyInfo;
52640      int idx;
52641      CollSeq *pColl;    /* Collating sequence to use on this term */
52642      int bRev;          /* True for DESCENDING sort order */
52643    } aj;
52644    struct OP_Or_stack_vars {
52645      int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
52646      int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
52647    } ak;
52648    struct OP_IfNot_stack_vars {
52649      int c;
52650    } al;
52651    struct OP_Column_stack_vars {
52652      u32 payloadSize;   /* Number of bytes in the record */
52653      i64 payloadSize64; /* Number of bytes in the record */
52654      int p1;            /* P1 value of the opcode */
52655      int p2;            /* column number to retrieve */
52656      VdbeCursor *pC;    /* The VDBE cursor */
52657      char *zRec;        /* Pointer to complete record-data */
52658      BtCursor *pCrsr;   /* The BTree cursor */
52659      u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
52660      u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
52661      int nField;        /* number of fields in the record */
52662      int len;           /* The length of the serialized data for the column */
52663      int i;             /* Loop counter */
52664      char *zData;       /* Part of the record being decoded */
52665      Mem *pDest;        /* Where to write the extracted value */
52666      Mem sMem;          /* For storing the record being decoded */
52667      u8 *zIdx;          /* Index into header */
52668      u8 *zEndHdr;       /* Pointer to first byte after the header */
52669      u32 offset;        /* Offset into the data */
52670      u32 szField;       /* Number of bytes in the content of a field */
52671      int szHdr;         /* Size of the header size field at start of record */
52672      int avail;         /* Number of bytes of available data */
52673      Mem *pReg;         /* PseudoTable input register */
52674    } am;
52675    struct OP_Affinity_stack_vars {
52676      const char *zAffinity;   /* The affinity to be applied */
52677      char cAff;               /* A single character of affinity */
52678    } an;
52679    struct OP_MakeRecord_stack_vars {
52680      u8 *zNewRecord;        /* A buffer to hold the data for the new record */
52681      Mem *pRec;             /* The new record */
52682      u64 nData;             /* Number of bytes of data space */
52683      int nHdr;              /* Number of bytes of header space */
52684      i64 nByte;             /* Data space required for this record */
52685      int nZero;             /* Number of zero bytes at the end of the record */
52686      int nVarint;           /* Number of bytes in a varint */
52687      u32 serial_type;       /* Type field */
52688      Mem *pData0;           /* First field to be combined into the record */
52689      Mem *pLast;            /* Last field of the record */
52690      int nField;            /* Number of fields in the record */
52691      char *zAffinity;       /* The affinity string for the record */
52692      int file_format;       /* File format to use for encoding */
52693      int i;                 /* Space used in zNewRecord[] */
52694      int len;               /* Length of a field */
52695    } ao;
52696    struct OP_Count_stack_vars {
52697      i64 nEntry;
52698      BtCursor *pCrsr;
52699    } ap;
52700    struct OP_Savepoint_stack_vars {
52701      int p1;                         /* Value of P1 operand */
52702      char *zName;                    /* Name of savepoint */
52703      int nName;
52704      Savepoint *pNew;
52705      Savepoint *pSavepoint;
52706      Savepoint *pTmp;
52707      int iSavepoint;
52708      int ii;
52709    } aq;
52710    struct OP_AutoCommit_stack_vars {
52711      int desiredAutoCommit;
52712      int iRollback;
52713      int turnOnAC;
52714    } ar;
52715    struct OP_Transaction_stack_vars {
52716      Btree *pBt;
52717    } as;
52718    struct OP_ReadCookie_stack_vars {
52719      int iMeta;
52720      int iDb;
52721      int iCookie;
52722    } at;
52723    struct OP_SetCookie_stack_vars {
52724      Db *pDb;
52725    } au;
52726    struct OP_VerifyCookie_stack_vars {
52727      int iMeta;
52728      Btree *pBt;
52729    } av;
52730    struct OP_OpenWrite_stack_vars {
52731      int nField;
52732      KeyInfo *pKeyInfo;
52733      int p2;
52734      int iDb;
52735      int wrFlag;
52736      Btree *pX;
52737      VdbeCursor *pCur;
52738      Db *pDb;
52739    } aw;
52740    struct OP_OpenEphemeral_stack_vars {
52741      VdbeCursor *pCx;
52742    } ax;
52743    struct OP_OpenPseudo_stack_vars {
52744      VdbeCursor *pCx;
52745    } ay;
52746    struct OP_SeekGt_stack_vars {
52747      int res;
52748      int oc;
52749      VdbeCursor *pC;
52750      UnpackedRecord r;
52751      int nField;
52752      i64 iKey;      /* The rowid we are to seek to */
52753    } az;
52754    struct OP_Seek_stack_vars {
52755      VdbeCursor *pC;
52756    } ba;
52757    struct OP_Found_stack_vars {
52758      int alreadyExists;
52759      VdbeCursor *pC;
52760      int res;
52761      UnpackedRecord *pIdxKey;
52762      UnpackedRecord r;
52763      char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
52764    } bb;
52765    struct OP_IsUnique_stack_vars {
52766      u16 ii;
52767      VdbeCursor *pCx;
52768      BtCursor *pCrsr;
52769      u16 nField;
52770      Mem *aMx;
52771      UnpackedRecord r;                  /* B-Tree index search key */
52772      i64 R;                             /* Rowid stored in register P3 */
52773    } bc;
52774    struct OP_NotExists_stack_vars {
52775      VdbeCursor *pC;
52776      BtCursor *pCrsr;
52777      int res;
52778      u64 iKey;
52779    } bd;
52780    struct OP_NewRowid_stack_vars {
52781      i64 v;                 /* The new rowid */
52782      VdbeCursor *pC;        /* Cursor of table to get the new rowid */
52783      int res;               /* Result of an sqlite3BtreeLast() */
52784      int cnt;               /* Counter to limit the number of searches */
52785      Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
52786      VdbeFrame *pFrame;     /* Root frame of VDBE */
52787    } be;
52788    struct OP_InsertInt_stack_vars {
52789      Mem *pData;       /* MEM cell holding data for the record to be inserted */
52790      Mem *pKey;        /* MEM cell holding key  for the record */
52791      i64 iKey;         /* The integer ROWID or key for the record to be inserted */
52792      VdbeCursor *pC;   /* Cursor to table into which insert is written */
52793      int nZero;        /* Number of zero-bytes to append */
52794      int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
52795      const char *zDb;  /* database name - used by the update hook */
52796      const char *zTbl; /* Table name - used by the opdate hook */
52797      int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
52798    } bf;
52799    struct OP_Delete_stack_vars {
52800      i64 iKey;
52801      VdbeCursor *pC;
52802    } bg;
52803    struct OP_RowData_stack_vars {
52804      VdbeCursor *pC;
52805      BtCursor *pCrsr;
52806      u32 n;
52807      i64 n64;
52808    } bh;
52809    struct OP_Rowid_stack_vars {
52810      VdbeCursor *pC;
52811      i64 v;
52812      sqlite3_vtab *pVtab;
52813      const sqlite3_module *pModule;
52814    } bi;
52815    struct OP_NullRow_stack_vars {
52816      VdbeCursor *pC;
52817    } bj;
52818    struct OP_Last_stack_vars {
52819      VdbeCursor *pC;
52820      BtCursor *pCrsr;
52821      int res;
52822    } bk;
52823    struct OP_Rewind_stack_vars {
52824      VdbeCursor *pC;
52825      BtCursor *pCrsr;
52826      int res;
52827    } bl;
52828    struct OP_Next_stack_vars {
52829      VdbeCursor *pC;
52830      BtCursor *pCrsr;
52831      int res;
52832    } bm;
52833    struct OP_IdxInsert_stack_vars {
52834      VdbeCursor *pC;
52835      BtCursor *pCrsr;
52836      int nKey;
52837      const char *zKey;
52838    } bn;
52839    struct OP_IdxDelete_stack_vars {
52840      VdbeCursor *pC;
52841      BtCursor *pCrsr;
52842      int res;
52843      UnpackedRecord r;
52844    } bo;
52845    struct OP_IdxRowid_stack_vars {
52846      BtCursor *pCrsr;
52847      VdbeCursor *pC;
52848      i64 rowid;
52849    } bp;
52850    struct OP_IdxGE_stack_vars {
52851      VdbeCursor *pC;
52852      int res;
52853      UnpackedRecord r;
52854    } bq;
52855    struct OP_Destroy_stack_vars {
52856      int iMoved;
52857      int iCnt;
52858      Vdbe *pVdbe;
52859      int iDb;
52860    } br;
52861    struct OP_Clear_stack_vars {
52862      int nChange;
52863    } bs;
52864    struct OP_CreateTable_stack_vars {
52865      int pgno;
52866      int flags;
52867      Db *pDb;
52868    } bt;
52869    struct OP_ParseSchema_stack_vars {
52870      int iDb;
52871      const char *zMaster;
52872      char *zSql;
52873      InitData initData;
52874    } bu;
52875    struct OP_IntegrityCk_stack_vars {
52876      int nRoot;      /* Number of tables to check.  (Number of root pages.) */
52877      int *aRoot;     /* Array of rootpage numbers for tables to be checked */
52878      int j;          /* Loop counter */
52879      int nErr;       /* Number of errors reported */
52880      char *z;        /* Text of the error report */
52881      Mem *pnErr;     /* Register keeping track of errors remaining */
52882    } bv;
52883    struct OP_RowSetRead_stack_vars {
52884      i64 val;
52885    } bw;
52886    struct OP_RowSetTest_stack_vars {
52887      int iSet;
52888      int exists;
52889    } bx;
52890    struct OP_Program_stack_vars {
52891      int nMem;               /* Number of memory registers for sub-program */
52892      int nByte;              /* Bytes of runtime space required for sub-program */
52893      Mem *pRt;               /* Register to allocate runtime space */
52894      Mem *pMem;              /* Used to iterate through memory cells */
52895      Mem *pEnd;              /* Last memory cell in new array */
52896      VdbeFrame *pFrame;      /* New vdbe frame to execute in */
52897      SubProgram *pProgram;   /* Sub-program to execute */
52898      void *t;                /* Token identifying trigger */
52899    } by;
52900    struct OP_Param_stack_vars {
52901      VdbeFrame *pFrame;
52902      Mem *pIn;
52903    } bz;
52904    struct OP_MemMax_stack_vars {
52905      Mem *pIn1;
52906      VdbeFrame *pFrame;
52907    } ca;
52908    struct OP_AggStep_stack_vars {
52909      int n;
52910      int i;
52911      Mem *pMem;
52912      Mem *pRec;
52913      sqlite3_context ctx;
52914      sqlite3_value **apVal;
52915    } cb;
52916    struct OP_AggFinal_stack_vars {
52917      Mem *pMem;
52918    } cc;
52919    struct OP_IncrVacuum_stack_vars {
52920      Btree *pBt;
52921    } cd;
52922    struct OP_VBegin_stack_vars {
52923      VTable *pVTab;
52924    } ce;
52925    struct OP_VOpen_stack_vars {
52926      VdbeCursor *pCur;
52927      sqlite3_vtab_cursor *pVtabCursor;
52928      sqlite3_vtab *pVtab;
52929      sqlite3_module *pModule;
52930    } cf;
52931    struct OP_VFilter_stack_vars {
52932      int nArg;
52933      int iQuery;
52934      const sqlite3_module *pModule;
52935      Mem *pQuery;
52936      Mem *pArgc;
52937      sqlite3_vtab_cursor *pVtabCursor;
52938      sqlite3_vtab *pVtab;
52939      VdbeCursor *pCur;
52940      int res;
52941      int i;
52942      Mem **apArg;
52943    } cg;
52944    struct OP_VColumn_stack_vars {
52945      sqlite3_vtab *pVtab;
52946      const sqlite3_module *pModule;
52947      Mem *pDest;
52948      sqlite3_context sContext;
52949    } ch;
52950    struct OP_VNext_stack_vars {
52951      sqlite3_vtab *pVtab;
52952      const sqlite3_module *pModule;
52953      int res;
52954      VdbeCursor *pCur;
52955    } ci;
52956    struct OP_VRename_stack_vars {
52957      sqlite3_vtab *pVtab;
52958      Mem *pName;
52959    } cj;
52960    struct OP_VUpdate_stack_vars {
52961      sqlite3_vtab *pVtab;
52962      sqlite3_module *pModule;
52963      int nArg;
52964      int i;
52965      sqlite_int64 rowid;
52966      Mem **apArg;
52967      Mem *pX;
52968    } ck;
52969    struct OP_Pagecount_stack_vars {
52970      int p1;
52971      int nPage;
52972      Pager *pPager;
52973    } cl;
52974    struct OP_Trace_stack_vars {
52975      char *zTrace;
52976    } cm;
52977  } u;
52978  /* End automatically generated code
52979  ********************************************************************/
52980
52981  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
52982  sqlite3VdbeMutexArrayEnter(p);
52983  if( p->rc==SQLITE_NOMEM ){
52984    /* This happens if a malloc() inside a call to sqlite3_column_text() or
52985    ** sqlite3_column_text16() failed.  */
52986    goto no_mem;
52987  }
52988  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
52989  p->rc = SQLITE_OK;
52990  assert( p->explain==0 );
52991  p->pResultSet = 0;
52992  db->busyHandler.nBusy = 0;
52993  CHECK_FOR_INTERRUPT;
52994  sqlite3VdbeIOTraceSql(p);
52995#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
52996  checkProgress = db->xProgress!=0;
52997#endif
52998#ifdef SQLITE_DEBUG
52999  sqlite3BeginBenignMalloc();
53000  if( p->pc==0
53001   && ((p->db->flags & SQLITE_VdbeListing) || fileExists(db, "vdbe_explain"))
53002  ){
53003    int i;
53004    printf("VDBE Program Listing:\n");
53005    sqlite3VdbePrintSql(p);
53006    for(i=0; i<p->nOp; i++){
53007      sqlite3VdbePrintOp(stdout, i, &aOp[i]);
53008    }
53009  }
53010  if( fileExists(db, "vdbe_trace") ){
53011    p->trace = stdout;
53012  }
53013  sqlite3EndBenignMalloc();
53014#endif
53015  for(pc=p->pc; rc==SQLITE_OK; pc++){
53016    assert( pc>=0 && pc<p->nOp );
53017    if( db->mallocFailed ) goto no_mem;
53018#ifdef VDBE_PROFILE
53019    origPc = pc;
53020    start = sqlite3Hwtime();
53021#endif
53022    pOp = &aOp[pc];
53023
53024    /* Only allow tracing if SQLITE_DEBUG is defined.
53025    */
53026#ifdef SQLITE_DEBUG
53027    if( p->trace ){
53028      if( pc==0 ){
53029        printf("VDBE Execution Trace:\n");
53030        sqlite3VdbePrintSql(p);
53031      }
53032      sqlite3VdbePrintOp(p->trace, pc, pOp);
53033    }
53034    if( p->trace==0 && pc==0 ){
53035      sqlite3BeginBenignMalloc();
53036      if( fileExists(db, "vdbe_sqltrace") ){
53037        sqlite3VdbePrintSql(p);
53038      }
53039      sqlite3EndBenignMalloc();
53040    }
53041#endif
53042
53043
53044    /* Check to see if we need to simulate an interrupt.  This only happens
53045    ** if we have a special test build.
53046    */
53047#ifdef SQLITE_TEST
53048    if( sqlite3_interrupt_count>0 ){
53049      sqlite3_interrupt_count--;
53050      if( sqlite3_interrupt_count==0 ){
53051        sqlite3_interrupt(db);
53052      }
53053    }
53054#endif
53055
53056#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
53057    /* Call the progress callback if it is configured and the required number
53058    ** of VDBE ops have been executed (either since this invocation of
53059    ** sqlite3VdbeExec() or since last time the progress callback was called).
53060    ** If the progress callback returns non-zero, exit the virtual machine with
53061    ** a return code SQLITE_ABORT.
53062    */
53063    if( checkProgress ){
53064      if( db->nProgressOps==nProgressOps ){
53065        int prc;
53066        prc = db->xProgress(db->pProgressArg);
53067        if( prc!=0 ){
53068          rc = SQLITE_INTERRUPT;
53069          goto vdbe_error_halt;
53070        }
53071        nProgressOps = 0;
53072      }
53073      nProgressOps++;
53074    }
53075#endif
53076
53077    /* On any opcode with the "out2-prerelase" tag, free any
53078    ** external allocations out of mem[p2] and set mem[p2] to be
53079    ** an undefined integer.  Opcodes will either fill in the integer
53080    ** value or convert mem[p2] to a different type.
53081    */
53082    assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
53083    if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
53084      assert( pOp->p2>0 );
53085      assert( pOp->p2<=p->nMem );
53086      pOut = &aMem[pOp->p2];
53087      sqlite3VdbeMemReleaseExternal(pOut);
53088      pOut->flags = MEM_Int;
53089    }
53090
53091    /* Sanity checking on other operands */
53092#ifdef SQLITE_DEBUG
53093    if( (pOp->opflags & OPFLG_IN1)!=0 ){
53094      assert( pOp->p1>0 );
53095      assert( pOp->p1<=p->nMem );
53096      REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
53097    }
53098    if( (pOp->opflags & OPFLG_IN2)!=0 ){
53099      assert( pOp->p2>0 );
53100      assert( pOp->p2<=p->nMem );
53101      REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
53102    }
53103    if( (pOp->opflags & OPFLG_IN3)!=0 ){
53104      assert( pOp->p3>0 );
53105      assert( pOp->p3<=p->nMem );
53106      REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
53107    }
53108    if( (pOp->opflags & OPFLG_OUT2)!=0 ){
53109      assert( pOp->p2>0 );
53110      assert( pOp->p2<=p->nMem );
53111    }
53112    if( (pOp->opflags & OPFLG_OUT3)!=0 ){
53113      assert( pOp->p3>0 );
53114      assert( pOp->p3<=p->nMem );
53115    }
53116#endif
53117
53118    switch( pOp->opcode ){
53119
53120/*****************************************************************************
53121** What follows is a massive switch statement where each case implements a
53122** separate instruction in the virtual machine.  If we follow the usual
53123** indentation conventions, each case should be indented by 6 spaces.  But
53124** that is a lot of wasted space on the left margin.  So the code within
53125** the switch statement will break with convention and be flush-left. Another
53126** big comment (similar to this one) will mark the point in the code where
53127** we transition back to normal indentation.
53128**
53129** The formatting of each case is important.  The makefile for SQLite
53130** generates two C files "opcodes.h" and "opcodes.c" by scanning this
53131** file looking for lines that begin with "case OP_".  The opcodes.h files
53132** will be filled with #defines that give unique integer values to each
53133** opcode and the opcodes.c file is filled with an array of strings where
53134** each string is the symbolic name for the corresponding opcode.  If the
53135** case statement is followed by a comment of the form "/# same as ... #/"
53136** that comment is used to determine the particular value of the opcode.
53137**
53138** Other keywords in the comment that follows each case are used to
53139** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
53140** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
53141** the mkopcodeh.awk script for additional information.
53142**
53143** Documentation about VDBE opcodes is generated by scanning this file
53144** for lines of that contain "Opcode:".  That line and all subsequent
53145** comment lines are used in the generation of the opcode.html documentation
53146** file.
53147**
53148** SUMMARY:
53149**
53150**     Formatting is important to scripts that scan this file.
53151**     Do not deviate from the formatting style currently in use.
53152**
53153*****************************************************************************/
53154
53155/* Opcode:  Goto * P2 * * *
53156**
53157** An unconditional jump to address P2.
53158** The next instruction executed will be
53159** the one at index P2 from the beginning of
53160** the program.
53161*/
53162case OP_Goto: {             /* jump */
53163  CHECK_FOR_INTERRUPT;
53164  pc = pOp->p2 - 1;
53165  break;
53166}
53167
53168/* Opcode:  Gosub P1 P2 * * *
53169**
53170** Write the current address onto register P1
53171** and then jump to address P2.
53172*/
53173case OP_Gosub: {            /* jump, in1 */
53174  pIn1 = &aMem[pOp->p1];
53175  assert( (pIn1->flags & MEM_Dyn)==0 );
53176  pIn1->flags = MEM_Int;
53177  pIn1->u.i = pc;
53178  REGISTER_TRACE(pOp->p1, pIn1);
53179  pc = pOp->p2 - 1;
53180  break;
53181}
53182
53183/* Opcode:  Return P1 * * * *
53184**
53185** Jump to the next instruction after the address in register P1.
53186*/
53187case OP_Return: {           /* in1 */
53188  pIn1 = &aMem[pOp->p1];
53189  assert( pIn1->flags & MEM_Int );
53190  pc = (int)pIn1->u.i;
53191  break;
53192}
53193
53194/* Opcode:  Yield P1 * * * *
53195**
53196** Swap the program counter with the value in register P1.
53197*/
53198case OP_Yield: {            /* in1 */
53199#if 0  /* local variables moved into u.aa */
53200  int pcDest;
53201#endif /* local variables moved into u.aa */
53202  pIn1 = &aMem[pOp->p1];
53203  assert( (pIn1->flags & MEM_Dyn)==0 );
53204  pIn1->flags = MEM_Int;
53205  u.aa.pcDest = (int)pIn1->u.i;
53206  pIn1->u.i = pc;
53207  REGISTER_TRACE(pOp->p1, pIn1);
53208  pc = u.aa.pcDest;
53209  break;
53210}
53211
53212/* Opcode:  HaltIfNull  P1 P2 P3 P4 *
53213**
53214** Check the value in register P3.  If is is NULL then Halt using
53215** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
53216** value in register P3 is not NULL, then this routine is a no-op.
53217*/
53218case OP_HaltIfNull: {      /* in3 */
53219  pIn3 = &aMem[pOp->p3];
53220  if( (pIn3->flags & MEM_Null)==0 ) break;
53221  /* Fall through into OP_Halt */
53222}
53223
53224/* Opcode:  Halt P1 P2 * P4 *
53225**
53226** Exit immediately.  All open cursors, etc are closed
53227** automatically.
53228**
53229** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
53230** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
53231** For errors, it can be some other value.  If P1!=0 then P2 will determine
53232** whether or not to rollback the current transaction.  Do not rollback
53233** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
53234** then back out all changes that have occurred during this execution of the
53235** VDBE, but do not rollback the transaction.
53236**
53237** If P4 is not null then it is an error message string.
53238**
53239** There is an implied "Halt 0 0 0" instruction inserted at the very end of
53240** every program.  So a jump past the last instruction of the program
53241** is the same as executing Halt.
53242*/
53243case OP_Halt: {
53244  if( pOp->p1==SQLITE_OK && p->pFrame ){
53245    /* Halt the sub-program. Return control to the parent frame. */
53246    VdbeFrame *pFrame = p->pFrame;
53247    p->pFrame = pFrame->pParent;
53248    p->nFrame--;
53249    sqlite3VdbeSetChanges(db, p->nChange);
53250    pc = sqlite3VdbeFrameRestore(pFrame);
53251    if( pOp->p2==OE_Ignore ){
53252      /* Instruction pc is the OP_Program that invoked the sub-program
53253      ** currently being halted. If the p2 instruction of this OP_Halt
53254      ** instruction is set to OE_Ignore, then the sub-program is throwing
53255      ** an IGNORE exception. In this case jump to the address specified
53256      ** as the p2 of the calling OP_Program.  */
53257      pc = p->aOp[pc].p2-1;
53258    }
53259    aOp = p->aOp;
53260    aMem = p->aMem;
53261    break;
53262  }
53263
53264  p->rc = pOp->p1;
53265  p->errorAction = (u8)pOp->p2;
53266  p->pc = pc;
53267  if( pOp->p4.z ){
53268    assert( p->rc!=SQLITE_OK );
53269    sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
53270    testcase( sqlite3GlobalConfig.xLog!=0 );
53271    sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
53272  }else if( p->rc ){
53273    testcase( sqlite3GlobalConfig.xLog!=0 );
53274    sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
53275  }
53276  rc = sqlite3VdbeHalt(p);
53277  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
53278  if( rc==SQLITE_BUSY ){
53279    p->rc = rc = SQLITE_BUSY;
53280  }else{
53281    assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
53282    assert( rc==SQLITE_OK || db->nDeferredCons>0 );
53283    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
53284  }
53285  goto vdbe_return;
53286}
53287
53288/* Opcode: Integer P1 P2 * * *
53289**
53290** The 32-bit integer value P1 is written into register P2.
53291*/
53292case OP_Integer: {         /* out2-prerelease */
53293  pOut->u.i = pOp->p1;
53294  break;
53295}
53296
53297/* Opcode: Int64 * P2 * P4 *
53298**
53299** P4 is a pointer to a 64-bit integer value.
53300** Write that value into register P2.
53301*/
53302case OP_Int64: {           /* out2-prerelease */
53303  assert( pOp->p4.pI64!=0 );
53304  pOut->u.i = *pOp->p4.pI64;
53305  break;
53306}
53307
53308/* Opcode: Real * P2 * P4 *
53309**
53310** P4 is a pointer to a 64-bit floating point value.
53311** Write that value into register P2.
53312*/
53313case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
53314  pOut->flags = MEM_Real;
53315  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
53316  pOut->r = *pOp->p4.pReal;
53317  break;
53318}
53319
53320/* Opcode: String8 * P2 * P4 *
53321**
53322** P4 points to a nul terminated UTF-8 string. This opcode is transformed
53323** into an OP_String before it is executed for the first time.
53324*/
53325case OP_String8: {         /* same as TK_STRING, out2-prerelease */
53326  assert( pOp->p4.z!=0 );
53327  pOp->opcode = OP_String;
53328  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
53329
53330#ifndef SQLITE_OMIT_UTF16
53331  if( encoding!=SQLITE_UTF8 ){
53332    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
53333    if( rc==SQLITE_TOOBIG ) goto too_big;
53334    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
53335    assert( pOut->zMalloc==pOut->z );
53336    assert( pOut->flags & MEM_Dyn );
53337    pOut->zMalloc = 0;
53338    pOut->flags |= MEM_Static;
53339    pOut->flags &= ~MEM_Dyn;
53340    if( pOp->p4type==P4_DYNAMIC ){
53341      sqlite3DbFree(db, pOp->p4.z);
53342    }
53343    pOp->p4type = P4_DYNAMIC;
53344    pOp->p4.z = pOut->z;
53345    pOp->p1 = pOut->n;
53346  }
53347#endif
53348  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
53349    goto too_big;
53350  }
53351  /* Fall through to the next case, OP_String */
53352}
53353
53354/* Opcode: String P1 P2 * P4 *
53355**
53356** The string value P4 of length P1 (bytes) is stored in register P2.
53357*/
53358case OP_String: {          /* out2-prerelease */
53359  assert( pOp->p4.z!=0 );
53360  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
53361  pOut->z = pOp->p4.z;
53362  pOut->n = pOp->p1;
53363  pOut->enc = encoding;
53364  UPDATE_MAX_BLOBSIZE(pOut);
53365  break;
53366}
53367
53368/* Opcode: Null * P2 * * *
53369**
53370** Write a NULL into register P2.
53371*/
53372case OP_Null: {           /* out2-prerelease */
53373  pOut->flags = MEM_Null;
53374  break;
53375}
53376
53377
53378/* Opcode: Blob P1 P2 * P4
53379**
53380** P4 points to a blob of data P1 bytes long.  Store this
53381** blob in register P2. This instruction is not coded directly
53382** by the compiler. Instead, the compiler layer specifies
53383** an OP_HexBlob opcode, with the hex string representation of
53384** the blob as P4. This opcode is transformed to an OP_Blob
53385** the first time it is executed.
53386*/
53387case OP_Blob: {                /* out2-prerelease */
53388  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
53389  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
53390  pOut->enc = encoding;
53391  UPDATE_MAX_BLOBSIZE(pOut);
53392  break;
53393}
53394
53395/* Opcode: Variable P1 P2 P3 P4 *
53396**
53397** Transfer the values of bound parameters P1..P1+P3-1 into registers
53398** P2..P2+P3-1.
53399**
53400** If the parameter is named, then its name appears in P4 and P3==1.
53401** The P4 value is used by sqlite3_bind_parameter_name().
53402*/
53403case OP_Variable: {
53404#if 0  /* local variables moved into u.ab */
53405  int p1;          /* Variable to copy from */
53406  int p2;          /* Register to copy to */
53407  int n;           /* Number of values left to copy */
53408  Mem *pVar;       /* Value being transferred */
53409#endif /* local variables moved into u.ab */
53410
53411  u.ab.p1 = pOp->p1 - 1;
53412  u.ab.p2 = pOp->p2;
53413  u.ab.n = pOp->p3;
53414  assert( u.ab.p1>=0 && u.ab.p1+u.ab.n<=p->nVar );
53415  assert( u.ab.p2>=1 && u.ab.p2+u.ab.n-1<=p->nMem );
53416  assert( pOp->p4.z==0 || pOp->p3==1 || pOp->p3==0 );
53417
53418  while( u.ab.n-- > 0 ){
53419    u.ab.pVar = &p->aVar[u.ab.p1++];
53420    if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
53421      goto too_big;
53422    }
53423    pOut = &aMem[u.ab.p2++];
53424    sqlite3VdbeMemReleaseExternal(pOut);
53425    pOut->flags = MEM_Null;
53426    sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
53427    UPDATE_MAX_BLOBSIZE(pOut);
53428  }
53429  break;
53430}
53431
53432/* Opcode: Move P1 P2 P3 * *
53433**
53434** Move the values in register P1..P1+P3-1 over into
53435** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
53436** left holding a NULL.  It is an error for register ranges
53437** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
53438*/
53439case OP_Move: {
53440#if 0  /* local variables moved into u.ac */
53441  char *zMalloc;   /* Holding variable for allocated memory */
53442  int n;           /* Number of registers left to copy */
53443  int p1;          /* Register to copy from */
53444  int p2;          /* Register to copy to */
53445#endif /* local variables moved into u.ac */
53446
53447  u.ac.n = pOp->p3;
53448  u.ac.p1 = pOp->p1;
53449  u.ac.p2 = pOp->p2;
53450  assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
53451  assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
53452
53453  pIn1 = &aMem[u.ac.p1];
53454  pOut = &aMem[u.ac.p2];
53455  while( u.ac.n-- ){
53456    assert( pOut<=&aMem[p->nMem] );
53457    assert( pIn1<=&aMem[p->nMem] );
53458    u.ac.zMalloc = pOut->zMalloc;
53459    pOut->zMalloc = 0;
53460    sqlite3VdbeMemMove(pOut, pIn1);
53461    pIn1->zMalloc = u.ac.zMalloc;
53462    REGISTER_TRACE(u.ac.p2++, pOut);
53463    pIn1++;
53464    pOut++;
53465  }
53466  break;
53467}
53468
53469/* Opcode: Copy P1 P2 * * *
53470**
53471** Make a copy of register P1 into register P2.
53472**
53473** This instruction makes a deep copy of the value.  A duplicate
53474** is made of any string or blob constant.  See also OP_SCopy.
53475*/
53476case OP_Copy: {             /* in1, out2 */
53477  pIn1 = &aMem[pOp->p1];
53478  pOut = &aMem[pOp->p2];
53479  assert( pOut!=pIn1 );
53480  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
53481  Deephemeralize(pOut);
53482  REGISTER_TRACE(pOp->p2, pOut);
53483  break;
53484}
53485
53486/* Opcode: SCopy P1 P2 * * *
53487**
53488** Make a shallow copy of register P1 into register P2.
53489**
53490** This instruction makes a shallow copy of the value.  If the value
53491** is a string or blob, then the copy is only a pointer to the
53492** original and hence if the original changes so will the copy.
53493** Worse, if the original is deallocated, the copy becomes invalid.
53494** Thus the program must guarantee that the original will not change
53495** during the lifetime of the copy.  Use OP_Copy to make a complete
53496** copy.
53497*/
53498case OP_SCopy: {            /* in1, out2 */
53499  pIn1 = &aMem[pOp->p1];
53500  pOut = &aMem[pOp->p2];
53501  assert( pOut!=pIn1 );
53502  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
53503  REGISTER_TRACE(pOp->p2, pOut);
53504  break;
53505}
53506
53507/* Opcode: ResultRow P1 P2 * * *
53508**
53509** The registers P1 through P1+P2-1 contain a single row of
53510** results. This opcode causes the sqlite3_step() call to terminate
53511** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
53512** structure to provide access to the top P1 values as the result
53513** row.
53514*/
53515case OP_ResultRow: {
53516#if 0  /* local variables moved into u.ad */
53517  Mem *pMem;
53518  int i;
53519#endif /* local variables moved into u.ad */
53520  assert( p->nResColumn==pOp->p2 );
53521  assert( pOp->p1>0 );
53522  assert( pOp->p1+pOp->p2<=p->nMem+1 );
53523
53524  /* If this statement has violated immediate foreign key constraints, do
53525  ** not return the number of rows modified. And do not RELEASE the statement
53526  ** transaction. It needs to be rolled back.  */
53527  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
53528    assert( db->flags&SQLITE_CountRows );
53529    assert( p->usesStmtJournal );
53530    break;
53531  }
53532
53533  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
53534  ** DML statements invoke this opcode to return the number of rows
53535  ** modified to the user. This is the only way that a VM that
53536  ** opens a statement transaction may invoke this opcode.
53537  **
53538  ** In case this is such a statement, close any statement transaction
53539  ** opened by this VM before returning control to the user. This is to
53540  ** ensure that statement-transactions are always nested, not overlapping.
53541  ** If the open statement-transaction is not closed here, then the user
53542  ** may step another VM that opens its own statement transaction. This
53543  ** may lead to overlapping statement transactions.
53544  **
53545  ** The statement transaction is never a top-level transaction.  Hence
53546  ** the RELEASE call below can never fail.
53547  */
53548  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
53549  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
53550  if( NEVER(rc!=SQLITE_OK) ){
53551    break;
53552  }
53553
53554  /* Invalidate all ephemeral cursor row caches */
53555  p->cacheCtr = (p->cacheCtr + 2)|1;
53556
53557  /* Make sure the results of the current row are \000 terminated
53558  ** and have an assigned type.  The results are de-ephemeralized as
53559  ** as side effect.
53560  */
53561  u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
53562  for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
53563    sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
53564    sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
53565    REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
53566  }
53567  if( db->mallocFailed ) goto no_mem;
53568
53569  /* Return SQLITE_ROW
53570  */
53571  p->pc = pc + 1;
53572  rc = SQLITE_ROW;
53573  goto vdbe_return;
53574}
53575
53576/* Opcode: Concat P1 P2 P3 * *
53577**
53578** Add the text in register P1 onto the end of the text in
53579** register P2 and store the result in register P3.
53580** If either the P1 or P2 text are NULL then store NULL in P3.
53581**
53582**   P3 = P2 || P1
53583**
53584** It is illegal for P1 and P3 to be the same register. Sometimes,
53585** if P3 is the same register as P2, the implementation is able
53586** to avoid a memcpy().
53587*/
53588case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
53589#if 0  /* local variables moved into u.ae */
53590  i64 nByte;
53591#endif /* local variables moved into u.ae */
53592
53593  pIn1 = &aMem[pOp->p1];
53594  pIn2 = &aMem[pOp->p2];
53595  pOut = &aMem[pOp->p3];
53596  assert( pIn1!=pOut );
53597  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
53598    sqlite3VdbeMemSetNull(pOut);
53599    break;
53600  }
53601  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
53602  Stringify(pIn1, encoding);
53603  Stringify(pIn2, encoding);
53604  u.ae.nByte = pIn1->n + pIn2->n;
53605  if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
53606    goto too_big;
53607  }
53608  MemSetTypeFlag(pOut, MEM_Str);
53609  if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
53610    goto no_mem;
53611  }
53612  if( pOut!=pIn2 ){
53613    memcpy(pOut->z, pIn2->z, pIn2->n);
53614  }
53615  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
53616  pOut->z[u.ae.nByte] = 0;
53617  pOut->z[u.ae.nByte+1] = 0;
53618  pOut->flags |= MEM_Term;
53619  pOut->n = (int)u.ae.nByte;
53620  pOut->enc = encoding;
53621  UPDATE_MAX_BLOBSIZE(pOut);
53622  break;
53623}
53624
53625/* Opcode: Add P1 P2 P3 * *
53626**
53627** Add the value in register P1 to the value in register P2
53628** and store the result in register P3.
53629** If either input is NULL, the result is NULL.
53630*/
53631/* Opcode: Multiply P1 P2 P3 * *
53632**
53633**
53634** Multiply the value in register P1 by the value in register P2
53635** and store the result in register P3.
53636** If either input is NULL, the result is NULL.
53637*/
53638/* Opcode: Subtract P1 P2 P3 * *
53639**
53640** Subtract the value in register P1 from the value in register P2
53641** and store the result in register P3.
53642** If either input is NULL, the result is NULL.
53643*/
53644/* Opcode: Divide P1 P2 P3 * *
53645**
53646** Divide the value in register P1 by the value in register P2
53647** and store the result in register P3 (P3=P2/P1). If the value in
53648** register P1 is zero, then the result is NULL. If either input is
53649** NULL, the result is NULL.
53650*/
53651/* Opcode: Remainder P1 P2 P3 * *
53652**
53653** Compute the remainder after integer division of the value in
53654** register P1 by the value in register P2 and store the result in P3.
53655** If the value in register P2 is zero the result is NULL.
53656** If either operand is NULL, the result is NULL.
53657*/
53658case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
53659case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
53660case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
53661case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
53662case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
53663#if 0  /* local variables moved into u.af */
53664  int flags;      /* Combined MEM_* flags from both inputs */
53665  i64 iA;         /* Integer value of left operand */
53666  i64 iB;         /* Integer value of right operand */
53667  double rA;      /* Real value of left operand */
53668  double rB;      /* Real value of right operand */
53669#endif /* local variables moved into u.af */
53670
53671  pIn1 = &aMem[pOp->p1];
53672  applyNumericAffinity(pIn1);
53673  pIn2 = &aMem[pOp->p2];
53674  applyNumericAffinity(pIn2);
53675  pOut = &aMem[pOp->p3];
53676  u.af.flags = pIn1->flags | pIn2->flags;
53677  if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
53678  if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
53679    u.af.iA = pIn1->u.i;
53680    u.af.iB = pIn2->u.i;
53681    switch( pOp->opcode ){
53682      case OP_Add:         u.af.iB += u.af.iA;       break;
53683      case OP_Subtract:    u.af.iB -= u.af.iA;       break;
53684      case OP_Multiply:    u.af.iB *= u.af.iA;       break;
53685      case OP_Divide: {
53686        if( u.af.iA==0 ) goto arithmetic_result_is_null;
53687        /* Dividing the largest possible negative 64-bit integer (1<<63) by
53688        ** -1 returns an integer too large to store in a 64-bit data-type. On
53689        ** some architectures, the value overflows to (1<<63). On others,
53690        ** a SIGFPE is issued. The following statement normalizes this
53691        ** behavior so that all architectures behave as if integer
53692        ** overflow occurred.
53693        */
53694        if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) u.af.iA = 1;
53695        u.af.iB /= u.af.iA;
53696        break;
53697      }
53698      default: {
53699        if( u.af.iA==0 ) goto arithmetic_result_is_null;
53700        if( u.af.iA==-1 ) u.af.iA = 1;
53701        u.af.iB %= u.af.iA;
53702        break;
53703      }
53704    }
53705    pOut->u.i = u.af.iB;
53706    MemSetTypeFlag(pOut, MEM_Int);
53707  }else{
53708    u.af.rA = sqlite3VdbeRealValue(pIn1);
53709    u.af.rB = sqlite3VdbeRealValue(pIn2);
53710    switch( pOp->opcode ){
53711      case OP_Add:         u.af.rB += u.af.rA;       break;
53712      case OP_Subtract:    u.af.rB -= u.af.rA;       break;
53713      case OP_Multiply:    u.af.rB *= u.af.rA;       break;
53714      case OP_Divide: {
53715        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
53716        if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
53717        u.af.rB /= u.af.rA;
53718        break;
53719      }
53720      default: {
53721        u.af.iA = (i64)u.af.rA;
53722        u.af.iB = (i64)u.af.rB;
53723        if( u.af.iA==0 ) goto arithmetic_result_is_null;
53724        if( u.af.iA==-1 ) u.af.iA = 1;
53725        u.af.rB = (double)(u.af.iB % u.af.iA);
53726        break;
53727      }
53728    }
53729    if( sqlite3IsNaN(u.af.rB) ){
53730      goto arithmetic_result_is_null;
53731    }
53732    pOut->r = u.af.rB;
53733    MemSetTypeFlag(pOut, MEM_Real);
53734    if( (u.af.flags & MEM_Real)==0 ){
53735      sqlite3VdbeIntegerAffinity(pOut);
53736    }
53737  }
53738  break;
53739
53740arithmetic_result_is_null:
53741  sqlite3VdbeMemSetNull(pOut);
53742  break;
53743}
53744
53745/* Opcode: CollSeq * * P4
53746**
53747** P4 is a pointer to a CollSeq struct. If the next call to a user function
53748** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
53749** be returned. This is used by the built-in min(), max() and nullif()
53750** functions.
53751**
53752** The interface used by the implementation of the aforementioned functions
53753** to retrieve the collation sequence set by this opcode is not available
53754** publicly, only to user functions defined in func.c.
53755*/
53756case OP_CollSeq: {
53757  assert( pOp->p4type==P4_COLLSEQ );
53758  break;
53759}
53760
53761/* Opcode: Function P1 P2 P3 P4 P5
53762**
53763** Invoke a user function (P4 is a pointer to a Function structure that
53764** defines the function) with P5 arguments taken from register P2 and
53765** successors.  The result of the function is stored in register P3.
53766** Register P3 must not be one of the function inputs.
53767**
53768** P1 is a 32-bit bitmask indicating whether or not each argument to the
53769** function was determined to be constant at compile time. If the first
53770** argument was constant then bit 0 of P1 is set. This is used to determine
53771** whether meta data associated with a user function argument using the
53772** sqlite3_set_auxdata() API may be safely retained until the next
53773** invocation of this opcode.
53774**
53775** See also: AggStep and AggFinal
53776*/
53777case OP_Function: {
53778#if 0  /* local variables moved into u.ag */
53779  int i;
53780  Mem *pArg;
53781  sqlite3_context ctx;
53782  sqlite3_value **apVal;
53783  int n;
53784#endif /* local variables moved into u.ag */
53785
53786  u.ag.n = pOp->p5;
53787  u.ag.apVal = p->apArg;
53788  assert( u.ag.apVal || u.ag.n==0 );
53789
53790  assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
53791  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
53792  u.ag.pArg = &aMem[pOp->p2];
53793  for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
53794    u.ag.apVal[u.ag.i] = u.ag.pArg;
53795    sqlite3VdbeMemStoreType(u.ag.pArg);
53796    REGISTER_TRACE(pOp->p2, u.ag.pArg);
53797  }
53798
53799  assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
53800  if( pOp->p4type==P4_FUNCDEF ){
53801    u.ag.ctx.pFunc = pOp->p4.pFunc;
53802    u.ag.ctx.pVdbeFunc = 0;
53803  }else{
53804    u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
53805    u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
53806  }
53807
53808  assert( pOp->p3>0 && pOp->p3<=p->nMem );
53809  pOut = &aMem[pOp->p3];
53810  u.ag.ctx.s.flags = MEM_Null;
53811  u.ag.ctx.s.db = db;
53812  u.ag.ctx.s.xDel = 0;
53813  u.ag.ctx.s.zMalloc = 0;
53814
53815  /* The output cell may already have a buffer allocated. Move
53816  ** the pointer to u.ag.ctx.s so in case the user-function can use
53817  ** the already allocated buffer instead of allocating a new one.
53818  */
53819  sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
53820  MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
53821
53822  u.ag.ctx.isError = 0;
53823  if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
53824    assert( pOp>aOp );
53825    assert( pOp[-1].p4type==P4_COLLSEQ );
53826    assert( pOp[-1].opcode==OP_CollSeq );
53827    u.ag.ctx.pColl = pOp[-1].p4.pColl;
53828  }
53829  (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal);
53830  if( db->mallocFailed ){
53831    /* Even though a malloc() has failed, the implementation of the
53832    ** user function may have called an sqlite3_result_XXX() function
53833    ** to return a value. The following call releases any resources
53834    ** associated with such a value.
53835    */
53836    sqlite3VdbeMemRelease(&u.ag.ctx.s);
53837    goto no_mem;
53838  }
53839
53840  /* If any auxiliary data functions have been called by this user function,
53841  ** immediately call the destructor for any non-static values.
53842  */
53843  if( u.ag.ctx.pVdbeFunc ){
53844    sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
53845    pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
53846    pOp->p4type = P4_VDBEFUNC;
53847  }
53848
53849  /* If the function returned an error, throw an exception */
53850  if( u.ag.ctx.isError ){
53851    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
53852    rc = u.ag.ctx.isError;
53853  }
53854
53855  /* Copy the result of the function into register P3 */
53856  sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
53857  sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
53858  if( sqlite3VdbeMemTooBig(pOut) ){
53859    goto too_big;
53860  }
53861  REGISTER_TRACE(pOp->p3, pOut);
53862  UPDATE_MAX_BLOBSIZE(pOut);
53863  break;
53864}
53865
53866/* Opcode: BitAnd P1 P2 P3 * *
53867**
53868** Take the bit-wise AND of the values in register P1 and P2 and
53869** store the result in register P3.
53870** If either input is NULL, the result is NULL.
53871*/
53872/* Opcode: BitOr P1 P2 P3 * *
53873**
53874** Take the bit-wise OR of the values in register P1 and P2 and
53875** store the result in register P3.
53876** If either input is NULL, the result is NULL.
53877*/
53878/* Opcode: ShiftLeft P1 P2 P3 * *
53879**
53880** Shift the integer value in register P2 to the left by the
53881** number of bits specified by the integer in regiser P1.
53882** Store the result in register P3.
53883** If either input is NULL, the result is NULL.
53884*/
53885/* Opcode: ShiftRight P1 P2 P3 * *
53886**
53887** Shift the integer value in register P2 to the right by the
53888** number of bits specified by the integer in register P1.
53889** Store the result in register P3.
53890** If either input is NULL, the result is NULL.
53891*/
53892case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
53893case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
53894case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
53895case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
53896#if 0  /* local variables moved into u.ah */
53897  i64 a;
53898  i64 b;
53899#endif /* local variables moved into u.ah */
53900
53901  pIn1 = &aMem[pOp->p1];
53902  pIn2 = &aMem[pOp->p2];
53903  pOut = &aMem[pOp->p3];
53904  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
53905    sqlite3VdbeMemSetNull(pOut);
53906    break;
53907  }
53908  u.ah.a = sqlite3VdbeIntValue(pIn2);
53909  u.ah.b = sqlite3VdbeIntValue(pIn1);
53910  switch( pOp->opcode ){
53911    case OP_BitAnd:      u.ah.a &= u.ah.b;     break;
53912    case OP_BitOr:       u.ah.a |= u.ah.b;     break;
53913    case OP_ShiftLeft:   u.ah.a <<= u.ah.b;    break;
53914    default:  assert( pOp->opcode==OP_ShiftRight );
53915                         u.ah.a >>= u.ah.b;    break;
53916  }
53917  pOut->u.i = u.ah.a;
53918  MemSetTypeFlag(pOut, MEM_Int);
53919  break;
53920}
53921
53922/* Opcode: AddImm  P1 P2 * * *
53923**
53924** Add the constant P2 to the value in register P1.
53925** The result is always an integer.
53926**
53927** To force any register to be an integer, just add 0.
53928*/
53929case OP_AddImm: {            /* in1 */
53930  pIn1 = &aMem[pOp->p1];
53931  sqlite3VdbeMemIntegerify(pIn1);
53932  pIn1->u.i += pOp->p2;
53933  break;
53934}
53935
53936/* Opcode: MustBeInt P1 P2 * * *
53937**
53938** Force the value in register P1 to be an integer.  If the value
53939** in P1 is not an integer and cannot be converted into an integer
53940** without data loss, then jump immediately to P2, or if P2==0
53941** raise an SQLITE_MISMATCH exception.
53942*/
53943case OP_MustBeInt: {            /* jump, in1 */
53944  pIn1 = &aMem[pOp->p1];
53945  applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
53946  if( (pIn1->flags & MEM_Int)==0 ){
53947    if( pOp->p2==0 ){
53948      rc = SQLITE_MISMATCH;
53949      goto abort_due_to_error;
53950    }else{
53951      pc = pOp->p2 - 1;
53952    }
53953  }else{
53954    MemSetTypeFlag(pIn1, MEM_Int);
53955  }
53956  break;
53957}
53958
53959/* Opcode: RealAffinity P1 * * * *
53960**
53961** If register P1 holds an integer convert it to a real value.
53962**
53963** This opcode is used when extracting information from a column that
53964** has REAL affinity.  Such column values may still be stored as
53965** integers, for space efficiency, but after extraction we want them
53966** to have only a real value.
53967*/
53968case OP_RealAffinity: {                  /* in1 */
53969  pIn1 = &aMem[pOp->p1];
53970  if( pIn1->flags & MEM_Int ){
53971    sqlite3VdbeMemRealify(pIn1);
53972  }
53973  break;
53974}
53975
53976#ifndef SQLITE_OMIT_CAST
53977/* Opcode: ToText P1 * * * *
53978**
53979** Force the value in register P1 to be text.
53980** If the value is numeric, convert it to a string using the
53981** equivalent of printf().  Blob values are unchanged and
53982** are afterwards simply interpreted as text.
53983**
53984** A NULL value is not changed by this routine.  It remains NULL.
53985*/
53986case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
53987  pIn1 = &aMem[pOp->p1];
53988  if( pIn1->flags & MEM_Null ) break;
53989  assert( MEM_Str==(MEM_Blob>>3) );
53990  pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
53991  applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
53992  rc = ExpandBlob(pIn1);
53993  assert( pIn1->flags & MEM_Str || db->mallocFailed );
53994  pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
53995  UPDATE_MAX_BLOBSIZE(pIn1);
53996  break;
53997}
53998
53999/* Opcode: ToBlob P1 * * * *
54000**
54001** Force the value in register P1 to be a BLOB.
54002** If the value is numeric, convert it to a string first.
54003** Strings are simply reinterpreted as blobs with no change
54004** to the underlying data.
54005**
54006** A NULL value is not changed by this routine.  It remains NULL.
54007*/
54008case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
54009  pIn1 = &aMem[pOp->p1];
54010  if( pIn1->flags & MEM_Null ) break;
54011  if( (pIn1->flags & MEM_Blob)==0 ){
54012    applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
54013    assert( pIn1->flags & MEM_Str || db->mallocFailed );
54014    MemSetTypeFlag(pIn1, MEM_Blob);
54015  }else{
54016    pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
54017  }
54018  UPDATE_MAX_BLOBSIZE(pIn1);
54019  break;
54020}
54021
54022/* Opcode: ToNumeric P1 * * * *
54023**
54024** Force the value in register P1 to be numeric (either an
54025** integer or a floating-point number.)
54026** If the value is text or blob, try to convert it to an using the
54027** equivalent of atoi() or atof() and store 0 if no such conversion
54028** is possible.
54029**
54030** A NULL value is not changed by this routine.  It remains NULL.
54031*/
54032case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
54033  pIn1 = &aMem[pOp->p1];
54034  if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
54035    sqlite3VdbeMemNumerify(pIn1);
54036  }
54037  break;
54038}
54039#endif /* SQLITE_OMIT_CAST */
54040
54041/* Opcode: ToInt P1 * * * *
54042**
54043** Force the value in register P1 be an integer.  If
54044** The value is currently a real number, drop its fractional part.
54045** If the value is text or blob, try to convert it to an integer using the
54046** equivalent of atoi() and store 0 if no such conversion is possible.
54047**
54048** A NULL value is not changed by this routine.  It remains NULL.
54049*/
54050case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
54051  pIn1 = &aMem[pOp->p1];
54052  if( (pIn1->flags & MEM_Null)==0 ){
54053    sqlite3VdbeMemIntegerify(pIn1);
54054  }
54055  break;
54056}
54057
54058#ifndef SQLITE_OMIT_CAST
54059/* Opcode: ToReal P1 * * * *
54060**
54061** Force the value in register P1 to be a floating point number.
54062** If The value is currently an integer, convert it.
54063** If the value is text or blob, try to convert it to an integer using the
54064** equivalent of atoi() and store 0.0 if no such conversion is possible.
54065**
54066** A NULL value is not changed by this routine.  It remains NULL.
54067*/
54068case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
54069  pIn1 = &aMem[pOp->p1];
54070  if( (pIn1->flags & MEM_Null)==0 ){
54071    sqlite3VdbeMemRealify(pIn1);
54072  }
54073  break;
54074}
54075#endif /* SQLITE_OMIT_CAST */
54076
54077/* Opcode: Lt P1 P2 P3 P4 P5
54078**
54079** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
54080** jump to address P2.
54081**
54082** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
54083** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
54084** bit is clear then fall thru if either operand is NULL.
54085**
54086** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
54087** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
54088** to coerce both inputs according to this affinity before the
54089** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
54090** affinity is used. Note that the affinity conversions are stored
54091** back into the input registers P1 and P3.  So this opcode can cause
54092** persistent changes to registers P1 and P3.
54093**
54094** Once any conversions have taken place, and neither value is NULL,
54095** the values are compared. If both values are blobs then memcmp() is
54096** used to determine the results of the comparison.  If both values
54097** are text, then the appropriate collating function specified in
54098** P4 is  used to do the comparison.  If P4 is not specified then
54099** memcmp() is used to compare text string.  If both values are
54100** numeric, then a numeric comparison is used. If the two values
54101** are of different types, then numbers are considered less than
54102** strings and strings are considered less than blobs.
54103**
54104** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
54105** store a boolean result (either 0, or 1, or NULL) in register P2.
54106*/
54107/* Opcode: Ne P1 P2 P3 P4 P5
54108**
54109** This works just like the Lt opcode except that the jump is taken if
54110** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
54111** additional information.
54112**
54113** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
54114** true or false and is never NULL.  If both operands are NULL then the result
54115** of comparison is false.  If either operand is NULL then the result is true.
54116** If neither operand is NULL the the result is the same as it would be if
54117** the SQLITE_NULLEQ flag were omitted from P5.
54118*/
54119/* Opcode: Eq P1 P2 P3 P4 P5
54120**
54121** This works just like the Lt opcode except that the jump is taken if
54122** the operands in registers P1 and P3 are equal.
54123** See the Lt opcode for additional information.
54124**
54125** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
54126** true or false and is never NULL.  If both operands are NULL then the result
54127** of comparison is true.  If either operand is NULL then the result is false.
54128** If neither operand is NULL the the result is the same as it would be if
54129** the SQLITE_NULLEQ flag were omitted from P5.
54130*/
54131/* Opcode: Le P1 P2 P3 P4 P5
54132**
54133** This works just like the Lt opcode except that the jump is taken if
54134** the content of register P3 is less than or equal to the content of
54135** register P1.  See the Lt opcode for additional information.
54136*/
54137/* Opcode: Gt P1 P2 P3 P4 P5
54138**
54139** This works just like the Lt opcode except that the jump is taken if
54140** the content of register P3 is greater than the content of
54141** register P1.  See the Lt opcode for additional information.
54142*/
54143/* Opcode: Ge P1 P2 P3 P4 P5
54144**
54145** This works just like the Lt opcode except that the jump is taken if
54146** the content of register P3 is greater than or equal to the content of
54147** register P1.  See the Lt opcode for additional information.
54148*/
54149case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
54150case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
54151case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
54152case OP_Le:               /* same as TK_LE, jump, in1, in3 */
54153case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
54154case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
54155#if 0  /* local variables moved into u.ai */
54156  int res;            /* Result of the comparison of pIn1 against pIn3 */
54157  char affinity;      /* Affinity to use for comparison */
54158#endif /* local variables moved into u.ai */
54159
54160  pIn1 = &aMem[pOp->p1];
54161  pIn3 = &aMem[pOp->p3];
54162  if( (pIn1->flags | pIn3->flags)&MEM_Null ){
54163    /* One or both operands are NULL */
54164    if( pOp->p5 & SQLITE_NULLEQ ){
54165      /* If SQLITE_NULLEQ is set (which will only happen if the operator is
54166      ** OP_Eq or OP_Ne) then take the jump or not depending on whether
54167      ** or not both operands are null.
54168      */
54169      assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
54170      u.ai.res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
54171    }else{
54172      /* SQLITE_NULLEQ is clear and at least one operand is NULL,
54173      ** then the result is always NULL.
54174      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
54175      */
54176      if( pOp->p5 & SQLITE_STOREP2 ){
54177        pOut = &aMem[pOp->p2];
54178        MemSetTypeFlag(pOut, MEM_Null);
54179        REGISTER_TRACE(pOp->p2, pOut);
54180      }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
54181        pc = pOp->p2-1;
54182      }
54183      break;
54184    }
54185  }else{
54186    /* Neither operand is NULL.  Do a comparison. */
54187    u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
54188    if( u.ai.affinity ){
54189      applyAffinity(pIn1, u.ai.affinity, encoding);
54190      applyAffinity(pIn3, u.ai.affinity, encoding);
54191      if( db->mallocFailed ) goto no_mem;
54192    }
54193
54194    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
54195    ExpandBlob(pIn1);
54196    ExpandBlob(pIn3);
54197    u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
54198  }
54199  switch( pOp->opcode ){
54200    case OP_Eq:    u.ai.res = u.ai.res==0;     break;
54201    case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
54202    case OP_Lt:    u.ai.res = u.ai.res<0;      break;
54203    case OP_Le:    u.ai.res = u.ai.res<=0;     break;
54204    case OP_Gt:    u.ai.res = u.ai.res>0;      break;
54205    default:       u.ai.res = u.ai.res>=0;     break;
54206  }
54207
54208  if( pOp->p5 & SQLITE_STOREP2 ){
54209    pOut = &aMem[pOp->p2];
54210    MemSetTypeFlag(pOut, MEM_Int);
54211    pOut->u.i = u.ai.res;
54212    REGISTER_TRACE(pOp->p2, pOut);
54213  }else if( u.ai.res ){
54214    pc = pOp->p2-1;
54215  }
54216  break;
54217}
54218
54219/* Opcode: Permutation * * * P4 *
54220**
54221** Set the permutation used by the OP_Compare operator to be the array
54222** of integers in P4.
54223**
54224** The permutation is only valid until the next OP_Permutation, OP_Compare,
54225** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
54226** immediately prior to the OP_Compare.
54227*/
54228case OP_Permutation: {
54229  assert( pOp->p4type==P4_INTARRAY );
54230  assert( pOp->p4.ai );
54231  aPermute = pOp->p4.ai;
54232  break;
54233}
54234
54235/* Opcode: Compare P1 P2 P3 P4 *
54236**
54237** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
54238** one "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
54239** the comparison for use by the next OP_Jump instruct.
54240**
54241** P4 is a KeyInfo structure that defines collating sequences and sort
54242** orders for the comparison.  The permutation applies to registers
54243** only.  The KeyInfo elements are used sequentially.
54244**
54245** The comparison is a sort comparison, so NULLs compare equal,
54246** NULLs are less than numbers, numbers are less than strings,
54247** and strings are less than blobs.
54248*/
54249case OP_Compare: {
54250#if 0  /* local variables moved into u.aj */
54251  int n;
54252  int i;
54253  int p1;
54254  int p2;
54255  const KeyInfo *pKeyInfo;
54256  int idx;
54257  CollSeq *pColl;    /* Collating sequence to use on this term */
54258  int bRev;          /* True for DESCENDING sort order */
54259#endif /* local variables moved into u.aj */
54260
54261  u.aj.n = pOp->p3;
54262  u.aj.pKeyInfo = pOp->p4.pKeyInfo;
54263  assert( u.aj.n>0 );
54264  assert( u.aj.pKeyInfo!=0 );
54265  u.aj.p1 = pOp->p1;
54266  u.aj.p2 = pOp->p2;
54267#if SQLITE_DEBUG
54268  if( aPermute ){
54269    int k, mx = 0;
54270    for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
54271    assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
54272    assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
54273  }else{
54274    assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
54275    assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
54276  }
54277#endif /* SQLITE_DEBUG */
54278  for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
54279    u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
54280    REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
54281    REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
54282    assert( u.aj.i<u.aj.pKeyInfo->nField );
54283    u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
54284    u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
54285    iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
54286    if( iCompare ){
54287      if( u.aj.bRev ) iCompare = -iCompare;
54288      break;
54289    }
54290  }
54291  aPermute = 0;
54292  break;
54293}
54294
54295/* Opcode: Jump P1 P2 P3 * *
54296**
54297** Jump to the instruction at address P1, P2, or P3 depending on whether
54298** in the most recent OP_Compare instruction the P1 vector was less than
54299** equal to, or greater than the P2 vector, respectively.
54300*/
54301case OP_Jump: {             /* jump */
54302  if( iCompare<0 ){
54303    pc = pOp->p1 - 1;
54304  }else if( iCompare==0 ){
54305    pc = pOp->p2 - 1;
54306  }else{
54307    pc = pOp->p3 - 1;
54308  }
54309  break;
54310}
54311
54312/* Opcode: And P1 P2 P3 * *
54313**
54314** Take the logical AND of the values in registers P1 and P2 and
54315** write the result into register P3.
54316**
54317** If either P1 or P2 is 0 (false) then the result is 0 even if
54318** the other input is NULL.  A NULL and true or two NULLs give
54319** a NULL output.
54320*/
54321/* Opcode: Or P1 P2 P3 * *
54322**
54323** Take the logical OR of the values in register P1 and P2 and
54324** store the answer in register P3.
54325**
54326** If either P1 or P2 is nonzero (true) then the result is 1 (true)
54327** even if the other input is NULL.  A NULL and false or two NULLs
54328** give a NULL output.
54329*/
54330case OP_And:              /* same as TK_AND, in1, in2, out3 */
54331case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
54332#if 0  /* local variables moved into u.ak */
54333  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
54334  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
54335#endif /* local variables moved into u.ak */
54336
54337  pIn1 = &aMem[pOp->p1];
54338  if( pIn1->flags & MEM_Null ){
54339    u.ak.v1 = 2;
54340  }else{
54341    u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
54342  }
54343  pIn2 = &aMem[pOp->p2];
54344  if( pIn2->flags & MEM_Null ){
54345    u.ak.v2 = 2;
54346  }else{
54347    u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
54348  }
54349  if( pOp->opcode==OP_And ){
54350    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
54351    u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
54352  }else{
54353    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
54354    u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
54355  }
54356  pOut = &aMem[pOp->p3];
54357  if( u.ak.v1==2 ){
54358    MemSetTypeFlag(pOut, MEM_Null);
54359  }else{
54360    pOut->u.i = u.ak.v1;
54361    MemSetTypeFlag(pOut, MEM_Int);
54362  }
54363  break;
54364}
54365
54366/* Opcode: Not P1 P2 * * *
54367**
54368** Interpret the value in register P1 as a boolean value.  Store the
54369** boolean complement in register P2.  If the value in register P1 is
54370** NULL, then a NULL is stored in P2.
54371*/
54372case OP_Not: {                /* same as TK_NOT, in1, out2 */
54373  pIn1 = &aMem[pOp->p1];
54374  pOut = &aMem[pOp->p2];
54375  if( pIn1->flags & MEM_Null ){
54376    sqlite3VdbeMemSetNull(pOut);
54377  }else{
54378    sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
54379  }
54380  break;
54381}
54382
54383/* Opcode: BitNot P1 P2 * * *
54384**
54385** Interpret the content of register P1 as an integer.  Store the
54386** ones-complement of the P1 value into register P2.  If P1 holds
54387** a NULL then store a NULL in P2.
54388*/
54389case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
54390  pIn1 = &aMem[pOp->p1];
54391  pOut = &aMem[pOp->p2];
54392  if( pIn1->flags & MEM_Null ){
54393    sqlite3VdbeMemSetNull(pOut);
54394  }else{
54395    sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
54396  }
54397  break;
54398}
54399
54400/* Opcode: If P1 P2 P3 * *
54401**
54402** Jump to P2 if the value in register P1 is true.  The value is
54403** is considered true if it is numeric and non-zero.  If the value
54404** in P1 is NULL then take the jump if P3 is true.
54405*/
54406/* Opcode: IfNot P1 P2 P3 * *
54407**
54408** Jump to P2 if the value in register P1 is False.  The value is
54409** is considered true if it has a numeric value of zero.  If the value
54410** in P1 is NULL then take the jump if P3 is true.
54411*/
54412case OP_If:                 /* jump, in1 */
54413case OP_IfNot: {            /* jump, in1 */
54414#if 0  /* local variables moved into u.al */
54415  int c;
54416#endif /* local variables moved into u.al */
54417  pIn1 = &aMem[pOp->p1];
54418  if( pIn1->flags & MEM_Null ){
54419    u.al.c = pOp->p3;
54420  }else{
54421#ifdef SQLITE_OMIT_FLOATING_POINT
54422    u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
54423#else
54424    u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
54425#endif
54426    if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
54427  }
54428  if( u.al.c ){
54429    pc = pOp->p2-1;
54430  }
54431  break;
54432}
54433
54434/* Opcode: IsNull P1 P2 * * *
54435**
54436** Jump to P2 if the value in register P1 is NULL.
54437*/
54438case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
54439  pIn1 = &aMem[pOp->p1];
54440  if( (pIn1->flags & MEM_Null)!=0 ){
54441    pc = pOp->p2 - 1;
54442  }
54443  break;
54444}
54445
54446/* Opcode: NotNull P1 P2 * * *
54447**
54448** Jump to P2 if the value in register P1 is not NULL.
54449*/
54450case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
54451  pIn1 = &aMem[pOp->p1];
54452  if( (pIn1->flags & MEM_Null)==0 ){
54453    pc = pOp->p2 - 1;
54454  }
54455  break;
54456}
54457
54458/* Opcode: Column P1 P2 P3 P4 P5
54459**
54460** Interpret the data that cursor P1 points to as a structure built using
54461** the MakeRecord instruction.  (See the MakeRecord opcode for additional
54462** information about the format of the data.)  Extract the P2-th column
54463** from this record.  If there are less that (P2+1)
54464** values in the record, extract a NULL.
54465**
54466** The value extracted is stored in register P3.
54467**
54468** If the column contains fewer than P2 fields, then extract a NULL.  Or,
54469** if the P4 argument is a P4_MEM use the value of the P4 argument as
54470** the result.
54471**
54472** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
54473** then the cache of the cursor is reset prior to extracting the column.
54474** The first OP_Column against a pseudo-table after the value of the content
54475** register has changed should have this bit set.
54476*/
54477case OP_Column: {
54478#if 0  /* local variables moved into u.am */
54479  u32 payloadSize;   /* Number of bytes in the record */
54480  i64 payloadSize64; /* Number of bytes in the record */
54481  int p1;            /* P1 value of the opcode */
54482  int p2;            /* column number to retrieve */
54483  VdbeCursor *pC;    /* The VDBE cursor */
54484  char *zRec;        /* Pointer to complete record-data */
54485  BtCursor *pCrsr;   /* The BTree cursor */
54486  u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
54487  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
54488  int nField;        /* number of fields in the record */
54489  int len;           /* The length of the serialized data for the column */
54490  int i;             /* Loop counter */
54491  char *zData;       /* Part of the record being decoded */
54492  Mem *pDest;        /* Where to write the extracted value */
54493  Mem sMem;          /* For storing the record being decoded */
54494  u8 *zIdx;          /* Index into header */
54495  u8 *zEndHdr;       /* Pointer to first byte after the header */
54496  u32 offset;        /* Offset into the data */
54497  u32 szField;       /* Number of bytes in the content of a field */
54498  int szHdr;         /* Size of the header size field at start of record */
54499  int avail;         /* Number of bytes of available data */
54500  Mem *pReg;         /* PseudoTable input register */
54501#endif /* local variables moved into u.am */
54502
54503
54504  u.am.p1 = pOp->p1;
54505  u.am.p2 = pOp->p2;
54506  u.am.pC = 0;
54507  memset(&u.am.sMem, 0, sizeof(u.am.sMem));
54508  assert( u.am.p1<p->nCursor );
54509  assert( pOp->p3>0 && pOp->p3<=p->nMem );
54510  u.am.pDest = &aMem[pOp->p3];
54511  MemSetTypeFlag(u.am.pDest, MEM_Null);
54512  u.am.zRec = 0;
54513
54514  /* This block sets the variable u.am.payloadSize to be the total number of
54515  ** bytes in the record.
54516  **
54517  ** u.am.zRec is set to be the complete text of the record if it is available.
54518  ** The complete record text is always available for pseudo-tables
54519  ** If the record is stored in a cursor, the complete record text
54520  ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
54521  ** If the data is unavailable,  u.am.zRec is set to NULL.
54522  **
54523  ** We also compute the number of columns in the record.  For cursors,
54524  ** the number of columns is stored in the VdbeCursor.nField element.
54525  */
54526  u.am.pC = p->apCsr[u.am.p1];
54527  assert( u.am.pC!=0 );
54528#ifndef SQLITE_OMIT_VIRTUALTABLE
54529  assert( u.am.pC->pVtabCursor==0 );
54530#endif
54531  u.am.pCrsr = u.am.pC->pCursor;
54532  if( u.am.pCrsr!=0 ){
54533    /* The record is stored in a B-Tree */
54534    rc = sqlite3VdbeCursorMoveto(u.am.pC);
54535    if( rc ) goto abort_due_to_error;
54536    if( u.am.pC->nullRow ){
54537      u.am.payloadSize = 0;
54538    }else if( u.am.pC->cacheStatus==p->cacheCtr ){
54539      u.am.payloadSize = u.am.pC->payloadSize;
54540      u.am.zRec = (char*)u.am.pC->aRow;
54541    }else if( u.am.pC->isIndex ){
54542      assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
54543      rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
54544      assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
54545      /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
54546      ** payload size, so it is impossible for u.am.payloadSize64 to be
54547      ** larger than 32 bits. */
54548      assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
54549      u.am.payloadSize = (u32)u.am.payloadSize64;
54550    }else{
54551      assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
54552      rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
54553      assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
54554    }
54555  }else if( u.am.pC->pseudoTableReg>0 ){
54556    u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
54557    assert( u.am.pReg->flags & MEM_Blob );
54558    u.am.payloadSize = u.am.pReg->n;
54559    u.am.zRec = u.am.pReg->z;
54560    u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
54561    assert( u.am.payloadSize==0 || u.am.zRec!=0 );
54562  }else{
54563    /* Consider the row to be NULL */
54564    u.am.payloadSize = 0;
54565  }
54566
54567  /* If u.am.payloadSize is 0, then just store a NULL */
54568  if( u.am.payloadSize==0 ){
54569    assert( u.am.pDest->flags&MEM_Null );
54570    goto op_column_out;
54571  }
54572  assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
54573  if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
54574    goto too_big;
54575  }
54576
54577  u.am.nField = u.am.pC->nField;
54578  assert( u.am.p2<u.am.nField );
54579
54580  /* Read and parse the table header.  Store the results of the parse
54581  ** into the record header cache fields of the cursor.
54582  */
54583  u.am.aType = u.am.pC->aType;
54584  if( u.am.pC->cacheStatus==p->cacheCtr ){
54585    u.am.aOffset = u.am.pC->aOffset;
54586  }else{
54587    assert(u.am.aType);
54588    u.am.avail = 0;
54589    u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
54590    u.am.pC->payloadSize = u.am.payloadSize;
54591    u.am.pC->cacheStatus = p->cacheCtr;
54592
54593    /* Figure out how many bytes are in the header */
54594    if( u.am.zRec ){
54595      u.am.zData = u.am.zRec;
54596    }else{
54597      if( u.am.pC->isIndex ){
54598        u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
54599      }else{
54600        u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
54601      }
54602      /* If KeyFetch()/DataFetch() managed to get the entire payload,
54603      ** save the payload in the u.am.pC->aRow cache.  That will save us from
54604      ** having to make additional calls to fetch the content portion of
54605      ** the record.
54606      */
54607      assert( u.am.avail>=0 );
54608      if( u.am.payloadSize <= (u32)u.am.avail ){
54609        u.am.zRec = u.am.zData;
54610        u.am.pC->aRow = (u8*)u.am.zData;
54611      }else{
54612        u.am.pC->aRow = 0;
54613      }
54614    }
54615    /* The following assert is true in all cases accept when
54616    ** the database file has been corrupted externally.
54617    **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
54618    u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
54619
54620    /* Make sure a corrupt database has not given us an oversize header.
54621    ** Do this now to avoid an oversize memory allocation.
54622    **
54623    ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
54624    ** types use so much data space that there can only be 4096 and 32 of
54625    ** them, respectively.  So the maximum header length results from a
54626    ** 3-byte type for each of the maximum of 32768 columns plus three
54627    ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
54628    */
54629    if( u.am.offset > 98307 ){
54630      rc = SQLITE_CORRUPT_BKPT;
54631      goto op_column_out;
54632    }
54633
54634    /* Compute in u.am.len the number of bytes of data we need to read in order
54635    ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
54636    ** u.am.nField might be significantly less than the true number of columns
54637    ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
54638    ** We want to minimize u.am.len in order to limit the size of the memory
54639    ** allocation, especially if a corrupt database file has caused u.am.offset
54640    ** to be oversized. Offset is limited to 98307 above.  But 98307 might
54641    ** still exceed Robson memory allocation limits on some configurations.
54642    ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
54643    ** will likely be much smaller since u.am.nField will likely be less than
54644    ** 20 or so.  This insures that Robson memory allocation limits are
54645    ** not exceeded even for corrupt database files.
54646    */
54647    u.am.len = u.am.nField*5 + 3;
54648    if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
54649
54650    /* The KeyFetch() or DataFetch() above are fast and will get the entire
54651    ** record header in most cases.  But they will fail to get the complete
54652    ** record header if the record header does not fit on a single page
54653    ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
54654    ** acquire the complete header text.
54655    */
54656    if( !u.am.zRec && u.am.avail<u.am.len ){
54657      u.am.sMem.flags = 0;
54658      u.am.sMem.db = 0;
54659      rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
54660      if( rc!=SQLITE_OK ){
54661        goto op_column_out;
54662      }
54663      u.am.zData = u.am.sMem.z;
54664    }
54665    u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
54666    u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
54667
54668    /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
54669    ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
54670    ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
54671    ** of the record to the start of the data for the u.am.i-th column
54672    */
54673    for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
54674      if( u.am.zIdx<u.am.zEndHdr ){
54675        u.am.aOffset[u.am.i] = u.am.offset;
54676        u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
54677        u.am.szField = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
54678        u.am.offset += u.am.szField;
54679        if( u.am.offset<u.am.szField ){  /* True if u.am.offset overflows */
54680          u.am.zIdx = &u.am.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
54681          break;
54682        }
54683      }else{
54684        /* If u.am.i is less that u.am.nField, then there are less fields in this
54685        ** record than SetNumColumns indicated there are columns in the
54686        ** table. Set the u.am.offset for any extra columns not present in
54687        ** the record to 0. This tells code below to store a NULL
54688        ** instead of deserializing a value from the record.
54689        */
54690        u.am.aOffset[u.am.i] = 0;
54691      }
54692    }
54693    sqlite3VdbeMemRelease(&u.am.sMem);
54694    u.am.sMem.flags = MEM_Null;
54695
54696    /* If we have read more header data than was contained in the header,
54697    ** or if the end of the last field appears to be past the end of the
54698    ** record, or if the end of the last field appears to be before the end
54699    ** of the record (when all fields present), then we must be dealing
54700    ** with a corrupt database.
54701    */
54702    if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
54703         || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
54704      rc = SQLITE_CORRUPT_BKPT;
54705      goto op_column_out;
54706    }
54707  }
54708
54709  /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
54710  ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
54711  ** then there are not enough fields in the record to satisfy the
54712  ** request.  In this case, set the value NULL or to P4 if P4 is
54713  ** a pointer to a Mem object.
54714  */
54715  if( u.am.aOffset[u.am.p2] ){
54716    assert( rc==SQLITE_OK );
54717    if( u.am.zRec ){
54718      sqlite3VdbeMemReleaseExternal(u.am.pDest);
54719      sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
54720    }else{
54721      u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
54722      sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
54723      rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
54724      if( rc!=SQLITE_OK ){
54725        goto op_column_out;
54726      }
54727      u.am.zData = u.am.sMem.z;
54728      sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
54729    }
54730    u.am.pDest->enc = encoding;
54731  }else{
54732    if( pOp->p4type==P4_MEM ){
54733      sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
54734    }else{
54735      assert( u.am.pDest->flags&MEM_Null );
54736    }
54737  }
54738
54739  /* If we dynamically allocated space to hold the data (in the
54740  ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
54741  ** dynamically allocated space over to the u.am.pDest structure.
54742  ** This prevents a memory copy.
54743  */
54744  if( u.am.sMem.zMalloc ){
54745    assert( u.am.sMem.z==u.am.sMem.zMalloc );
54746    assert( !(u.am.pDest->flags & MEM_Dyn) );
54747    assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
54748    u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
54749    u.am.pDest->flags |= MEM_Term;
54750    u.am.pDest->z = u.am.sMem.z;
54751    u.am.pDest->zMalloc = u.am.sMem.zMalloc;
54752  }
54753
54754  rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
54755
54756op_column_out:
54757  UPDATE_MAX_BLOBSIZE(u.am.pDest);
54758  REGISTER_TRACE(pOp->p3, u.am.pDest);
54759  break;
54760}
54761
54762/* Opcode: Affinity P1 P2 * P4 *
54763**
54764** Apply affinities to a range of P2 registers starting with P1.
54765**
54766** P4 is a string that is P2 characters long. The nth character of the
54767** string indicates the column affinity that should be used for the nth
54768** memory cell in the range.
54769*/
54770case OP_Affinity: {
54771#if 0  /* local variables moved into u.an */
54772  const char *zAffinity;   /* The affinity to be applied */
54773  char cAff;               /* A single character of affinity */
54774#endif /* local variables moved into u.an */
54775
54776  u.an.zAffinity = pOp->p4.z;
54777  assert( u.an.zAffinity!=0 );
54778  assert( u.an.zAffinity[pOp->p2]==0 );
54779  pIn1 = &aMem[pOp->p1];
54780  while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
54781    assert( pIn1 <= &p->aMem[p->nMem] );
54782    ExpandBlob(pIn1);
54783    applyAffinity(pIn1, u.an.cAff, encoding);
54784    pIn1++;
54785  }
54786  break;
54787}
54788
54789/* Opcode: MakeRecord P1 P2 P3 P4 *
54790**
54791** Convert P2 registers beginning with P1 into a single entry
54792** suitable for use as a data record in a database table or as a key
54793** in an index.  The details of the format are irrelevant as long as
54794** the OP_Column opcode can decode the record later.
54795** Refer to source code comments for the details of the record
54796** format.
54797**
54798** P4 may be a string that is P2 characters long.  The nth character of the
54799** string indicates the column affinity that should be used for the nth
54800** field of the index key.
54801**
54802** The mapping from character to affinity is given by the SQLITE_AFF_
54803** macros defined in sqliteInt.h.
54804**
54805** If P4 is NULL then all index fields have the affinity NONE.
54806*/
54807case OP_MakeRecord: {
54808#if 0  /* local variables moved into u.ao */
54809  u8 *zNewRecord;        /* A buffer to hold the data for the new record */
54810  Mem *pRec;             /* The new record */
54811  u64 nData;             /* Number of bytes of data space */
54812  int nHdr;              /* Number of bytes of header space */
54813  i64 nByte;             /* Data space required for this record */
54814  int nZero;             /* Number of zero bytes at the end of the record */
54815  int nVarint;           /* Number of bytes in a varint */
54816  u32 serial_type;       /* Type field */
54817  Mem *pData0;           /* First field to be combined into the record */
54818  Mem *pLast;            /* Last field of the record */
54819  int nField;            /* Number of fields in the record */
54820  char *zAffinity;       /* The affinity string for the record */
54821  int file_format;       /* File format to use for encoding */
54822  int i;                 /* Space used in zNewRecord[] */
54823  int len;               /* Length of a field */
54824#endif /* local variables moved into u.ao */
54825
54826  /* Assuming the record contains N fields, the record format looks
54827  ** like this:
54828  **
54829  ** ------------------------------------------------------------------------
54830  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
54831  ** ------------------------------------------------------------------------
54832  **
54833  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
54834  ** and so froth.
54835  **
54836  ** Each type field is a varint representing the serial type of the
54837  ** corresponding data element (see sqlite3VdbeSerialType()). The
54838  ** hdr-size field is also a varint which is the offset from the beginning
54839  ** of the record to data0.
54840  */
54841  u.ao.nData = 0;         /* Number of bytes of data space */
54842  u.ao.nHdr = 0;          /* Number of bytes of header space */
54843  u.ao.nByte = 0;         /* Data space required for this record */
54844  u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
54845  u.ao.nField = pOp->p1;
54846  u.ao.zAffinity = pOp->p4.z;
54847  assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
54848  u.ao.pData0 = &aMem[u.ao.nField];
54849  u.ao.nField = pOp->p2;
54850  u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
54851  u.ao.file_format = p->minWriteFileFormat;
54852
54853  /* Loop through the elements that will make up the record to figure
54854  ** out how much space is required for the new record.
54855  */
54856  for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
54857    if( u.ao.zAffinity ){
54858      applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
54859    }
54860    if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
54861      sqlite3VdbeMemExpandBlob(u.ao.pRec);
54862    }
54863    u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
54864    u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
54865    u.ao.nData += u.ao.len;
54866    u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
54867    if( u.ao.pRec->flags & MEM_Zero ){
54868      /* Only pure zero-filled BLOBs can be input to this Opcode.
54869      ** We do not allow blobs with a prefix and a zero-filled tail. */
54870      u.ao.nZero += u.ao.pRec->u.nZero;
54871    }else if( u.ao.len ){
54872      u.ao.nZero = 0;
54873    }
54874  }
54875
54876  /* Add the initial header varint and total the size */
54877  u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
54878  if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
54879    u.ao.nHdr++;
54880  }
54881  u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
54882  if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
54883    goto too_big;
54884  }
54885
54886  /* Make sure the output register has a buffer large enough to store
54887  ** the new record. The output register (pOp->p3) is not allowed to
54888  ** be one of the input registers (because the following call to
54889  ** sqlite3VdbeMemGrow() could clobber the value before it is used).
54890  */
54891  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
54892  pOut = &aMem[pOp->p3];
54893  if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
54894    goto no_mem;
54895  }
54896  u.ao.zNewRecord = (u8 *)pOut->z;
54897
54898  /* Write the record */
54899  u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
54900  for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
54901    u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
54902    u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
54903  }
54904  for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
54905    u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
54906  }
54907  assert( u.ao.i==u.ao.nByte );
54908
54909  assert( pOp->p3>0 && pOp->p3<=p->nMem );
54910  pOut->n = (int)u.ao.nByte;
54911  pOut->flags = MEM_Blob | MEM_Dyn;
54912  pOut->xDel = 0;
54913  if( u.ao.nZero ){
54914    pOut->u.nZero = u.ao.nZero;
54915    pOut->flags |= MEM_Zero;
54916  }
54917  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
54918  REGISTER_TRACE(pOp->p3, pOut);
54919  UPDATE_MAX_BLOBSIZE(pOut);
54920  break;
54921}
54922
54923/* Opcode: Count P1 P2 * * *
54924**
54925** Store the number of entries (an integer value) in the table or index
54926** opened by cursor P1 in register P2
54927*/
54928#ifndef SQLITE_OMIT_BTREECOUNT
54929case OP_Count: {         /* out2-prerelease */
54930#if 0  /* local variables moved into u.ap */
54931  i64 nEntry;
54932  BtCursor *pCrsr;
54933#endif /* local variables moved into u.ap */
54934
54935  u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
54936  if( u.ap.pCrsr ){
54937    rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
54938  }else{
54939    u.ap.nEntry = 0;
54940  }
54941  pOut->u.i = u.ap.nEntry;
54942  break;
54943}
54944#endif
54945
54946/* Opcode: Savepoint P1 * * P4 *
54947**
54948** Open, release or rollback the savepoint named by parameter P4, depending
54949** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
54950** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
54951*/
54952case OP_Savepoint: {
54953#if 0  /* local variables moved into u.aq */
54954  int p1;                         /* Value of P1 operand */
54955  char *zName;                    /* Name of savepoint */
54956  int nName;
54957  Savepoint *pNew;
54958  Savepoint *pSavepoint;
54959  Savepoint *pTmp;
54960  int iSavepoint;
54961  int ii;
54962#endif /* local variables moved into u.aq */
54963
54964  u.aq.p1 = pOp->p1;
54965  u.aq.zName = pOp->p4.z;
54966
54967  /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
54968  ** transaction, then there cannot be any savepoints.
54969  */
54970  assert( db->pSavepoint==0 || db->autoCommit==0 );
54971  assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
54972  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
54973  assert( checkSavepointCount(db) );
54974
54975  if( u.aq.p1==SAVEPOINT_BEGIN ){
54976    if( db->writeVdbeCnt>0 ){
54977      /* A new savepoint cannot be created if there are active write
54978      ** statements (i.e. open read/write incremental blob handles).
54979      */
54980      sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
54981        "SQL statements in progress");
54982      rc = SQLITE_BUSY;
54983    }else{
54984      u.aq.nName = sqlite3Strlen30(u.aq.zName);
54985
54986      /* Create a new savepoint structure. */
54987      u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
54988      if( u.aq.pNew ){
54989        u.aq.pNew->zName = (char *)&u.aq.pNew[1];
54990        memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
54991
54992        /* If there is no open transaction, then mark this as a special
54993        ** "transaction savepoint". */
54994        if( db->autoCommit ){
54995          db->autoCommit = 0;
54996          db->isTransactionSavepoint = 1;
54997        }else{
54998          db->nSavepoint++;
54999        }
55000
55001        /* Link the new savepoint into the database handle's list. */
55002        u.aq.pNew->pNext = db->pSavepoint;
55003        db->pSavepoint = u.aq.pNew;
55004        u.aq.pNew->nDeferredCons = db->nDeferredCons;
55005      }
55006    }
55007  }else{
55008    u.aq.iSavepoint = 0;
55009
55010    /* Find the named savepoint. If there is no such savepoint, then an
55011    ** an error is returned to the user.  */
55012    for(
55013      u.aq.pSavepoint = db->pSavepoint;
55014      u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
55015      u.aq.pSavepoint = u.aq.pSavepoint->pNext
55016    ){
55017      u.aq.iSavepoint++;
55018    }
55019    if( !u.aq.pSavepoint ){
55020      sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
55021      rc = SQLITE_ERROR;
55022    }else if(
55023        db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
55024    ){
55025      /* It is not possible to release (commit) a savepoint if there are
55026      ** active write statements. It is not possible to rollback a savepoint
55027      ** if there are any active statements at all.
55028      */
55029      sqlite3SetString(&p->zErrMsg, db,
55030        "cannot %s savepoint - SQL statements in progress",
55031        (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
55032      );
55033      rc = SQLITE_BUSY;
55034    }else{
55035
55036      /* Determine whether or not this is a transaction savepoint. If so,
55037      ** and this is a RELEASE command, then the current transaction
55038      ** is committed.
55039      */
55040      int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
55041      if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
55042        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
55043          goto vdbe_return;
55044        }
55045        db->autoCommit = 1;
55046        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
55047          p->pc = pc;
55048          db->autoCommit = 0;
55049          p->rc = rc = SQLITE_BUSY;
55050          goto vdbe_return;
55051        }
55052        db->isTransactionSavepoint = 0;
55053        rc = p->rc;
55054      }else{
55055        u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
55056        for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
55057          rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
55058          if( rc!=SQLITE_OK ){
55059            goto abort_due_to_error;
55060          }
55061        }
55062        if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
55063          sqlite3ExpirePreparedStatements(db);
55064          sqlite3ResetInternalSchema(db, 0);
55065        }
55066      }
55067
55068      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
55069      ** savepoints nested inside of the savepoint being operated on. */
55070      while( db->pSavepoint!=u.aq.pSavepoint ){
55071        u.aq.pTmp = db->pSavepoint;
55072        db->pSavepoint = u.aq.pTmp->pNext;
55073        sqlite3DbFree(db, u.aq.pTmp);
55074        db->nSavepoint--;
55075      }
55076
55077      /* If it is a RELEASE, then destroy the savepoint being operated on
55078      ** too. If it is a ROLLBACK TO, then set the number of deferred
55079      ** constraint violations present in the database to the value stored
55080      ** when the savepoint was created.  */
55081      if( u.aq.p1==SAVEPOINT_RELEASE ){
55082        assert( u.aq.pSavepoint==db->pSavepoint );
55083        db->pSavepoint = u.aq.pSavepoint->pNext;
55084        sqlite3DbFree(db, u.aq.pSavepoint);
55085        if( !isTransaction ){
55086          db->nSavepoint--;
55087        }
55088      }else{
55089        db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
55090      }
55091    }
55092  }
55093
55094  break;
55095}
55096
55097/* Opcode: AutoCommit P1 P2 * * *
55098**
55099** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
55100** back any currently active btree transactions. If there are any active
55101** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
55102** there are active writing VMs or active VMs that use shared cache.
55103**
55104** This instruction causes the VM to halt.
55105*/
55106case OP_AutoCommit: {
55107#if 0  /* local variables moved into u.ar */
55108  int desiredAutoCommit;
55109  int iRollback;
55110  int turnOnAC;
55111#endif /* local variables moved into u.ar */
55112
55113  u.ar.desiredAutoCommit = pOp->p1;
55114  u.ar.iRollback = pOp->p2;
55115  u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
55116  assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
55117  assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
55118  assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
55119
55120  if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
55121    /* If this instruction implements a ROLLBACK and other VMs are
55122    ** still running, and a transaction is active, return an error indicating
55123    ** that the other VMs must complete first.
55124    */
55125    sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
55126        "SQL statements in progress");
55127    rc = SQLITE_BUSY;
55128  }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
55129    /* If this instruction implements a COMMIT and other VMs are writing
55130    ** return an error indicating that the other VMs must complete first.
55131    */
55132    sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
55133        "SQL statements in progress");
55134    rc = SQLITE_BUSY;
55135  }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
55136    if( u.ar.iRollback ){
55137      assert( u.ar.desiredAutoCommit==1 );
55138      sqlite3RollbackAll(db);
55139      db->autoCommit = 1;
55140    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
55141      goto vdbe_return;
55142    }else{
55143      db->autoCommit = (u8)u.ar.desiredAutoCommit;
55144      if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
55145        p->pc = pc;
55146        db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
55147        p->rc = rc = SQLITE_BUSY;
55148        goto vdbe_return;
55149      }
55150    }
55151    assert( db->nStatement==0 );
55152    sqlite3CloseSavepoints(db);
55153    if( p->rc==SQLITE_OK ){
55154      rc = SQLITE_DONE;
55155    }else{
55156      rc = SQLITE_ERROR;
55157    }
55158    goto vdbe_return;
55159  }else{
55160    sqlite3SetString(&p->zErrMsg, db,
55161        (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
55162        (u.ar.iRollback)?"cannot rollback - no transaction is active":
55163                   "cannot commit - no transaction is active"));
55164
55165    rc = SQLITE_ERROR;
55166  }
55167  break;
55168}
55169
55170/* Opcode: Transaction P1 P2 * * *
55171**
55172** Begin a transaction.  The transaction ends when a Commit or Rollback
55173** opcode is encountered.  Depending on the ON CONFLICT setting, the
55174** transaction might also be rolled back if an error is encountered.
55175**
55176** P1 is the index of the database file on which the transaction is
55177** started.  Index 0 is the main database file and index 1 is the
55178** file used for temporary tables.  Indices of 2 or more are used for
55179** attached databases.
55180**
55181** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
55182** obtained on the database file when a write-transaction is started.  No
55183** other process can start another write transaction while this transaction is
55184** underway.  Starting a write transaction also creates a rollback journal. A
55185** write transaction must be started before any changes can be made to the
55186** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
55187** on the file.
55188**
55189** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
55190** true (this flag is set if the Vdbe may modify more than one row and may
55191** throw an ABORT exception), a statement transaction may also be opened.
55192** More specifically, a statement transaction is opened iff the database
55193** connection is currently not in autocommit mode, or if there are other
55194** active statements. A statement transaction allows the affects of this
55195** VDBE to be rolled back after an error without having to roll back the
55196** entire transaction. If no error is encountered, the statement transaction
55197** will automatically commit when the VDBE halts.
55198**
55199** If P2 is zero, then a read-lock is obtained on the database file.
55200*/
55201case OP_Transaction: {
55202#if 0  /* local variables moved into u.as */
55203  Btree *pBt;
55204#endif /* local variables moved into u.as */
55205
55206  assert( pOp->p1>=0 && pOp->p1<db->nDb );
55207  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
55208  u.as.pBt = db->aDb[pOp->p1].pBt;
55209
55210  if( u.as.pBt ){
55211    rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
55212    if( rc==SQLITE_BUSY ){
55213      p->pc = pc;
55214      p->rc = rc = SQLITE_BUSY;
55215      goto vdbe_return;
55216    }
55217    if( rc!=SQLITE_OK ){
55218      goto abort_due_to_error;
55219    }
55220
55221    if( pOp->p2 && p->usesStmtJournal
55222     && (db->autoCommit==0 || db->activeVdbeCnt>1)
55223    ){
55224      assert( sqlite3BtreeIsInTrans(u.as.pBt) );
55225      if( p->iStatement==0 ){
55226        assert( db->nStatement>=0 && db->nSavepoint>=0 );
55227        db->nStatement++;
55228        p->iStatement = db->nSavepoint + db->nStatement;
55229      }
55230      rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
55231
55232      /* Store the current value of the database handles deferred constraint
55233      ** counter. If the statement transaction needs to be rolled back,
55234      ** the value of this counter needs to be restored too.  */
55235      p->nStmtDefCons = db->nDeferredCons;
55236    }
55237  }
55238  break;
55239}
55240
55241/* Opcode: ReadCookie P1 P2 P3 * *
55242**
55243** Read cookie number P3 from database P1 and write it into register P2.
55244** P3==1 is the schema version.  P3==2 is the database format.
55245** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
55246** the main database file and P1==1 is the database file used to store
55247** temporary tables.
55248**
55249** There must be a read-lock on the database (either a transaction
55250** must be started or there must be an open cursor) before
55251** executing this instruction.
55252*/
55253case OP_ReadCookie: {               /* out2-prerelease */
55254#if 0  /* local variables moved into u.at */
55255  int iMeta;
55256  int iDb;
55257  int iCookie;
55258#endif /* local variables moved into u.at */
55259
55260  u.at.iDb = pOp->p1;
55261  u.at.iCookie = pOp->p3;
55262  assert( pOp->p3<SQLITE_N_BTREE_META );
55263  assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
55264  assert( db->aDb[u.at.iDb].pBt!=0 );
55265  assert( (p->btreeMask & (1<<u.at.iDb))!=0 );
55266
55267  sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
55268  pOut->u.i = u.at.iMeta;
55269  break;
55270}
55271
55272/* Opcode: SetCookie P1 P2 P3 * *
55273**
55274** Write the content of register P3 (interpreted as an integer)
55275** into cookie number P2 of database P1.  P2==1 is the schema version.
55276** P2==2 is the database format. P2==3 is the recommended pager cache
55277** size, and so forth.  P1==0 is the main database file and P1==1 is the
55278** database file used to store temporary tables.
55279**
55280** A transaction must be started before executing this opcode.
55281*/
55282case OP_SetCookie: {       /* in3 */
55283#if 0  /* local variables moved into u.au */
55284  Db *pDb;
55285#endif /* local variables moved into u.au */
55286  assert( pOp->p2<SQLITE_N_BTREE_META );
55287  assert( pOp->p1>=0 && pOp->p1<db->nDb );
55288  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
55289  u.au.pDb = &db->aDb[pOp->p1];
55290  assert( u.au.pDb->pBt!=0 );
55291  pIn3 = &aMem[pOp->p3];
55292  sqlite3VdbeMemIntegerify(pIn3);
55293  /* See note about index shifting on OP_ReadCookie */
55294  rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
55295  if( pOp->p2==BTREE_SCHEMA_VERSION ){
55296    /* When the schema cookie changes, record the new cookie internally */
55297    u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
55298    db->flags |= SQLITE_InternChanges;
55299  }else if( pOp->p2==BTREE_FILE_FORMAT ){
55300    /* Record changes in the file format */
55301    u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
55302  }
55303  if( pOp->p1==1 ){
55304    /* Invalidate all prepared statements whenever the TEMP database
55305    ** schema is changed.  Ticket #1644 */
55306    sqlite3ExpirePreparedStatements(db);
55307    p->expired = 0;
55308  }
55309  break;
55310}
55311
55312/* Opcode: VerifyCookie P1 P2 *
55313**
55314** Check the value of global database parameter number 0 (the
55315** schema version) and make sure it is equal to P2.
55316** P1 is the database number which is 0 for the main database file
55317** and 1 for the file holding temporary tables and some higher number
55318** for auxiliary databases.
55319**
55320** The cookie changes its value whenever the database schema changes.
55321** This operation is used to detect when that the cookie has changed
55322** and that the current process needs to reread the schema.
55323**
55324** Either a transaction needs to have been started or an OP_Open needs
55325** to be executed (to establish a read lock) before this opcode is
55326** invoked.
55327*/
55328case OP_VerifyCookie: {
55329#if 0  /* local variables moved into u.av */
55330  int iMeta;
55331  Btree *pBt;
55332#endif /* local variables moved into u.av */
55333  assert( pOp->p1>=0 && pOp->p1<db->nDb );
55334  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
55335  u.av.pBt = db->aDb[pOp->p1].pBt;
55336  if( u.av.pBt ){
55337    sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
55338  }else{
55339    u.av.iMeta = 0;
55340  }
55341  if( u.av.iMeta!=pOp->p2 ){
55342    sqlite3DbFree(db, p->zErrMsg);
55343    p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
55344    /* If the schema-cookie from the database file matches the cookie
55345    ** stored with the in-memory representation of the schema, do
55346    ** not reload the schema from the database file.
55347    **
55348    ** If virtual-tables are in use, this is not just an optimization.
55349    ** Often, v-tables store their data in other SQLite tables, which
55350    ** are queried from within xNext() and other v-table methods using
55351    ** prepared queries. If such a query is out-of-date, we do not want to
55352    ** discard the database schema, as the user code implementing the
55353    ** v-table would have to be ready for the sqlite3_vtab structure itself
55354    ** to be invalidated whenever sqlite3_step() is called from within
55355    ** a v-table method.
55356    */
55357    if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
55358      sqlite3ResetInternalSchema(db, pOp->p1);
55359    }
55360
55361    sqlite3ExpirePreparedStatements(db);
55362    rc = SQLITE_SCHEMA;
55363  }
55364  break;
55365}
55366
55367/* Opcode: OpenRead P1 P2 P3 P4 P5
55368**
55369** Open a read-only cursor for the database table whose root page is
55370** P2 in a database file.  The database file is determined by P3.
55371** P3==0 means the main database, P3==1 means the database used for
55372** temporary tables, and P3>1 means used the corresponding attached
55373** database.  Give the new cursor an identifier of P1.  The P1
55374** values need not be contiguous but all P1 values should be small integers.
55375** It is an error for P1 to be negative.
55376**
55377** If P5!=0 then use the content of register P2 as the root page, not
55378** the value of P2 itself.
55379**
55380** There will be a read lock on the database whenever there is an
55381** open cursor.  If the database was unlocked prior to this instruction
55382** then a read lock is acquired as part of this instruction.  A read
55383** lock allows other processes to read the database but prohibits
55384** any other process from modifying the database.  The read lock is
55385** released when all cursors are closed.  If this instruction attempts
55386** to get a read lock but fails, the script terminates with an
55387** SQLITE_BUSY error code.
55388**
55389** The P4 value may be either an integer (P4_INT32) or a pointer to
55390** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
55391** structure, then said structure defines the content and collating
55392** sequence of the index being opened. Otherwise, if P4 is an integer
55393** value, it is set to the number of columns in the table.
55394**
55395** See also OpenWrite.
55396*/
55397/* Opcode: OpenWrite P1 P2 P3 P4 P5
55398**
55399** Open a read/write cursor named P1 on the table or index whose root
55400** page is P2.  Or if P5!=0 use the content of register P2 to find the
55401** root page.
55402**
55403** The P4 value may be either an integer (P4_INT32) or a pointer to
55404** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
55405** structure, then said structure defines the content and collating
55406** sequence of the index being opened. Otherwise, if P4 is an integer
55407** value, it is set to the number of columns in the table, or to the
55408** largest index of any column of the table that is actually used.
55409**
55410** This instruction works just like OpenRead except that it opens the cursor
55411** in read/write mode.  For a given table, there can be one or more read-only
55412** cursors or a single read/write cursor but not both.
55413**
55414** See also OpenRead.
55415*/
55416case OP_OpenRead:
55417case OP_OpenWrite: {
55418#if 0  /* local variables moved into u.aw */
55419  int nField;
55420  KeyInfo *pKeyInfo;
55421  int p2;
55422  int iDb;
55423  int wrFlag;
55424  Btree *pX;
55425  VdbeCursor *pCur;
55426  Db *pDb;
55427#endif /* local variables moved into u.aw */
55428
55429  if( p->expired ){
55430    rc = SQLITE_ABORT;
55431    break;
55432  }
55433
55434  u.aw.nField = 0;
55435  u.aw.pKeyInfo = 0;
55436  u.aw.p2 = pOp->p2;
55437  u.aw.iDb = pOp->p3;
55438  assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
55439  assert( (p->btreeMask & (1<<u.aw.iDb))!=0 );
55440  u.aw.pDb = &db->aDb[u.aw.iDb];
55441  u.aw.pX = u.aw.pDb->pBt;
55442  assert( u.aw.pX!=0 );
55443  if( pOp->opcode==OP_OpenWrite ){
55444    u.aw.wrFlag = 1;
55445    if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
55446      p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
55447    }
55448  }else{
55449    u.aw.wrFlag = 0;
55450  }
55451  if( pOp->p5 ){
55452    assert( u.aw.p2>0 );
55453    assert( u.aw.p2<=p->nMem );
55454    pIn2 = &aMem[u.aw.p2];
55455    sqlite3VdbeMemIntegerify(pIn2);
55456    u.aw.p2 = (int)pIn2->u.i;
55457    /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
55458    ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
55459    ** If there were a failure, the prepared statement would have halted
55460    ** before reaching this instruction. */
55461    if( NEVER(u.aw.p2<2) ) {
55462      rc = SQLITE_CORRUPT_BKPT;
55463      goto abort_due_to_error;
55464    }
55465  }
55466  if( pOp->p4type==P4_KEYINFO ){
55467    u.aw.pKeyInfo = pOp->p4.pKeyInfo;
55468    u.aw.pKeyInfo->enc = ENC(p->db);
55469    u.aw.nField = u.aw.pKeyInfo->nField+1;
55470  }else if( pOp->p4type==P4_INT32 ){
55471    u.aw.nField = pOp->p4.i;
55472  }
55473  assert( pOp->p1>=0 );
55474  u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
55475  if( u.aw.pCur==0 ) goto no_mem;
55476  u.aw.pCur->nullRow = 1;
55477  rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
55478  u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
55479
55480  /* Since it performs no memory allocation or IO, the only values that
55481  ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
55482  ** SQLITE_EMPTY is only returned when attempting to open the table
55483  ** rooted at page 1 of a zero-byte database.  */
55484  assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
55485  if( rc==SQLITE_EMPTY ){
55486    u.aw.pCur->pCursor = 0;
55487    rc = SQLITE_OK;
55488  }
55489
55490  /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
55491  ** SQLite used to check if the root-page flags were sane at this point
55492  ** and report database corruption if they were not, but this check has
55493  ** since moved into the btree layer.  */
55494  u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
55495  u.aw.pCur->isIndex = !u.aw.pCur->isTable;
55496  break;
55497}
55498
55499/* Opcode: OpenEphemeral P1 P2 * P4 *
55500**
55501** Open a new cursor P1 to a transient table.
55502** The cursor is always opened read/write even if
55503** the main database is read-only.  The transient or virtual
55504** table is deleted automatically when the cursor is closed.
55505**
55506** P2 is the number of columns in the virtual table.
55507** The cursor points to a BTree table if P4==0 and to a BTree index
55508** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
55509** that defines the format of keys in the index.
55510**
55511** This opcode was once called OpenTemp.  But that created
55512** confusion because the term "temp table", might refer either
55513** to a TEMP table at the SQL level, or to a table opened by
55514** this opcode.  Then this opcode was call OpenVirtual.  But
55515** that created confusion with the whole virtual-table idea.
55516*/
55517case OP_OpenEphemeral: {
55518#if 0  /* local variables moved into u.ax */
55519  VdbeCursor *pCx;
55520#endif /* local variables moved into u.ax */
55521  static const int openFlags =
55522      SQLITE_OPEN_READWRITE |
55523      SQLITE_OPEN_CREATE |
55524      SQLITE_OPEN_EXCLUSIVE |
55525      SQLITE_OPEN_DELETEONCLOSE |
55526      SQLITE_OPEN_TRANSIENT_DB;
55527
55528  assert( pOp->p1>=0 );
55529  u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
55530  if( u.ax.pCx==0 ) goto no_mem;
55531  u.ax.pCx->nullRow = 1;
55532  rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
55533                           &u.ax.pCx->pBt);
55534  if( rc==SQLITE_OK ){
55535    rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
55536  }
55537  if( rc==SQLITE_OK ){
55538    /* If a transient index is required, create it by calling
55539    ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
55540    ** opening it. If a transient table is required, just use the
55541    ** automatically created table with root-page 1 (an INTKEY table).
55542    */
55543    if( pOp->p4.pKeyInfo ){
55544      int pgno;
55545      assert( pOp->p4type==P4_KEYINFO );
55546      rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_ZERODATA);
55547      if( rc==SQLITE_OK ){
55548        assert( pgno==MASTER_ROOT+1 );
55549        rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
55550                                (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
55551        u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
55552        u.ax.pCx->pKeyInfo->enc = ENC(p->db);
55553      }
55554      u.ax.pCx->isTable = 0;
55555    }else{
55556      rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
55557      u.ax.pCx->isTable = 1;
55558    }
55559  }
55560  u.ax.pCx->isIndex = !u.ax.pCx->isTable;
55561  break;
55562}
55563
55564/* Opcode: OpenPseudo P1 P2 P3 * *
55565**
55566** Open a new cursor that points to a fake table that contains a single
55567** row of data.  The content of that one row in the content of memory
55568** register P2.  In other words, cursor P1 becomes an alias for the
55569** MEM_Blob content contained in register P2.
55570**
55571** A pseudo-table created by this opcode is used to hold the a single
55572** row output from the sorter so that the row can be decomposed into
55573** individual columns using the OP_Column opcode.  The OP_Column opcode
55574** is the only cursor opcode that works with a pseudo-table.
55575**
55576** P3 is the number of fields in the records that will be stored by
55577** the pseudo-table.
55578*/
55579case OP_OpenPseudo: {
55580#if 0  /* local variables moved into u.ay */
55581  VdbeCursor *pCx;
55582#endif /* local variables moved into u.ay */
55583
55584  assert( pOp->p1>=0 );
55585  u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
55586  if( u.ay.pCx==0 ) goto no_mem;
55587  u.ay.pCx->nullRow = 1;
55588  u.ay.pCx->pseudoTableReg = pOp->p2;
55589  u.ay.pCx->isTable = 1;
55590  u.ay.pCx->isIndex = 0;
55591  break;
55592}
55593
55594/* Opcode: Close P1 * * * *
55595**
55596** Close a cursor previously opened as P1.  If P1 is not
55597** currently open, this instruction is a no-op.
55598*/
55599case OP_Close: {
55600  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55601  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
55602  p->apCsr[pOp->p1] = 0;
55603  break;
55604}
55605
55606/* Opcode: SeekGe P1 P2 P3 P4 *
55607**
55608** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
55609** use the value in register P3 as the key.  If cursor P1 refers
55610** to an SQL index, then P3 is the first in an array of P4 registers
55611** that are used as an unpacked index key.
55612**
55613** Reposition cursor P1 so that  it points to the smallest entry that
55614** is greater than or equal to the key value. If there are no records
55615** greater than or equal to the key and P2 is not zero, then jump to P2.
55616**
55617** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
55618*/
55619/* Opcode: SeekGt P1 P2 P3 P4 *
55620**
55621** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
55622** use the value in register P3 as a key. If cursor P1 refers
55623** to an SQL index, then P3 is the first in an array of P4 registers
55624** that are used as an unpacked index key.
55625**
55626** Reposition cursor P1 so that  it points to the smallest entry that
55627** is greater than the key value. If there are no records greater than
55628** the key and P2 is not zero, then jump to P2.
55629**
55630** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
55631*/
55632/* Opcode: SeekLt P1 P2 P3 P4 *
55633**
55634** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
55635** use the value in register P3 as a key. If cursor P1 refers
55636** to an SQL index, then P3 is the first in an array of P4 registers
55637** that are used as an unpacked index key.
55638**
55639** Reposition cursor P1 so that  it points to the largest entry that
55640** is less than the key value. If there are no records less than
55641** the key and P2 is not zero, then jump to P2.
55642**
55643** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
55644*/
55645/* Opcode: SeekLe P1 P2 P3 P4 *
55646**
55647** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
55648** use the value in register P3 as a key. If cursor P1 refers
55649** to an SQL index, then P3 is the first in an array of P4 registers
55650** that are used as an unpacked index key.
55651**
55652** Reposition cursor P1 so that it points to the largest entry that
55653** is less than or equal to the key value. If there are no records
55654** less than or equal to the key and P2 is not zero, then jump to P2.
55655**
55656** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
55657*/
55658case OP_SeekLt:         /* jump, in3 */
55659case OP_SeekLe:         /* jump, in3 */
55660case OP_SeekGe:         /* jump, in3 */
55661case OP_SeekGt: {       /* jump, in3 */
55662#if 0  /* local variables moved into u.az */
55663  int res;
55664  int oc;
55665  VdbeCursor *pC;
55666  UnpackedRecord r;
55667  int nField;
55668  i64 iKey;      /* The rowid we are to seek to */
55669#endif /* local variables moved into u.az */
55670
55671  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55672  assert( pOp->p2!=0 );
55673  u.az.pC = p->apCsr[pOp->p1];
55674  assert( u.az.pC!=0 );
55675  assert( u.az.pC->pseudoTableReg==0 );
55676  assert( OP_SeekLe == OP_SeekLt+1 );
55677  assert( OP_SeekGe == OP_SeekLt+2 );
55678  assert( OP_SeekGt == OP_SeekLt+3 );
55679  if( u.az.pC->pCursor!=0 ){
55680    u.az.oc = pOp->opcode;
55681    u.az.pC->nullRow = 0;
55682    if( u.az.pC->isTable ){
55683      /* The input value in P3 might be of any type: integer, real, string,
55684      ** blob, or NULL.  But it needs to be an integer before we can do
55685      ** the seek, so covert it. */
55686      pIn3 = &aMem[pOp->p3];
55687      applyNumericAffinity(pIn3);
55688      u.az.iKey = sqlite3VdbeIntValue(pIn3);
55689      u.az.pC->rowidIsValid = 0;
55690
55691      /* If the P3 value could not be converted into an integer without
55692      ** loss of information, then special processing is required... */
55693      if( (pIn3->flags & MEM_Int)==0 ){
55694        if( (pIn3->flags & MEM_Real)==0 ){
55695          /* If the P3 value cannot be converted into any kind of a number,
55696          ** then the seek is not possible, so jump to P2 */
55697          pc = pOp->p2 - 1;
55698          break;
55699        }
55700        /* If we reach this point, then the P3 value must be a floating
55701        ** point number. */
55702        assert( (pIn3->flags & MEM_Real)!=0 );
55703
55704        if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
55705          /* The P3 value is too large in magnitude to be expressed as an
55706          ** integer. */
55707          u.az.res = 1;
55708          if( pIn3->r<0 ){
55709            if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
55710              rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
55711              if( rc!=SQLITE_OK ) goto abort_due_to_error;
55712            }
55713          }else{
55714            if( u.az.oc<=OP_SeekLe ){  assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
55715              rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
55716              if( rc!=SQLITE_OK ) goto abort_due_to_error;
55717            }
55718          }
55719          if( u.az.res ){
55720            pc = pOp->p2 - 1;
55721          }
55722          break;
55723        }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
55724          /* Use the ceiling() function to convert real->int */
55725          if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
55726        }else{
55727          /* Use the floor() function to convert real->int */
55728          assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
55729          if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
55730        }
55731      }
55732      rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
55733      if( rc!=SQLITE_OK ){
55734        goto abort_due_to_error;
55735      }
55736      if( u.az.res==0 ){
55737        u.az.pC->rowidIsValid = 1;
55738        u.az.pC->lastRowid = u.az.iKey;
55739      }
55740    }else{
55741      u.az.nField = pOp->p4.i;
55742      assert( pOp->p4type==P4_INT32 );
55743      assert( u.az.nField>0 );
55744      u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
55745      u.az.r.nField = (u16)u.az.nField;
55746
55747      /* The next line of code computes as follows, only faster:
55748      **   if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
55749      **     u.az.r.flags = UNPACKED_INCRKEY;
55750      **   }else{
55751      **     u.az.r.flags = 0;
55752      **   }
55753      */
55754      u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
55755      assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
55756      assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
55757      assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
55758      assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
55759
55760      u.az.r.aMem = &aMem[pOp->p3];
55761      ExpandBlob(u.az.r.aMem);
55762      rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
55763      if( rc!=SQLITE_OK ){
55764        goto abort_due_to_error;
55765      }
55766      u.az.pC->rowidIsValid = 0;
55767    }
55768    u.az.pC->deferredMoveto = 0;
55769    u.az.pC->cacheStatus = CACHE_STALE;
55770#ifdef SQLITE_TEST
55771    sqlite3_search_count++;
55772#endif
55773    if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
55774      if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
55775        rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
55776        if( rc!=SQLITE_OK ) goto abort_due_to_error;
55777        u.az.pC->rowidIsValid = 0;
55778      }else{
55779        u.az.res = 0;
55780      }
55781    }else{
55782      assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
55783      if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
55784        rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
55785        if( rc!=SQLITE_OK ) goto abort_due_to_error;
55786        u.az.pC->rowidIsValid = 0;
55787      }else{
55788        /* u.az.res might be negative because the table is empty.  Check to
55789        ** see if this is the case.
55790        */
55791        u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
55792      }
55793    }
55794    assert( pOp->p2>0 );
55795    if( u.az.res ){
55796      pc = pOp->p2 - 1;
55797    }
55798  }else{
55799    /* This happens when attempting to open the sqlite3_master table
55800    ** for read access returns SQLITE_EMPTY. In this case always
55801    ** take the jump (since there are no records in the table).
55802    */
55803    pc = pOp->p2 - 1;
55804  }
55805  break;
55806}
55807
55808/* Opcode: Seek P1 P2 * * *
55809**
55810** P1 is an open table cursor and P2 is a rowid integer.  Arrange
55811** for P1 to move so that it points to the rowid given by P2.
55812**
55813** This is actually a deferred seek.  Nothing actually happens until
55814** the cursor is used to read a record.  That way, if no reads
55815** occur, no unnecessary I/O happens.
55816*/
55817case OP_Seek: {    /* in2 */
55818#if 0  /* local variables moved into u.ba */
55819  VdbeCursor *pC;
55820#endif /* local variables moved into u.ba */
55821
55822  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55823  u.ba.pC = p->apCsr[pOp->p1];
55824  assert( u.ba.pC!=0 );
55825  if( ALWAYS(u.ba.pC->pCursor!=0) ){
55826    assert( u.ba.pC->isTable );
55827    u.ba.pC->nullRow = 0;
55828    pIn2 = &aMem[pOp->p2];
55829    u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
55830    u.ba.pC->rowidIsValid = 0;
55831    u.ba.pC->deferredMoveto = 1;
55832  }
55833  break;
55834}
55835
55836
55837/* Opcode: Found P1 P2 P3 P4 *
55838**
55839** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
55840** P4>0 then register P3 is the first of P4 registers that form an unpacked
55841** record.
55842**
55843** Cursor P1 is on an index btree.  If the record identified by P3 and P4
55844** is a prefix of any entry in P1 then a jump is made to P2 and
55845** P1 is left pointing at the matching entry.
55846*/
55847/* Opcode: NotFound P1 P2 P3 P4 *
55848**
55849** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
55850** P4>0 then register P3 is the first of P4 registers that form an unpacked
55851** record.
55852**
55853** Cursor P1 is on an index btree.  If the record identified by P3 and P4
55854** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
55855** does contain an entry whose prefix matches the P3/P4 record then control
55856** falls through to the next instruction and P1 is left pointing at the
55857** matching entry.
55858**
55859** See also: Found, NotExists, IsUnique
55860*/
55861case OP_NotFound:       /* jump, in3 */
55862case OP_Found: {        /* jump, in3 */
55863#if 0  /* local variables moved into u.bb */
55864  int alreadyExists;
55865  VdbeCursor *pC;
55866  int res;
55867  UnpackedRecord *pIdxKey;
55868  UnpackedRecord r;
55869  char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
55870#endif /* local variables moved into u.bb */
55871
55872#ifdef SQLITE_TEST
55873  sqlite3_found_count++;
55874#endif
55875
55876  u.bb.alreadyExists = 0;
55877  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55878  assert( pOp->p4type==P4_INT32 );
55879  u.bb.pC = p->apCsr[pOp->p1];
55880  assert( u.bb.pC!=0 );
55881  pIn3 = &aMem[pOp->p3];
55882  if( ALWAYS(u.bb.pC->pCursor!=0) ){
55883
55884    assert( u.bb.pC->isTable==0 );
55885    if( pOp->p4.i>0 ){
55886      u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
55887      u.bb.r.nField = (u16)pOp->p4.i;
55888      u.bb.r.aMem = pIn3;
55889      u.bb.r.flags = UNPACKED_PREFIX_MATCH;
55890      u.bb.pIdxKey = &u.bb.r;
55891    }else{
55892      assert( pIn3->flags & MEM_Blob );
55893      ExpandBlob(pIn3);
55894      u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
55895                                        u.bb.aTempRec, sizeof(u.bb.aTempRec));
55896      if( u.bb.pIdxKey==0 ){
55897        goto no_mem;
55898      }
55899      u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
55900    }
55901    rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
55902    if( pOp->p4.i==0 ){
55903      sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
55904    }
55905    if( rc!=SQLITE_OK ){
55906      break;
55907    }
55908    u.bb.alreadyExists = (u.bb.res==0);
55909    u.bb.pC->deferredMoveto = 0;
55910    u.bb.pC->cacheStatus = CACHE_STALE;
55911  }
55912  if( pOp->opcode==OP_Found ){
55913    if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
55914  }else{
55915    if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
55916  }
55917  break;
55918}
55919
55920/* Opcode: IsUnique P1 P2 P3 P4 *
55921**
55922** Cursor P1 is open on an index b-tree - that is to say, a btree which
55923** no data and where the key are records generated by OP_MakeRecord with
55924** the list field being the integer ROWID of the entry that the index
55925** entry refers to.
55926**
55927** The P3 register contains an integer record number. Call this record
55928** number R. Register P4 is the first in a set of N contiguous registers
55929** that make up an unpacked index key that can be used with cursor P1.
55930** The value of N can be inferred from the cursor. N includes the rowid
55931** value appended to the end of the index record. This rowid value may
55932** or may not be the same as R.
55933**
55934** If any of the N registers beginning with register P4 contains a NULL
55935** value, jump immediately to P2.
55936**
55937** Otherwise, this instruction checks if cursor P1 contains an entry
55938** where the first (N-1) fields match but the rowid value at the end
55939** of the index entry is not R. If there is no such entry, control jumps
55940** to instruction P2. Otherwise, the rowid of the conflicting index
55941** entry is copied to register P3 and control falls through to the next
55942** instruction.
55943**
55944** See also: NotFound, NotExists, Found
55945*/
55946case OP_IsUnique: {        /* jump, in3 */
55947#if 0  /* local variables moved into u.bc */
55948  u16 ii;
55949  VdbeCursor *pCx;
55950  BtCursor *pCrsr;
55951  u16 nField;
55952  Mem *aMx;
55953  UnpackedRecord r;                  /* B-Tree index search key */
55954  i64 R;                             /* Rowid stored in register P3 */
55955#endif /* local variables moved into u.bc */
55956
55957  pIn3 = &aMem[pOp->p3];
55958  u.bc.aMx = &aMem[pOp->p4.i];
55959  /* Assert that the values of parameters P1 and P4 are in range. */
55960  assert( pOp->p4type==P4_INT32 );
55961  assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
55962  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55963
55964  /* Find the index cursor. */
55965  u.bc.pCx = p->apCsr[pOp->p1];
55966  assert( u.bc.pCx->deferredMoveto==0 );
55967  u.bc.pCx->seekResult = 0;
55968  u.bc.pCx->cacheStatus = CACHE_STALE;
55969  u.bc.pCrsr = u.bc.pCx->pCursor;
55970
55971  /* If any of the values are NULL, take the jump. */
55972  u.bc.nField = u.bc.pCx->pKeyInfo->nField;
55973  for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
55974    if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
55975      pc = pOp->p2 - 1;
55976      u.bc.pCrsr = 0;
55977      break;
55978    }
55979  }
55980  assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
55981
55982  if( u.bc.pCrsr!=0 ){
55983    /* Populate the index search key. */
55984    u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
55985    u.bc.r.nField = u.bc.nField + 1;
55986    u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
55987    u.bc.r.aMem = u.bc.aMx;
55988
55989    /* Extract the value of u.bc.R from register P3. */
55990    sqlite3VdbeMemIntegerify(pIn3);
55991    u.bc.R = pIn3->u.i;
55992
55993    /* Search the B-Tree index. If no conflicting record is found, jump
55994    ** to P2. Otherwise, copy the rowid of the conflicting record to
55995    ** register P3 and fall through to the next instruction.  */
55996    rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
55997    if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
55998      pc = pOp->p2 - 1;
55999    }else{
56000      pIn3->u.i = u.bc.r.rowid;
56001    }
56002  }
56003  break;
56004}
56005
56006/* Opcode: NotExists P1 P2 P3 * *
56007**
56008** Use the content of register P3 as a integer key.  If a record
56009** with that key does not exist in table of P1, then jump to P2.
56010** If the record does exist, then fall thru.  The cursor is left
56011** pointing to the record if it exists.
56012**
56013** The difference between this operation and NotFound is that this
56014** operation assumes the key is an integer and that P1 is a table whereas
56015** NotFound assumes key is a blob constructed from MakeRecord and
56016** P1 is an index.
56017**
56018** See also: Found, NotFound, IsUnique
56019*/
56020case OP_NotExists: {        /* jump, in3 */
56021#if 0  /* local variables moved into u.bd */
56022  VdbeCursor *pC;
56023  BtCursor *pCrsr;
56024  int res;
56025  u64 iKey;
56026#endif /* local variables moved into u.bd */
56027
56028  pIn3 = &aMem[pOp->p3];
56029  assert( pIn3->flags & MEM_Int );
56030  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56031  u.bd.pC = p->apCsr[pOp->p1];
56032  assert( u.bd.pC!=0 );
56033  assert( u.bd.pC->isTable );
56034  assert( u.bd.pC->pseudoTableReg==0 );
56035  u.bd.pCrsr = u.bd.pC->pCursor;
56036  if( u.bd.pCrsr!=0 ){
56037    u.bd.res = 0;
56038    u.bd.iKey = pIn3->u.i;
56039    rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
56040    u.bd.pC->lastRowid = pIn3->u.i;
56041    u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
56042    u.bd.pC->nullRow = 0;
56043    u.bd.pC->cacheStatus = CACHE_STALE;
56044    u.bd.pC->deferredMoveto = 0;
56045    if( u.bd.res!=0 ){
56046      pc = pOp->p2 - 1;
56047      assert( u.bd.pC->rowidIsValid==0 );
56048    }
56049    u.bd.pC->seekResult = u.bd.res;
56050  }else{
56051    /* This happens when an attempt to open a read cursor on the
56052    ** sqlite_master table returns SQLITE_EMPTY.
56053    */
56054    pc = pOp->p2 - 1;
56055    assert( u.bd.pC->rowidIsValid==0 );
56056    u.bd.pC->seekResult = 0;
56057  }
56058  break;
56059}
56060
56061/* Opcode: Sequence P1 P2 * * *
56062**
56063** Find the next available sequence number for cursor P1.
56064** Write the sequence number into register P2.
56065** The sequence number on the cursor is incremented after this
56066** instruction.
56067*/
56068case OP_Sequence: {           /* out2-prerelease */
56069  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56070  assert( p->apCsr[pOp->p1]!=0 );
56071  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
56072  break;
56073}
56074
56075
56076/* Opcode: NewRowid P1 P2 P3 * *
56077**
56078** Get a new integer record number (a.k.a "rowid") used as the key to a table.
56079** The record number is not previously used as a key in the database
56080** table that cursor P1 points to.  The new record number is written
56081** written to register P2.
56082**
56083** If P3>0 then P3 is a register in the root frame of this VDBE that holds
56084** the largest previously generated record number. No new record numbers are
56085** allowed to be less than this value. When this value reaches its maximum,
56086** a SQLITE_FULL error is generated. The P3 register is updated with the '
56087** generated record number. This P3 mechanism is used to help implement the
56088** AUTOINCREMENT feature.
56089*/
56090case OP_NewRowid: {           /* out2-prerelease */
56091#if 0  /* local variables moved into u.be */
56092  i64 v;                 /* The new rowid */
56093  VdbeCursor *pC;        /* Cursor of table to get the new rowid */
56094  int res;               /* Result of an sqlite3BtreeLast() */
56095  int cnt;               /* Counter to limit the number of searches */
56096  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
56097  VdbeFrame *pFrame;     /* Root frame of VDBE */
56098#endif /* local variables moved into u.be */
56099
56100  u.be.v = 0;
56101  u.be.res = 0;
56102  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56103  u.be.pC = p->apCsr[pOp->p1];
56104  assert( u.be.pC!=0 );
56105  if( NEVER(u.be.pC->pCursor==0) ){
56106    /* The zero initialization above is all that is needed */
56107  }else{
56108    /* The next rowid or record number (different terms for the same
56109    ** thing) is obtained in a two-step algorithm.
56110    **
56111    ** First we attempt to find the largest existing rowid and add one
56112    ** to that.  But if the largest existing rowid is already the maximum
56113    ** positive integer, we have to fall through to the second
56114    ** probabilistic algorithm
56115    **
56116    ** The second algorithm is to select a rowid at random and see if
56117    ** it already exists in the table.  If it does not exist, we have
56118    ** succeeded.  If the random rowid does exist, we select a new one
56119    ** and try again, up to 100 times.
56120    */
56121    assert( u.be.pC->isTable );
56122    u.be.cnt = 0;
56123
56124#ifdef SQLITE_32BIT_ROWID
56125#   define MAX_ROWID 0x7fffffff
56126#else
56127    /* Some compilers complain about constants of the form 0x7fffffffffffffff.
56128    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
56129    ** to provide the constant while making all compilers happy.
56130    */
56131#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
56132#endif
56133
56134    if( !u.be.pC->useRandomRowid ){
56135      u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
56136      if( u.be.v==0 ){
56137        rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
56138        if( rc!=SQLITE_OK ){
56139          goto abort_due_to_error;
56140        }
56141        if( u.be.res ){
56142          u.be.v = 1;   /* IMP: R-61914-48074 */
56143        }else{
56144          assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
56145          rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
56146          assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
56147          if( u.be.v==MAX_ROWID ){
56148            u.be.pC->useRandomRowid = 1;
56149          }else{
56150            u.be.v++;   /* IMP: R-29538-34987 */
56151          }
56152        }
56153      }
56154
56155#ifndef SQLITE_OMIT_AUTOINCREMENT
56156      if( pOp->p3 ){
56157        /* Assert that P3 is a valid memory cell. */
56158        assert( pOp->p3>0 );
56159        if( p->pFrame ){
56160          for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
56161          /* Assert that P3 is a valid memory cell. */
56162          assert( pOp->p3<=u.be.pFrame->nMem );
56163          u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
56164        }else{
56165          /* Assert that P3 is a valid memory cell. */
56166          assert( pOp->p3<=p->nMem );
56167          u.be.pMem = &aMem[pOp->p3];
56168        }
56169
56170        REGISTER_TRACE(pOp->p3, u.be.pMem);
56171        sqlite3VdbeMemIntegerify(u.be.pMem);
56172        assert( (u.be.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
56173        if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
56174          rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
56175          goto abort_due_to_error;
56176        }
56177        if( u.be.v<u.be.pMem->u.i+1 ){
56178          u.be.v = u.be.pMem->u.i + 1;
56179        }
56180        u.be.pMem->u.i = u.be.v;
56181      }
56182#endif
56183
56184      sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
56185    }
56186    if( u.be.pC->useRandomRowid ){
56187      /* IMPLEMENTATION-OF: R-48598-02938 If the largest ROWID is equal to the
56188      ** largest possible integer (9223372036854775807) then the database
56189      ** engine starts picking candidate ROWIDs at random until it finds one
56190      ** that is not previously used.
56191      */
56192      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
56193                             ** an AUTOINCREMENT table. */
56194      u.be.v = db->lastRowid;
56195      u.be.cnt = 0;
56196      do{
56197        if( u.be.cnt==0 && (u.be.v&0xffffff)==u.be.v ){
56198          u.be.v++;
56199        }else{
56200          sqlite3_randomness(sizeof(u.be.v), &u.be.v);
56201          if( u.be.cnt<5 ) u.be.v &= 0xffffff;
56202        }
56203        rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v, 0, &u.be.res);
56204        u.be.cnt++;
56205      }while( u.be.cnt<100 && rc==SQLITE_OK && u.be.res==0 );
56206      if( rc==SQLITE_OK && u.be.res==0 ){
56207        rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
56208        goto abort_due_to_error;
56209      }
56210    }
56211    u.be.pC->rowidIsValid = 0;
56212    u.be.pC->deferredMoveto = 0;
56213    u.be.pC->cacheStatus = CACHE_STALE;
56214  }
56215  pOut->u.i = u.be.v;
56216  break;
56217}
56218
56219/* Opcode: Insert P1 P2 P3 P4 P5
56220**
56221** Write an entry into the table of cursor P1.  A new entry is
56222** created if it doesn't already exist or the data for an existing
56223** entry is overwritten.  The data is the value MEM_Blob stored in register
56224** number P2. The key is stored in register P3. The key must
56225** be a MEM_Int.
56226**
56227** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
56228** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
56229** then rowid is stored for subsequent return by the
56230** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
56231**
56232** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
56233** the last seek operation (OP_NotExists) was a success, then this
56234** operation will not attempt to find the appropriate row before doing
56235** the insert but will instead overwrite the row that the cursor is
56236** currently pointing to.  Presumably, the prior OP_NotExists opcode
56237** has already positioned the cursor correctly.  This is an optimization
56238** that boosts performance by avoiding redundant seeks.
56239**
56240** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
56241** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
56242** is part of an INSERT operation.  The difference is only important to
56243** the update hook.
56244**
56245** Parameter P4 may point to a string containing the table-name, or
56246** may be NULL. If it is not NULL, then the update-hook
56247** (sqlite3.xUpdateCallback) is invoked following a successful insert.
56248**
56249** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
56250** allocated, then ownership of P2 is transferred to the pseudo-cursor
56251** and register P2 becomes ephemeral.  If the cursor is changed, the
56252** value of register P2 will then change.  Make sure this does not
56253** cause any problems.)
56254**
56255** This instruction only works on tables.  The equivalent instruction
56256** for indices is OP_IdxInsert.
56257*/
56258/* Opcode: InsertInt P1 P2 P3 P4 P5
56259**
56260** This works exactly like OP_Insert except that the key is the
56261** integer value P3, not the value of the integer stored in register P3.
56262*/
56263case OP_Insert:
56264case OP_InsertInt: {
56265#if 0  /* local variables moved into u.bf */
56266  Mem *pData;       /* MEM cell holding data for the record to be inserted */
56267  Mem *pKey;        /* MEM cell holding key  for the record */
56268  i64 iKey;         /* The integer ROWID or key for the record to be inserted */
56269  VdbeCursor *pC;   /* Cursor to table into which insert is written */
56270  int nZero;        /* Number of zero-bytes to append */
56271  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
56272  const char *zDb;  /* database name - used by the update hook */
56273  const char *zTbl; /* Table name - used by the opdate hook */
56274  int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
56275#endif /* local variables moved into u.bf */
56276
56277  u.bf.pData = &aMem[pOp->p2];
56278  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56279  u.bf.pC = p->apCsr[pOp->p1];
56280  assert( u.bf.pC!=0 );
56281  assert( u.bf.pC->pCursor!=0 );
56282  assert( u.bf.pC->pseudoTableReg==0 );
56283  assert( u.bf.pC->isTable );
56284  REGISTER_TRACE(pOp->p2, u.bf.pData);
56285
56286  if( pOp->opcode==OP_Insert ){
56287    u.bf.pKey = &aMem[pOp->p3];
56288    assert( u.bf.pKey->flags & MEM_Int );
56289    REGISTER_TRACE(pOp->p3, u.bf.pKey);
56290    u.bf.iKey = u.bf.pKey->u.i;
56291  }else{
56292    assert( pOp->opcode==OP_InsertInt );
56293    u.bf.iKey = pOp->p3;
56294  }
56295
56296  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
56297  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = u.bf.iKey;
56298  if( u.bf.pData->flags & MEM_Null ){
56299    u.bf.pData->z = 0;
56300    u.bf.pData->n = 0;
56301  }else{
56302    assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
56303  }
56304  u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
56305  if( u.bf.pData->flags & MEM_Zero ){
56306    u.bf.nZero = u.bf.pData->u.nZero;
56307  }else{
56308    u.bf.nZero = 0;
56309  }
56310  sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
56311  rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
56312                          u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
56313                          pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
56314  );
56315  u.bf.pC->rowidIsValid = 0;
56316  u.bf.pC->deferredMoveto = 0;
56317  u.bf.pC->cacheStatus = CACHE_STALE;
56318
56319  /* Invoke the update-hook if required. */
56320  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
56321    u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
56322    u.bf.zTbl = pOp->p4.z;
56323    u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
56324    assert( u.bf.pC->isTable );
56325    db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
56326    assert( u.bf.pC->iDb>=0 );
56327  }
56328  break;
56329}
56330
56331/* Opcode: Delete P1 P2 * P4 *
56332**
56333** Delete the record at which the P1 cursor is currently pointing.
56334**
56335** The cursor will be left pointing at either the next or the previous
56336** record in the table. If it is left pointing at the next record, then
56337** the next Next instruction will be a no-op.  Hence it is OK to delete
56338** a record from within an Next loop.
56339**
56340** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
56341** incremented (otherwise not).
56342**
56343** P1 must not be pseudo-table.  It has to be a real table with
56344** multiple rows.
56345**
56346** If P4 is not NULL, then it is the name of the table that P1 is
56347** pointing to.  The update hook will be invoked, if it exists.
56348** If P4 is not NULL then the P1 cursor must have been positioned
56349** using OP_NotFound prior to invoking this opcode.
56350*/
56351case OP_Delete: {
56352#if 0  /* local variables moved into u.bg */
56353  i64 iKey;
56354  VdbeCursor *pC;
56355#endif /* local variables moved into u.bg */
56356
56357  u.bg.iKey = 0;
56358  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56359  u.bg.pC = p->apCsr[pOp->p1];
56360  assert( u.bg.pC!=0 );
56361  assert( u.bg.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
56362
56363  /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
56364  ** row being deleted.
56365  */
56366  if( db->xUpdateCallback && pOp->p4.z ){
56367    assert( u.bg.pC->isTable );
56368    assert( u.bg.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
56369    u.bg.iKey = u.bg.pC->lastRowid;
56370  }
56371
56372  /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
56373  ** OP_Column on the same table without any intervening operations that
56374  ** might move or invalidate the cursor.  Hence cursor u.bg.pC is always pointing
56375  ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
56376  ** below is always a no-op and cannot fail.  We will run it anyhow, though,
56377  ** to guard against future changes to the code generator.
56378  **/
56379  assert( u.bg.pC->deferredMoveto==0 );
56380  rc = sqlite3VdbeCursorMoveto(u.bg.pC);
56381  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
56382
56383  sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
56384  rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
56385  u.bg.pC->cacheStatus = CACHE_STALE;
56386
56387  /* Invoke the update-hook if required. */
56388  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
56389    const char *zDb = db->aDb[u.bg.pC->iDb].zName;
56390    const char *zTbl = pOp->p4.z;
56391    db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
56392    assert( u.bg.pC->iDb>=0 );
56393  }
56394  if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
56395  break;
56396}
56397/* Opcode: ResetCount * * * * *
56398**
56399** The value of the change counter is copied to the database handle
56400** change counter (returned by subsequent calls to sqlite3_changes()).
56401** Then the VMs internal change counter resets to 0.
56402** This is used by trigger programs.
56403*/
56404case OP_ResetCount: {
56405  sqlite3VdbeSetChanges(db, p->nChange);
56406  p->nChange = 0;
56407  break;
56408}
56409
56410/* Opcode: RowData P1 P2 * * *
56411**
56412** Write into register P2 the complete row data for cursor P1.
56413** There is no interpretation of the data.
56414** It is just copied onto the P2 register exactly as
56415** it is found in the database file.
56416**
56417** If the P1 cursor must be pointing to a valid row (not a NULL row)
56418** of a real table, not a pseudo-table.
56419*/
56420/* Opcode: RowKey P1 P2 * * *
56421**
56422** Write into register P2 the complete row key for cursor P1.
56423** There is no interpretation of the data.
56424** The key is copied onto the P3 register exactly as
56425** it is found in the database file.
56426**
56427** If the P1 cursor must be pointing to a valid row (not a NULL row)
56428** of a real table, not a pseudo-table.
56429*/
56430case OP_RowKey:
56431case OP_RowData: {
56432#if 0  /* local variables moved into u.bh */
56433  VdbeCursor *pC;
56434  BtCursor *pCrsr;
56435  u32 n;
56436  i64 n64;
56437#endif /* local variables moved into u.bh */
56438
56439  pOut = &aMem[pOp->p2];
56440
56441  /* Note that RowKey and RowData are really exactly the same instruction */
56442  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56443  u.bh.pC = p->apCsr[pOp->p1];
56444  assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
56445  assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
56446  assert( u.bh.pC!=0 );
56447  assert( u.bh.pC->nullRow==0 );
56448  assert( u.bh.pC->pseudoTableReg==0 );
56449  assert( u.bh.pC->pCursor!=0 );
56450  u.bh.pCrsr = u.bh.pC->pCursor;
56451  assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
56452
56453  /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
56454  ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
56455  ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
56456  ** a no-op and can never fail.  But we leave it in place as a safety.
56457  */
56458  assert( u.bh.pC->deferredMoveto==0 );
56459  rc = sqlite3VdbeCursorMoveto(u.bh.pC);
56460  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
56461
56462  if( u.bh.pC->isIndex ){
56463    assert( !u.bh.pC->isTable );
56464    rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
56465    assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
56466    if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
56467      goto too_big;
56468    }
56469    u.bh.n = (u32)u.bh.n64;
56470  }else{
56471    rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
56472    assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
56473    if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
56474      goto too_big;
56475    }
56476  }
56477  if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
56478    goto no_mem;
56479  }
56480  pOut->n = u.bh.n;
56481  MemSetTypeFlag(pOut, MEM_Blob);
56482  if( u.bh.pC->isIndex ){
56483    rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
56484  }else{
56485    rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
56486  }
56487  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
56488  UPDATE_MAX_BLOBSIZE(pOut);
56489  break;
56490}
56491
56492/* Opcode: Rowid P1 P2 * * *
56493**
56494** Store in register P2 an integer which is the key of the table entry that
56495** P1 is currently point to.
56496**
56497** P1 can be either an ordinary table or a virtual table.  There used to
56498** be a separate OP_VRowid opcode for use with virtual tables, but this
56499** one opcode now works for both table types.
56500*/
56501case OP_Rowid: {                 /* out2-prerelease */
56502#if 0  /* local variables moved into u.bi */
56503  VdbeCursor *pC;
56504  i64 v;
56505  sqlite3_vtab *pVtab;
56506  const sqlite3_module *pModule;
56507#endif /* local variables moved into u.bi */
56508
56509  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56510  u.bi.pC = p->apCsr[pOp->p1];
56511  assert( u.bi.pC!=0 );
56512  assert( u.bi.pC->pseudoTableReg==0 );
56513  if( u.bi.pC->nullRow ){
56514    pOut->flags = MEM_Null;
56515    break;
56516  }else if( u.bi.pC->deferredMoveto ){
56517    u.bi.v = u.bi.pC->movetoTarget;
56518#ifndef SQLITE_OMIT_VIRTUALTABLE
56519  }else if( u.bi.pC->pVtabCursor ){
56520    u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
56521    u.bi.pModule = u.bi.pVtab->pModule;
56522    assert( u.bi.pModule->xRowid );
56523    rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
56524    sqlite3DbFree(db, p->zErrMsg);
56525    p->zErrMsg = u.bi.pVtab->zErrMsg;
56526    u.bi.pVtab->zErrMsg = 0;
56527#endif /* SQLITE_OMIT_VIRTUALTABLE */
56528  }else{
56529    assert( u.bi.pC->pCursor!=0 );
56530    rc = sqlite3VdbeCursorMoveto(u.bi.pC);
56531    if( rc ) goto abort_due_to_error;
56532    if( u.bi.pC->rowidIsValid ){
56533      u.bi.v = u.bi.pC->lastRowid;
56534    }else{
56535      rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
56536      assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
56537    }
56538  }
56539  pOut->u.i = u.bi.v;
56540  break;
56541}
56542
56543/* Opcode: NullRow P1 * * * *
56544**
56545** Move the cursor P1 to a null row.  Any OP_Column operations
56546** that occur while the cursor is on the null row will always
56547** write a NULL.
56548*/
56549case OP_NullRow: {
56550#if 0  /* local variables moved into u.bj */
56551  VdbeCursor *pC;
56552#endif /* local variables moved into u.bj */
56553
56554  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56555  u.bj.pC = p->apCsr[pOp->p1];
56556  assert( u.bj.pC!=0 );
56557  u.bj.pC->nullRow = 1;
56558  u.bj.pC->rowidIsValid = 0;
56559  if( u.bj.pC->pCursor ){
56560    sqlite3BtreeClearCursor(u.bj.pC->pCursor);
56561  }
56562  break;
56563}
56564
56565/* Opcode: Last P1 P2 * * *
56566**
56567** The next use of the Rowid or Column or Next instruction for P1
56568** will refer to the last entry in the database table or index.
56569** If the table or index is empty and P2>0, then jump immediately to P2.
56570** If P2 is 0 or if the table or index is not empty, fall through
56571** to the following instruction.
56572*/
56573case OP_Last: {        /* jump */
56574#if 0  /* local variables moved into u.bk */
56575  VdbeCursor *pC;
56576  BtCursor *pCrsr;
56577  int res;
56578#endif /* local variables moved into u.bk */
56579
56580  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56581  u.bk.pC = p->apCsr[pOp->p1];
56582  assert( u.bk.pC!=0 );
56583  u.bk.pCrsr = u.bk.pC->pCursor;
56584  if( u.bk.pCrsr==0 ){
56585    u.bk.res = 1;
56586  }else{
56587    rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
56588  }
56589  u.bk.pC->nullRow = (u8)u.bk.res;
56590  u.bk.pC->deferredMoveto = 0;
56591  u.bk.pC->rowidIsValid = 0;
56592  u.bk.pC->cacheStatus = CACHE_STALE;
56593  if( pOp->p2>0 && u.bk.res ){
56594    pc = pOp->p2 - 1;
56595  }
56596  break;
56597}
56598
56599
56600/* Opcode: Sort P1 P2 * * *
56601**
56602** This opcode does exactly the same thing as OP_Rewind except that
56603** it increments an undocumented global variable used for testing.
56604**
56605** Sorting is accomplished by writing records into a sorting index,
56606** then rewinding that index and playing it back from beginning to
56607** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
56608** rewinding so that the global variable will be incremented and
56609** regression tests can determine whether or not the optimizer is
56610** correctly optimizing out sorts.
56611*/
56612case OP_Sort: {        /* jump */
56613#ifdef SQLITE_TEST
56614  sqlite3_sort_count++;
56615  sqlite3_search_count--;
56616#endif
56617  p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
56618  /* Fall through into OP_Rewind */
56619}
56620/* Opcode: Rewind P1 P2 * * *
56621**
56622** The next use of the Rowid or Column or Next instruction for P1
56623** will refer to the first entry in the database table or index.
56624** If the table or index is empty and P2>0, then jump immediately to P2.
56625** If P2 is 0 or if the table or index is not empty, fall through
56626** to the following instruction.
56627*/
56628case OP_Rewind: {        /* jump */
56629#if 0  /* local variables moved into u.bl */
56630  VdbeCursor *pC;
56631  BtCursor *pCrsr;
56632  int res;
56633#endif /* local variables moved into u.bl */
56634
56635  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56636  u.bl.pC = p->apCsr[pOp->p1];
56637  assert( u.bl.pC!=0 );
56638  if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
56639    rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
56640    u.bl.pC->atFirst = u.bl.res==0 ?1:0;
56641    u.bl.pC->deferredMoveto = 0;
56642    u.bl.pC->cacheStatus = CACHE_STALE;
56643    u.bl.pC->rowidIsValid = 0;
56644  }else{
56645    u.bl.res = 1;
56646  }
56647  u.bl.pC->nullRow = (u8)u.bl.res;
56648  assert( pOp->p2>0 && pOp->p2<p->nOp );
56649  if( u.bl.res ){
56650    pc = pOp->p2 - 1;
56651  }
56652  break;
56653}
56654
56655/* Opcode: Next P1 P2 * * *
56656**
56657** Advance cursor P1 so that it points to the next key/data pair in its
56658** table or index.  If there are no more key/value pairs then fall through
56659** to the following instruction.  But if the cursor advance was successful,
56660** jump immediately to P2.
56661**
56662** The P1 cursor must be for a real table, not a pseudo-table.
56663**
56664** See also: Prev
56665*/
56666/* Opcode: Prev P1 P2 * * *
56667**
56668** Back up cursor P1 so that it points to the previous key/data pair in its
56669** table or index.  If there is no previous key/value pairs then fall through
56670** to the following instruction.  But if the cursor backup was successful,
56671** jump immediately to P2.
56672**
56673** The P1 cursor must be for a real table, not a pseudo-table.
56674*/
56675case OP_Prev:          /* jump */
56676case OP_Next: {        /* jump */
56677#if 0  /* local variables moved into u.bm */
56678  VdbeCursor *pC;
56679  BtCursor *pCrsr;
56680  int res;
56681#endif /* local variables moved into u.bm */
56682
56683  CHECK_FOR_INTERRUPT;
56684  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56685  u.bm.pC = p->apCsr[pOp->p1];
56686  if( u.bm.pC==0 ){
56687    break;  /* See ticket #2273 */
56688  }
56689  u.bm.pCrsr = u.bm.pC->pCursor;
56690  if( u.bm.pCrsr==0 ){
56691    u.bm.pC->nullRow = 1;
56692    break;
56693  }
56694  u.bm.res = 1;
56695  assert( u.bm.pC->deferredMoveto==0 );
56696  rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
56697                              sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
56698  u.bm.pC->nullRow = (u8)u.bm.res;
56699  u.bm.pC->cacheStatus = CACHE_STALE;
56700  if( u.bm.res==0 ){
56701    pc = pOp->p2 - 1;
56702    if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
56703#ifdef SQLITE_TEST
56704    sqlite3_search_count++;
56705#endif
56706  }
56707  u.bm.pC->rowidIsValid = 0;
56708  break;
56709}
56710
56711/* Opcode: IdxInsert P1 P2 P3 * P5
56712**
56713** Register P2 holds a SQL index key made using the
56714** MakeRecord instructions.  This opcode writes that key
56715** into the index P1.  Data for the entry is nil.
56716**
56717** P3 is a flag that provides a hint to the b-tree layer that this
56718** insert is likely to be an append.
56719**
56720** This instruction only works for indices.  The equivalent instruction
56721** for tables is OP_Insert.
56722*/
56723case OP_IdxInsert: {        /* in2 */
56724#if 0  /* local variables moved into u.bn */
56725  VdbeCursor *pC;
56726  BtCursor *pCrsr;
56727  int nKey;
56728  const char *zKey;
56729#endif /* local variables moved into u.bn */
56730
56731  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56732  u.bn.pC = p->apCsr[pOp->p1];
56733  assert( u.bn.pC!=0 );
56734  pIn2 = &aMem[pOp->p2];
56735  assert( pIn2->flags & MEM_Blob );
56736  u.bn.pCrsr = u.bn.pC->pCursor;
56737  if( ALWAYS(u.bn.pCrsr!=0) ){
56738    assert( u.bn.pC->isTable==0 );
56739    rc = ExpandBlob(pIn2);
56740    if( rc==SQLITE_OK ){
56741      u.bn.nKey = pIn2->n;
56742      u.bn.zKey = pIn2->z;
56743      rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
56744          ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
56745      );
56746      assert( u.bn.pC->deferredMoveto==0 );
56747      u.bn.pC->cacheStatus = CACHE_STALE;
56748    }
56749  }
56750  break;
56751}
56752
56753/* Opcode: IdxDelete P1 P2 P3 * *
56754**
56755** The content of P3 registers starting at register P2 form
56756** an unpacked index key. This opcode removes that entry from the
56757** index opened by cursor P1.
56758*/
56759case OP_IdxDelete: {
56760#if 0  /* local variables moved into u.bo */
56761  VdbeCursor *pC;
56762  BtCursor *pCrsr;
56763  int res;
56764  UnpackedRecord r;
56765#endif /* local variables moved into u.bo */
56766
56767  assert( pOp->p3>0 );
56768  assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
56769  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56770  u.bo.pC = p->apCsr[pOp->p1];
56771  assert( u.bo.pC!=0 );
56772  u.bo.pCrsr = u.bo.pC->pCursor;
56773  if( ALWAYS(u.bo.pCrsr!=0) ){
56774    u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
56775    u.bo.r.nField = (u16)pOp->p3;
56776    u.bo.r.flags = 0;
56777    u.bo.r.aMem = &aMem[pOp->p2];
56778    rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
56779    if( rc==SQLITE_OK && u.bo.res==0 ){
56780      rc = sqlite3BtreeDelete(u.bo.pCrsr);
56781    }
56782    assert( u.bo.pC->deferredMoveto==0 );
56783    u.bo.pC->cacheStatus = CACHE_STALE;
56784  }
56785  break;
56786}
56787
56788/* Opcode: IdxRowid P1 P2 * * *
56789**
56790** Write into register P2 an integer which is the last entry in the record at
56791** the end of the index key pointed to by cursor P1.  This integer should be
56792** the rowid of the table entry to which this index entry points.
56793**
56794** See also: Rowid, MakeRecord.
56795*/
56796case OP_IdxRowid: {              /* out2-prerelease */
56797#if 0  /* local variables moved into u.bp */
56798  BtCursor *pCrsr;
56799  VdbeCursor *pC;
56800  i64 rowid;
56801#endif /* local variables moved into u.bp */
56802
56803  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56804  u.bp.pC = p->apCsr[pOp->p1];
56805  assert( u.bp.pC!=0 );
56806  u.bp.pCrsr = u.bp.pC->pCursor;
56807  pOut->flags = MEM_Null;
56808  if( ALWAYS(u.bp.pCrsr!=0) ){
56809    rc = sqlite3VdbeCursorMoveto(u.bp.pC);
56810    if( NEVER(rc) ) goto abort_due_to_error;
56811    assert( u.bp.pC->deferredMoveto==0 );
56812    assert( u.bp.pC->isTable==0 );
56813    if( !u.bp.pC->nullRow ){
56814      rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
56815      if( rc!=SQLITE_OK ){
56816        goto abort_due_to_error;
56817      }
56818      pOut->u.i = u.bp.rowid;
56819      pOut->flags = MEM_Int;
56820    }
56821  }
56822  break;
56823}
56824
56825/* Opcode: IdxGE P1 P2 P3 P4 P5
56826**
56827** The P4 register values beginning with P3 form an unpacked index
56828** key that omits the ROWID.  Compare this key value against the index
56829** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
56830**
56831** If the P1 index entry is greater than or equal to the key value
56832** then jump to P2.  Otherwise fall through to the next instruction.
56833**
56834** If P5 is non-zero then the key value is increased by an epsilon
56835** prior to the comparison.  This make the opcode work like IdxGT except
56836** that if the key from register P3 is a prefix of the key in the cursor,
56837** the result is false whereas it would be true with IdxGT.
56838*/
56839/* Opcode: IdxLT P1 P2 P3 * P5
56840**
56841** The P4 register values beginning with P3 form an unpacked index
56842** key that omits the ROWID.  Compare this key value against the index
56843** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
56844**
56845** If the P1 index entry is less than the key value then jump to P2.
56846** Otherwise fall through to the next instruction.
56847**
56848** If P5 is non-zero then the key value is increased by an epsilon prior
56849** to the comparison.  This makes the opcode work like IdxLE.
56850*/
56851case OP_IdxLT:          /* jump */
56852case OP_IdxGE: {        /* jump */
56853#if 0  /* local variables moved into u.bq */
56854  VdbeCursor *pC;
56855  int res;
56856  UnpackedRecord r;
56857#endif /* local variables moved into u.bq */
56858
56859  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56860  u.bq.pC = p->apCsr[pOp->p1];
56861  assert( u.bq.pC!=0 );
56862  if( ALWAYS(u.bq.pC->pCursor!=0) ){
56863    assert( u.bq.pC->deferredMoveto==0 );
56864    assert( pOp->p5==0 || pOp->p5==1 );
56865    assert( pOp->p4type==P4_INT32 );
56866    u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
56867    u.bq.r.nField = (u16)pOp->p4.i;
56868    if( pOp->p5 ){
56869      u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
56870    }else{
56871      u.bq.r.flags = UNPACKED_IGNORE_ROWID;
56872    }
56873    u.bq.r.aMem = &aMem[pOp->p3];
56874    rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
56875    if( pOp->opcode==OP_IdxLT ){
56876      u.bq.res = -u.bq.res;
56877    }else{
56878      assert( pOp->opcode==OP_IdxGE );
56879      u.bq.res++;
56880    }
56881    if( u.bq.res>0 ){
56882      pc = pOp->p2 - 1 ;
56883    }
56884  }
56885  break;
56886}
56887
56888/* Opcode: Destroy P1 P2 P3 * *
56889**
56890** Delete an entire database table or index whose root page in the database
56891** file is given by P1.
56892**
56893** The table being destroyed is in the main database file if P3==0.  If
56894** P3==1 then the table to be clear is in the auxiliary database file
56895** that is used to store tables create using CREATE TEMPORARY TABLE.
56896**
56897** If AUTOVACUUM is enabled then it is possible that another root page
56898** might be moved into the newly deleted root page in order to keep all
56899** root pages contiguous at the beginning of the database.  The former
56900** value of the root page that moved - its value before the move occurred -
56901** is stored in register P2.  If no page
56902** movement was required (because the table being dropped was already
56903** the last one in the database) then a zero is stored in register P2.
56904** If AUTOVACUUM is disabled then a zero is stored in register P2.
56905**
56906** See also: Clear
56907*/
56908case OP_Destroy: {     /* out2-prerelease */
56909#if 0  /* local variables moved into u.br */
56910  int iMoved;
56911  int iCnt;
56912  Vdbe *pVdbe;
56913  int iDb;
56914#endif /* local variables moved into u.br */
56915#ifndef SQLITE_OMIT_VIRTUALTABLE
56916  u.br.iCnt = 0;
56917  for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
56918    if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
56919      u.br.iCnt++;
56920    }
56921  }
56922#else
56923  u.br.iCnt = db->activeVdbeCnt;
56924#endif
56925  pOut->flags = MEM_Null;
56926  if( u.br.iCnt>1 ){
56927    rc = SQLITE_LOCKED;
56928    p->errorAction = OE_Abort;
56929  }else{
56930    u.br.iDb = pOp->p3;
56931    assert( u.br.iCnt==1 );
56932    assert( (p->btreeMask & (1<<u.br.iDb))!=0 );
56933    rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
56934    pOut->flags = MEM_Int;
56935    pOut->u.i = u.br.iMoved;
56936#ifndef SQLITE_OMIT_AUTOVACUUM
56937    if( rc==SQLITE_OK && u.br.iMoved!=0 ){
56938      sqlite3RootPageMoved(&db->aDb[u.br.iDb], u.br.iMoved, pOp->p1);
56939      resetSchemaOnFault = 1;
56940    }
56941#endif
56942  }
56943  break;
56944}
56945
56946/* Opcode: Clear P1 P2 P3
56947**
56948** Delete all contents of the database table or index whose root page
56949** in the database file is given by P1.  But, unlike Destroy, do not
56950** remove the table or index from the database file.
56951**
56952** The table being clear is in the main database file if P2==0.  If
56953** P2==1 then the table to be clear is in the auxiliary database file
56954** that is used to store tables create using CREATE TEMPORARY TABLE.
56955**
56956** If the P3 value is non-zero, then the table referred to must be an
56957** intkey table (an SQL table, not an index). In this case the row change
56958** count is incremented by the number of rows in the table being cleared.
56959** If P3 is greater than zero, then the value stored in register P3 is
56960** also incremented by the number of rows in the table being cleared.
56961**
56962** See also: Destroy
56963*/
56964case OP_Clear: {
56965#if 0  /* local variables moved into u.bs */
56966  int nChange;
56967#endif /* local variables moved into u.bs */
56968
56969  u.bs.nChange = 0;
56970  assert( (p->btreeMask & (1<<pOp->p2))!=0 );
56971  rc = sqlite3BtreeClearTable(
56972      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
56973  );
56974  if( pOp->p3 ){
56975    p->nChange += u.bs.nChange;
56976    if( pOp->p3>0 ){
56977      aMem[pOp->p3].u.i += u.bs.nChange;
56978    }
56979  }
56980  break;
56981}
56982
56983/* Opcode: CreateTable P1 P2 * * *
56984**
56985** Allocate a new table in the main database file if P1==0 or in the
56986** auxiliary database file if P1==1 or in an attached database if
56987** P1>1.  Write the root page number of the new table into
56988** register P2
56989**
56990** The difference between a table and an index is this:  A table must
56991** have a 4-byte integer key and can have arbitrary data.  An index
56992** has an arbitrary key but no data.
56993**
56994** See also: CreateIndex
56995*/
56996/* Opcode: CreateIndex P1 P2 * * *
56997**
56998** Allocate a new index in the main database file if P1==0 or in the
56999** auxiliary database file if P1==1 or in an attached database if
57000** P1>1.  Write the root page number of the new table into
57001** register P2.
57002**
57003** See documentation on OP_CreateTable for additional information.
57004*/
57005case OP_CreateIndex:            /* out2-prerelease */
57006case OP_CreateTable: {          /* out2-prerelease */
57007#if 0  /* local variables moved into u.bt */
57008  int pgno;
57009  int flags;
57010  Db *pDb;
57011#endif /* local variables moved into u.bt */
57012
57013  u.bt.pgno = 0;
57014  assert( pOp->p1>=0 && pOp->p1<db->nDb );
57015  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
57016  u.bt.pDb = &db->aDb[pOp->p1];
57017  assert( u.bt.pDb->pBt!=0 );
57018  if( pOp->opcode==OP_CreateTable ){
57019    /* u.bt.flags = BTREE_INTKEY; */
57020    u.bt.flags = BTREE_LEAFDATA|BTREE_INTKEY;
57021  }else{
57022    u.bt.flags = BTREE_ZERODATA;
57023  }
57024  rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
57025  pOut->u.i = u.bt.pgno;
57026  break;
57027}
57028
57029/* Opcode: ParseSchema P1 P2 * P4 *
57030**
57031** Read and parse all entries from the SQLITE_MASTER table of database P1
57032** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
57033** the parsing if P2 is true.  If P2 is false, then this routine is a
57034** no-op if the schema is not currently loaded.  In other words, if P2
57035** is false, the SQLITE_MASTER table is only parsed if the rest of the
57036** schema is already loaded into the symbol table.
57037**
57038** This opcode invokes the parser to create a new virtual machine,
57039** then runs the new virtual machine.  It is thus a re-entrant opcode.
57040*/
57041case OP_ParseSchema: {
57042#if 0  /* local variables moved into u.bu */
57043  int iDb;
57044  const char *zMaster;
57045  char *zSql;
57046  InitData initData;
57047#endif /* local variables moved into u.bu */
57048
57049  u.bu.iDb = pOp->p1;
57050  assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
57051
57052  /* If pOp->p2 is 0, then this opcode is being executed to read a
57053  ** single row, for example the row corresponding to a new index
57054  ** created by this VDBE, from the sqlite_master table. It only
57055  ** does this if the corresponding in-memory schema is currently
57056  ** loaded. Otherwise, the new index definition can be loaded along
57057  ** with the rest of the schema when it is required.
57058  **
57059  ** Although the mutex on the BtShared object that corresponds to
57060  ** database u.bu.iDb (the database containing the sqlite_master table
57061  ** read by this instruction) is currently held, it is necessary to
57062  ** obtain the mutexes on all attached databases before checking if
57063  ** the schema of u.bu.iDb is loaded. This is because, at the start of
57064  ** the sqlite3_exec() call below, SQLite will invoke
57065  ** sqlite3BtreeEnterAll(). If all mutexes are not already held, the
57066  ** u.bu.iDb mutex may be temporarily released to avoid deadlock. If
57067  ** this happens, then some other thread may delete the in-memory
57068  ** schema of database u.bu.iDb before the SQL statement runs. The schema
57069  ** will not be reloaded becuase the db->init.busy flag is set. This
57070  ** can result in a "no such table: sqlite_master" or "malformed
57071  ** database schema" error being returned to the user.
57072  */
57073  assert( sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
57074  sqlite3BtreeEnterAll(db);
57075  if( pOp->p2 || DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) ){
57076    u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
57077    u.bu.initData.db = db;
57078    u.bu.initData.iDb = pOp->p1;
57079    u.bu.initData.pzErrMsg = &p->zErrMsg;
57080    u.bu.zSql = sqlite3MPrintf(db,
57081       "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
57082       db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
57083    if( u.bu.zSql==0 ){
57084      rc = SQLITE_NOMEM;
57085    }else{
57086      assert( db->init.busy==0 );
57087      db->init.busy = 1;
57088      u.bu.initData.rc = SQLITE_OK;
57089      assert( !db->mallocFailed );
57090      rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
57091      if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
57092      sqlite3DbFree(db, u.bu.zSql);
57093      db->init.busy = 0;
57094    }
57095  }
57096  sqlite3BtreeLeaveAll(db);
57097  if( rc==SQLITE_NOMEM ){
57098    goto no_mem;
57099  }
57100  break;
57101}
57102
57103#if !defined(SQLITE_OMIT_ANALYZE)
57104/* Opcode: LoadAnalysis P1 * * * *
57105**
57106** Read the sqlite_stat1 table for database P1 and load the content
57107** of that table into the internal index hash table.  This will cause
57108** the analysis to be used when preparing all subsequent queries.
57109*/
57110case OP_LoadAnalysis: {
57111  assert( pOp->p1>=0 && pOp->p1<db->nDb );
57112  rc = sqlite3AnalysisLoad(db, pOp->p1);
57113  break;
57114}
57115#endif /* !defined(SQLITE_OMIT_ANALYZE) */
57116
57117/* Opcode: DropTable P1 * * P4 *
57118**
57119** Remove the internal (in-memory) data structures that describe
57120** the table named P4 in database P1.  This is called after a table
57121** is dropped in order to keep the internal representation of the
57122** schema consistent with what is on disk.
57123*/
57124case OP_DropTable: {
57125  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
57126  break;
57127}
57128
57129/* Opcode: DropIndex P1 * * P4 *
57130**
57131** Remove the internal (in-memory) data structures that describe
57132** the index named P4 in database P1.  This is called after an index
57133** is dropped in order to keep the internal representation of the
57134** schema consistent with what is on disk.
57135*/
57136case OP_DropIndex: {
57137  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
57138  break;
57139}
57140
57141/* Opcode: DropTrigger P1 * * P4 *
57142**
57143** Remove the internal (in-memory) data structures that describe
57144** the trigger named P4 in database P1.  This is called after a trigger
57145** is dropped in order to keep the internal representation of the
57146** schema consistent with what is on disk.
57147*/
57148case OP_DropTrigger: {
57149  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
57150  break;
57151}
57152
57153
57154#ifndef SQLITE_OMIT_INTEGRITY_CHECK
57155/* Opcode: IntegrityCk P1 P2 P3 * P5
57156**
57157** Do an analysis of the currently open database.  Store in
57158** register P1 the text of an error message describing any problems.
57159** If no problems are found, store a NULL in register P1.
57160**
57161** The register P3 contains the maximum number of allowed errors.
57162** At most reg(P3) errors will be reported.
57163** In other words, the analysis stops as soon as reg(P1) errors are
57164** seen.  Reg(P1) is updated with the number of errors remaining.
57165**
57166** The root page numbers of all tables in the database are integer
57167** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
57168** total.
57169**
57170** If P5 is not zero, the check is done on the auxiliary database
57171** file, not the main database file.
57172**
57173** This opcode is used to implement the integrity_check pragma.
57174*/
57175case OP_IntegrityCk: {
57176#if 0  /* local variables moved into u.bv */
57177  int nRoot;      /* Number of tables to check.  (Number of root pages.) */
57178  int *aRoot;     /* Array of rootpage numbers for tables to be checked */
57179  int j;          /* Loop counter */
57180  int nErr;       /* Number of errors reported */
57181  char *z;        /* Text of the error report */
57182  Mem *pnErr;     /* Register keeping track of errors remaining */
57183#endif /* local variables moved into u.bv */
57184
57185  u.bv.nRoot = pOp->p2;
57186  assert( u.bv.nRoot>0 );
57187  u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
57188  if( u.bv.aRoot==0 ) goto no_mem;
57189  assert( pOp->p3>0 && pOp->p3<=p->nMem );
57190  u.bv.pnErr = &aMem[pOp->p3];
57191  assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
57192  assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
57193  pIn1 = &aMem[pOp->p1];
57194  for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
57195    u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
57196  }
57197  u.bv.aRoot[u.bv.j] = 0;
57198  assert( pOp->p5<db->nDb );
57199  assert( (p->btreeMask & (1<<pOp->p5))!=0 );
57200  u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
57201                                 (int)u.bv.pnErr->u.i, &u.bv.nErr);
57202  sqlite3DbFree(db, u.bv.aRoot);
57203  u.bv.pnErr->u.i -= u.bv.nErr;
57204  sqlite3VdbeMemSetNull(pIn1);
57205  if( u.bv.nErr==0 ){
57206    assert( u.bv.z==0 );
57207  }else if( u.bv.z==0 ){
57208    goto no_mem;
57209  }else{
57210    sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
57211  }
57212  UPDATE_MAX_BLOBSIZE(pIn1);
57213  sqlite3VdbeChangeEncoding(pIn1, encoding);
57214  break;
57215}
57216#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57217
57218/* Opcode: RowSetAdd P1 P2 * * *
57219**
57220** Insert the integer value held by register P2 into a boolean index
57221** held in register P1.
57222**
57223** An assertion fails if P2 is not an integer.
57224*/
57225case OP_RowSetAdd: {       /* in1, in2 */
57226  pIn1 = &aMem[pOp->p1];
57227  pIn2 = &aMem[pOp->p2];
57228  assert( (pIn2->flags & MEM_Int)!=0 );
57229  if( (pIn1->flags & MEM_RowSet)==0 ){
57230    sqlite3VdbeMemSetRowSet(pIn1);
57231    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
57232  }
57233  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
57234  break;
57235}
57236
57237/* Opcode: RowSetRead P1 P2 P3 * *
57238**
57239** Extract the smallest value from boolean index P1 and put that value into
57240** register P3.  Or, if boolean index P1 is initially empty, leave P3
57241** unchanged and jump to instruction P2.
57242*/
57243case OP_RowSetRead: {       /* jump, in1, out3 */
57244#if 0  /* local variables moved into u.bw */
57245  i64 val;
57246#endif /* local variables moved into u.bw */
57247  CHECK_FOR_INTERRUPT;
57248  pIn1 = &aMem[pOp->p1];
57249  if( (pIn1->flags & MEM_RowSet)==0
57250   || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
57251  ){
57252    /* The boolean index is empty */
57253    sqlite3VdbeMemSetNull(pIn1);
57254    pc = pOp->p2 - 1;
57255  }else{
57256    /* A value was pulled from the index */
57257    sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
57258  }
57259  break;
57260}
57261
57262/* Opcode: RowSetTest P1 P2 P3 P4
57263**
57264** Register P3 is assumed to hold a 64-bit integer value. If register P1
57265** contains a RowSet object and that RowSet object contains
57266** the value held in P3, jump to register P2. Otherwise, insert the
57267** integer in P3 into the RowSet and continue on to the
57268** next opcode.
57269**
57270** The RowSet object is optimized for the case where successive sets
57271** of integers, where each set contains no duplicates. Each set
57272** of values is identified by a unique P4 value. The first set
57273** must have P4==0, the final set P4=-1.  P4 must be either -1 or
57274** non-negative.  For non-negative values of P4 only the lower 4
57275** bits are significant.
57276**
57277** This allows optimizations: (a) when P4==0 there is no need to test
57278** the rowset object for P3, as it is guaranteed not to contain it,
57279** (b) when P4==-1 there is no need to insert the value, as it will
57280** never be tested for, and (c) when a value that is part of set X is
57281** inserted, there is no need to search to see if the same value was
57282** previously inserted as part of set X (only if it was previously
57283** inserted as part of some other set).
57284*/
57285case OP_RowSetTest: {                     /* jump, in1, in3 */
57286#if 0  /* local variables moved into u.bx */
57287  int iSet;
57288  int exists;
57289#endif /* local variables moved into u.bx */
57290
57291  pIn1 = &aMem[pOp->p1];
57292  pIn3 = &aMem[pOp->p3];
57293  u.bx.iSet = pOp->p4.i;
57294  assert( pIn3->flags&MEM_Int );
57295
57296  /* If there is anything other than a rowset object in memory cell P1,
57297  ** delete it now and initialize P1 with an empty rowset
57298  */
57299  if( (pIn1->flags & MEM_RowSet)==0 ){
57300    sqlite3VdbeMemSetRowSet(pIn1);
57301    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
57302  }
57303
57304  assert( pOp->p4type==P4_INT32 );
57305  assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
57306  if( u.bx.iSet ){
57307    u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
57308                               (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
57309                               pIn3->u.i);
57310    if( u.bx.exists ){
57311      pc = pOp->p2 - 1;
57312      break;
57313    }
57314  }
57315  if( u.bx.iSet>=0 ){
57316    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
57317  }
57318  break;
57319}
57320
57321
57322#ifndef SQLITE_OMIT_TRIGGER
57323
57324/* Opcode: Program P1 P2 P3 P4 *
57325**
57326** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
57327**
57328** P1 contains the address of the memory cell that contains the first memory
57329** cell in an array of values used as arguments to the sub-program. P2
57330** contains the address to jump to if the sub-program throws an IGNORE
57331** exception using the RAISE() function. Register P3 contains the address
57332** of a memory cell in this (the parent) VM that is used to allocate the
57333** memory required by the sub-vdbe at runtime.
57334**
57335** P4 is a pointer to the VM containing the trigger program.
57336*/
57337case OP_Program: {        /* jump */
57338#if 0  /* local variables moved into u.by */
57339  int nMem;               /* Number of memory registers for sub-program */
57340  int nByte;              /* Bytes of runtime space required for sub-program */
57341  Mem *pRt;               /* Register to allocate runtime space */
57342  Mem *pMem;              /* Used to iterate through memory cells */
57343  Mem *pEnd;              /* Last memory cell in new array */
57344  VdbeFrame *pFrame;      /* New vdbe frame to execute in */
57345  SubProgram *pProgram;   /* Sub-program to execute */
57346  void *t;                /* Token identifying trigger */
57347#endif /* local variables moved into u.by */
57348
57349  u.by.pProgram = pOp->p4.pProgram;
57350  u.by.pRt = &aMem[pOp->p3];
57351  assert( u.by.pProgram->nOp>0 );
57352
57353  /* If the p5 flag is clear, then recursive invocation of triggers is
57354  ** disabled for backwards compatibility (p5 is set if this sub-program
57355  ** is really a trigger, not a foreign key action, and the flag set
57356  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
57357  **
57358  ** It is recursive invocation of triggers, at the SQL level, that is
57359  ** disabled. In some cases a single trigger may generate more than one
57360  ** SubProgram (if the trigger may be executed with more than one different
57361  ** ON CONFLICT algorithm). SubProgram structures associated with a
57362  ** single trigger all have the same value for the SubProgram.token
57363  ** variable.  */
57364  if( pOp->p5 ){
57365    u.by.t = u.by.pProgram->token;
57366    for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
57367    if( u.by.pFrame ) break;
57368  }
57369
57370  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
57371    rc = SQLITE_ERROR;
57372    sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
57373    break;
57374  }
57375
57376  /* Register u.by.pRt is used to store the memory required to save the state
57377  ** of the current program, and the memory required at runtime to execute
57378  ** the trigger program. If this trigger has been fired before, then u.by.pRt
57379  ** is already allocated. Otherwise, it must be initialized.  */
57380  if( (u.by.pRt->flags&MEM_Frame)==0 ){
57381    /* SubProgram.nMem is set to the number of memory cells used by the
57382    ** program stored in SubProgram.aOp. As well as these, one memory
57383    ** cell is required for each cursor used by the program. Set local
57384    ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
57385    */
57386    u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
57387    u.by.nByte = ROUND8(sizeof(VdbeFrame))
57388              + u.by.nMem * sizeof(Mem)
57389              + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
57390    u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
57391    if( !u.by.pFrame ){
57392      goto no_mem;
57393    }
57394    sqlite3VdbeMemRelease(u.by.pRt);
57395    u.by.pRt->flags = MEM_Frame;
57396    u.by.pRt->u.pFrame = u.by.pFrame;
57397
57398    u.by.pFrame->v = p;
57399    u.by.pFrame->nChildMem = u.by.nMem;
57400    u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
57401    u.by.pFrame->pc = pc;
57402    u.by.pFrame->aMem = p->aMem;
57403    u.by.pFrame->nMem = p->nMem;
57404    u.by.pFrame->apCsr = p->apCsr;
57405    u.by.pFrame->nCursor = p->nCursor;
57406    u.by.pFrame->aOp = p->aOp;
57407    u.by.pFrame->nOp = p->nOp;
57408    u.by.pFrame->token = u.by.pProgram->token;
57409
57410    u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
57411    for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
57412      u.by.pMem->flags = MEM_Null;
57413      u.by.pMem->db = db;
57414    }
57415  }else{
57416    u.by.pFrame = u.by.pRt->u.pFrame;
57417    assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
57418    assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
57419    assert( pc==u.by.pFrame->pc );
57420  }
57421
57422  p->nFrame++;
57423  u.by.pFrame->pParent = p->pFrame;
57424  u.by.pFrame->lastRowid = db->lastRowid;
57425  u.by.pFrame->nChange = p->nChange;
57426  p->nChange = 0;
57427  p->pFrame = u.by.pFrame;
57428  p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
57429  p->nMem = u.by.pFrame->nChildMem;
57430  p->nCursor = (u16)u.by.pFrame->nChildCsr;
57431  p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
57432  p->aOp = aOp = u.by.pProgram->aOp;
57433  p->nOp = u.by.pProgram->nOp;
57434  pc = -1;
57435
57436  break;
57437}
57438
57439/* Opcode: Param P1 P2 * * *
57440**
57441** This opcode is only ever present in sub-programs called via the
57442** OP_Program instruction. Copy a value currently stored in a memory
57443** cell of the calling (parent) frame to cell P2 in the current frames
57444** address space. This is used by trigger programs to access the new.*
57445** and old.* values.
57446**
57447** The address of the cell in the parent frame is determined by adding
57448** the value of the P1 argument to the value of the P1 argument to the
57449** calling OP_Program instruction.
57450*/
57451case OP_Param: {           /* out2-prerelease */
57452#if 0  /* local variables moved into u.bz */
57453  VdbeFrame *pFrame;
57454  Mem *pIn;
57455#endif /* local variables moved into u.bz */
57456  u.bz.pFrame = p->pFrame;
57457  u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
57458  sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
57459  break;
57460}
57461
57462#endif /* #ifndef SQLITE_OMIT_TRIGGER */
57463
57464#ifndef SQLITE_OMIT_FOREIGN_KEY
57465/* Opcode: FkCounter P1 P2 * * *
57466**
57467** Increment a "constraint counter" by P2 (P2 may be negative or positive).
57468** If P1 is non-zero, the database constraint counter is incremented
57469** (deferred foreign key constraints). Otherwise, if P1 is zero, the
57470** statement counter is incremented (immediate foreign key constraints).
57471*/
57472case OP_FkCounter: {
57473  if( pOp->p1 ){
57474    db->nDeferredCons += pOp->p2;
57475  }else{
57476    p->nFkConstraint += pOp->p2;
57477  }
57478  break;
57479}
57480
57481/* Opcode: FkIfZero P1 P2 * * *
57482**
57483** This opcode tests if a foreign key constraint-counter is currently zero.
57484** If so, jump to instruction P2. Otherwise, fall through to the next
57485** instruction.
57486**
57487** If P1 is non-zero, then the jump is taken if the database constraint-counter
57488** is zero (the one that counts deferred constraint violations). If P1 is
57489** zero, the jump is taken if the statement constraint-counter is zero
57490** (immediate foreign key constraint violations).
57491*/
57492case OP_FkIfZero: {         /* jump */
57493  if( pOp->p1 ){
57494    if( db->nDeferredCons==0 ) pc = pOp->p2-1;
57495  }else{
57496    if( p->nFkConstraint==0 ) pc = pOp->p2-1;
57497  }
57498  break;
57499}
57500#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
57501
57502#ifndef SQLITE_OMIT_AUTOINCREMENT
57503/* Opcode: MemMax P1 P2 * * *
57504**
57505** P1 is a register in the root frame of this VM (the root frame is
57506** different from the current frame if this instruction is being executed
57507** within a sub-program). Set the value of register P1 to the maximum of
57508** its current value and the value in register P2.
57509**
57510** This instruction throws an error if the memory cell is not initially
57511** an integer.
57512*/
57513case OP_MemMax: {        /* in2 */
57514#if 0  /* local variables moved into u.ca */
57515  Mem *pIn1;
57516  VdbeFrame *pFrame;
57517#endif /* local variables moved into u.ca */
57518  if( p->pFrame ){
57519    for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
57520    u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
57521  }else{
57522    u.ca.pIn1 = &aMem[pOp->p1];
57523  }
57524  sqlite3VdbeMemIntegerify(u.ca.pIn1);
57525  pIn2 = &aMem[pOp->p2];
57526  sqlite3VdbeMemIntegerify(pIn2);
57527  if( u.ca.pIn1->u.i<pIn2->u.i){
57528    u.ca.pIn1->u.i = pIn2->u.i;
57529  }
57530  break;
57531}
57532#endif /* SQLITE_OMIT_AUTOINCREMENT */
57533
57534/* Opcode: IfPos P1 P2 * * *
57535**
57536** If the value of register P1 is 1 or greater, jump to P2.
57537**
57538** It is illegal to use this instruction on a register that does
57539** not contain an integer.  An assertion fault will result if you try.
57540*/
57541case OP_IfPos: {        /* jump, in1 */
57542  pIn1 = &aMem[pOp->p1];
57543  assert( pIn1->flags&MEM_Int );
57544  if( pIn1->u.i>0 ){
57545     pc = pOp->p2 - 1;
57546  }
57547  break;
57548}
57549
57550/* Opcode: IfNeg P1 P2 * * *
57551**
57552** If the value of register P1 is less than zero, jump to P2.
57553**
57554** It is illegal to use this instruction on a register that does
57555** not contain an integer.  An assertion fault will result if you try.
57556*/
57557case OP_IfNeg: {        /* jump, in1 */
57558  pIn1 = &aMem[pOp->p1];
57559  assert( pIn1->flags&MEM_Int );
57560  if( pIn1->u.i<0 ){
57561     pc = pOp->p2 - 1;
57562  }
57563  break;
57564}
57565
57566/* Opcode: IfZero P1 P2 P3 * *
57567**
57568** The register P1 must contain an integer.  Add literal P3 to the
57569** value in register P1.  If the result is exactly 0, jump to P2.
57570**
57571** It is illegal to use this instruction on a register that does
57572** not contain an integer.  An assertion fault will result if you try.
57573*/
57574case OP_IfZero: {        /* jump, in1 */
57575  pIn1 = &aMem[pOp->p1];
57576  assert( pIn1->flags&MEM_Int );
57577  pIn1->u.i += pOp->p3;
57578  if( pIn1->u.i==0 ){
57579     pc = pOp->p2 - 1;
57580  }
57581  break;
57582}
57583
57584/* Opcode: AggStep * P2 P3 P4 P5
57585**
57586** Execute the step function for an aggregate.  The
57587** function has P5 arguments.   P4 is a pointer to the FuncDef
57588** structure that specifies the function.  Use register
57589** P3 as the accumulator.
57590**
57591** The P5 arguments are taken from register P2 and its
57592** successors.
57593*/
57594case OP_AggStep: {
57595#if 0  /* local variables moved into u.cb */
57596  int n;
57597  int i;
57598  Mem *pMem;
57599  Mem *pRec;
57600  sqlite3_context ctx;
57601  sqlite3_value **apVal;
57602#endif /* local variables moved into u.cb */
57603
57604  u.cb.n = pOp->p5;
57605  assert( u.cb.n>=0 );
57606  u.cb.pRec = &aMem[pOp->p2];
57607  u.cb.apVal = p->apArg;
57608  assert( u.cb.apVal || u.cb.n==0 );
57609  for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
57610    u.cb.apVal[u.cb.i] = u.cb.pRec;
57611    sqlite3VdbeMemStoreType(u.cb.pRec);
57612  }
57613  u.cb.ctx.pFunc = pOp->p4.pFunc;
57614  assert( pOp->p3>0 && pOp->p3<=p->nMem );
57615  u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
57616  u.cb.pMem->n++;
57617  u.cb.ctx.s.flags = MEM_Null;
57618  u.cb.ctx.s.z = 0;
57619  u.cb.ctx.s.zMalloc = 0;
57620  u.cb.ctx.s.xDel = 0;
57621  u.cb.ctx.s.db = db;
57622  u.cb.ctx.isError = 0;
57623  u.cb.ctx.pColl = 0;
57624  if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
57625    assert( pOp>p->aOp );
57626    assert( pOp[-1].p4type==P4_COLLSEQ );
57627    assert( pOp[-1].opcode==OP_CollSeq );
57628    u.cb.ctx.pColl = pOp[-1].p4.pColl;
57629  }
57630  (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal);
57631  if( u.cb.ctx.isError ){
57632    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
57633    rc = u.cb.ctx.isError;
57634  }
57635  sqlite3VdbeMemRelease(&u.cb.ctx.s);
57636  break;
57637}
57638
57639/* Opcode: AggFinal P1 P2 * P4 *
57640**
57641** Execute the finalizer function for an aggregate.  P1 is
57642** the memory location that is the accumulator for the aggregate.
57643**
57644** P2 is the number of arguments that the step function takes and
57645** P4 is a pointer to the FuncDef for this function.  The P2
57646** argument is not used by this opcode.  It is only there to disambiguate
57647** functions that can take varying numbers of arguments.  The
57648** P4 argument is only needed for the degenerate case where
57649** the step function was not previously called.
57650*/
57651case OP_AggFinal: {
57652#if 0  /* local variables moved into u.cc */
57653  Mem *pMem;
57654#endif /* local variables moved into u.cc */
57655  assert( pOp->p1>0 && pOp->p1<=p->nMem );
57656  u.cc.pMem = &aMem[pOp->p1];
57657  assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
57658  rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
57659  if( rc ){
57660    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
57661  }
57662  sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
57663  UPDATE_MAX_BLOBSIZE(u.cc.pMem);
57664  if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
57665    goto too_big;
57666  }
57667  break;
57668}
57669
57670
57671#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
57672/* Opcode: Vacuum * * * * *
57673**
57674** Vacuum the entire database.  This opcode will cause other virtual
57675** machines to be created and run.  It may not be called from within
57676** a transaction.
57677*/
57678case OP_Vacuum: {
57679  rc = sqlite3RunVacuum(&p->zErrMsg, db);
57680  break;
57681}
57682#endif
57683
57684#if !defined(SQLITE_OMIT_AUTOVACUUM)
57685/* Opcode: IncrVacuum P1 P2 * * *
57686**
57687** Perform a single step of the incremental vacuum procedure on
57688** the P1 database. If the vacuum has finished, jump to instruction
57689** P2. Otherwise, fall through to the next instruction.
57690*/
57691case OP_IncrVacuum: {        /* jump */
57692#if 0  /* local variables moved into u.cd */
57693  Btree *pBt;
57694#endif /* local variables moved into u.cd */
57695
57696  assert( pOp->p1>=0 && pOp->p1<db->nDb );
57697  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
57698  u.cd.pBt = db->aDb[pOp->p1].pBt;
57699  rc = sqlite3BtreeIncrVacuum(u.cd.pBt);
57700  if( rc==SQLITE_DONE ){
57701    pc = pOp->p2 - 1;
57702    rc = SQLITE_OK;
57703  }
57704  break;
57705}
57706#endif
57707
57708/* Opcode: Expire P1 * * * *
57709**
57710** Cause precompiled statements to become expired. An expired statement
57711** fails with an error code of SQLITE_SCHEMA if it is ever executed
57712** (via sqlite3_step()).
57713**
57714** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
57715** then only the currently executing statement is affected.
57716*/
57717case OP_Expire: {
57718  if( !pOp->p1 ){
57719    sqlite3ExpirePreparedStatements(db);
57720  }else{
57721    p->expired = 1;
57722  }
57723  break;
57724}
57725
57726#ifndef SQLITE_OMIT_SHARED_CACHE
57727/* Opcode: TableLock P1 P2 P3 P4 *
57728**
57729** Obtain a lock on a particular table. This instruction is only used when
57730** the shared-cache feature is enabled.
57731**
57732** P1 is the index of the database in sqlite3.aDb[] of the database
57733** on which the lock is acquired.  A readlock is obtained if P3==0 or
57734** a write lock if P3==1.
57735**
57736** P2 contains the root-page of the table to lock.
57737**
57738** P4 contains a pointer to the name of the table being locked. This is only
57739** used to generate an error message if the lock cannot be obtained.
57740*/
57741case OP_TableLock: {
57742  u8 isWriteLock = (u8)pOp->p3;
57743  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
57744    int p1 = pOp->p1;
57745    assert( p1>=0 && p1<db->nDb );
57746    assert( (p->btreeMask & (1<<p1))!=0 );
57747    assert( isWriteLock==0 || isWriteLock==1 );
57748    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
57749    if( (rc&0xFF)==SQLITE_LOCKED ){
57750      const char *z = pOp->p4.z;
57751      sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
57752    }
57753  }
57754  break;
57755}
57756#endif /* SQLITE_OMIT_SHARED_CACHE */
57757
57758#ifndef SQLITE_OMIT_VIRTUALTABLE
57759/* Opcode: VBegin * * * P4 *
57760**
57761** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
57762** xBegin method for that table.
57763**
57764** Also, whether or not P4 is set, check that this is not being called from
57765** within a callback to a virtual table xSync() method. If it is, the error
57766** code will be set to SQLITE_LOCKED.
57767*/
57768case OP_VBegin: {
57769#if 0  /* local variables moved into u.ce */
57770  VTable *pVTab;
57771#endif /* local variables moved into u.ce */
57772  u.ce.pVTab = pOp->p4.pVtab;
57773  rc = sqlite3VtabBegin(db, u.ce.pVTab);
57774  if( u.ce.pVTab ){
57775    sqlite3DbFree(db, p->zErrMsg);
57776    p->zErrMsg = u.ce.pVTab->pVtab->zErrMsg;
57777    u.ce.pVTab->pVtab->zErrMsg = 0;
57778  }
57779  break;
57780}
57781#endif /* SQLITE_OMIT_VIRTUALTABLE */
57782
57783#ifndef SQLITE_OMIT_VIRTUALTABLE
57784/* Opcode: VCreate P1 * * P4 *
57785**
57786** P4 is the name of a virtual table in database P1. Call the xCreate method
57787** for that table.
57788*/
57789case OP_VCreate: {
57790  rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
57791  break;
57792}
57793#endif /* SQLITE_OMIT_VIRTUALTABLE */
57794
57795#ifndef SQLITE_OMIT_VIRTUALTABLE
57796/* Opcode: VDestroy P1 * * P4 *
57797**
57798** P4 is the name of a virtual table in database P1.  Call the xDestroy method
57799** of that table.
57800*/
57801case OP_VDestroy: {
57802  p->inVtabMethod = 2;
57803  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
57804  p->inVtabMethod = 0;
57805  break;
57806}
57807#endif /* SQLITE_OMIT_VIRTUALTABLE */
57808
57809#ifndef SQLITE_OMIT_VIRTUALTABLE
57810/* Opcode: VOpen P1 * * P4 *
57811**
57812** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
57813** P1 is a cursor number.  This opcode opens a cursor to the virtual
57814** table and stores that cursor in P1.
57815*/
57816case OP_VOpen: {
57817#if 0  /* local variables moved into u.cf */
57818  VdbeCursor *pCur;
57819  sqlite3_vtab_cursor *pVtabCursor;
57820  sqlite3_vtab *pVtab;
57821  sqlite3_module *pModule;
57822#endif /* local variables moved into u.cf */
57823
57824  u.cf.pCur = 0;
57825  u.cf.pVtabCursor = 0;
57826  u.cf.pVtab = pOp->p4.pVtab->pVtab;
57827  u.cf.pModule = (sqlite3_module *)u.cf.pVtab->pModule;
57828  assert(u.cf.pVtab && u.cf.pModule);
57829  rc = u.cf.pModule->xOpen(u.cf.pVtab, &u.cf.pVtabCursor);
57830  sqlite3DbFree(db, p->zErrMsg);
57831  p->zErrMsg = u.cf.pVtab->zErrMsg;
57832  u.cf.pVtab->zErrMsg = 0;
57833  if( SQLITE_OK==rc ){
57834    /* Initialize sqlite3_vtab_cursor base class */
57835    u.cf.pVtabCursor->pVtab = u.cf.pVtab;
57836
57837    /* Initialise vdbe cursor object */
57838    u.cf.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
57839    if( u.cf.pCur ){
57840      u.cf.pCur->pVtabCursor = u.cf.pVtabCursor;
57841      u.cf.pCur->pModule = u.cf.pVtabCursor->pVtab->pModule;
57842    }else{
57843      db->mallocFailed = 1;
57844      u.cf.pModule->xClose(u.cf.pVtabCursor);
57845    }
57846  }
57847  break;
57848}
57849#endif /* SQLITE_OMIT_VIRTUALTABLE */
57850
57851#ifndef SQLITE_OMIT_VIRTUALTABLE
57852/* Opcode: VFilter P1 P2 P3 P4 *
57853**
57854** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
57855** the filtered result set is empty.
57856**
57857** P4 is either NULL or a string that was generated by the xBestIndex
57858** method of the module.  The interpretation of the P4 string is left
57859** to the module implementation.
57860**
57861** This opcode invokes the xFilter method on the virtual table specified
57862** by P1.  The integer query plan parameter to xFilter is stored in register
57863** P3. Register P3+1 stores the argc parameter to be passed to the
57864** xFilter method. Registers P3+2..P3+1+argc are the argc
57865** additional parameters which are passed to
57866** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
57867**
57868** A jump is made to P2 if the result set after filtering would be empty.
57869*/
57870case OP_VFilter: {   /* jump */
57871#if 0  /* local variables moved into u.cg */
57872  int nArg;
57873  int iQuery;
57874  const sqlite3_module *pModule;
57875  Mem *pQuery;
57876  Mem *pArgc;
57877  sqlite3_vtab_cursor *pVtabCursor;
57878  sqlite3_vtab *pVtab;
57879  VdbeCursor *pCur;
57880  int res;
57881  int i;
57882  Mem **apArg;
57883#endif /* local variables moved into u.cg */
57884
57885  u.cg.pQuery = &aMem[pOp->p3];
57886  u.cg.pArgc = &u.cg.pQuery[1];
57887  u.cg.pCur = p->apCsr[pOp->p1];
57888  REGISTER_TRACE(pOp->p3, u.cg.pQuery);
57889  assert( u.cg.pCur->pVtabCursor );
57890  u.cg.pVtabCursor = u.cg.pCur->pVtabCursor;
57891  u.cg.pVtab = u.cg.pVtabCursor->pVtab;
57892  u.cg.pModule = u.cg.pVtab->pModule;
57893
57894  /* Grab the index number and argc parameters */
57895  assert( (u.cg.pQuery->flags&MEM_Int)!=0 && u.cg.pArgc->flags==MEM_Int );
57896  u.cg.nArg = (int)u.cg.pArgc->u.i;
57897  u.cg.iQuery = (int)u.cg.pQuery->u.i;
57898
57899  /* Invoke the xFilter method */
57900  {
57901    u.cg.res = 0;
57902    u.cg.apArg = p->apArg;
57903    for(u.cg.i = 0; u.cg.i<u.cg.nArg; u.cg.i++){
57904      u.cg.apArg[u.cg.i] = &u.cg.pArgc[u.cg.i+1];
57905      sqlite3VdbeMemStoreType(u.cg.apArg[u.cg.i]);
57906    }
57907
57908    p->inVtabMethod = 1;
57909    rc = u.cg.pModule->xFilter(u.cg.pVtabCursor, u.cg.iQuery, pOp->p4.z, u.cg.nArg, u.cg.apArg);
57910    p->inVtabMethod = 0;
57911    sqlite3DbFree(db, p->zErrMsg);
57912    p->zErrMsg = u.cg.pVtab->zErrMsg;
57913    u.cg.pVtab->zErrMsg = 0;
57914    if( rc==SQLITE_OK ){
57915      u.cg.res = u.cg.pModule->xEof(u.cg.pVtabCursor);
57916    }
57917
57918    if( u.cg.res ){
57919      pc = pOp->p2 - 1;
57920    }
57921  }
57922  u.cg.pCur->nullRow = 0;
57923
57924  break;
57925}
57926#endif /* SQLITE_OMIT_VIRTUALTABLE */
57927
57928#ifndef SQLITE_OMIT_VIRTUALTABLE
57929/* Opcode: VColumn P1 P2 P3 * *
57930**
57931** Store the value of the P2-th column of
57932** the row of the virtual-table that the
57933** P1 cursor is pointing to into register P3.
57934*/
57935case OP_VColumn: {
57936#if 0  /* local variables moved into u.ch */
57937  sqlite3_vtab *pVtab;
57938  const sqlite3_module *pModule;
57939  Mem *pDest;
57940  sqlite3_context sContext;
57941#endif /* local variables moved into u.ch */
57942
57943  VdbeCursor *pCur = p->apCsr[pOp->p1];
57944  assert( pCur->pVtabCursor );
57945  assert( pOp->p3>0 && pOp->p3<=p->nMem );
57946  u.ch.pDest = &aMem[pOp->p3];
57947  if( pCur->nullRow ){
57948    sqlite3VdbeMemSetNull(u.ch.pDest);
57949    break;
57950  }
57951  u.ch.pVtab = pCur->pVtabCursor->pVtab;
57952  u.ch.pModule = u.ch.pVtab->pModule;
57953  assert( u.ch.pModule->xColumn );
57954  memset(&u.ch.sContext, 0, sizeof(u.ch.sContext));
57955
57956  /* The output cell may already have a buffer allocated. Move
57957  ** the current contents to u.ch.sContext.s so in case the user-function
57958  ** can use the already allocated buffer instead of allocating a
57959  ** new one.
57960  */
57961  sqlite3VdbeMemMove(&u.ch.sContext.s, u.ch.pDest);
57962  MemSetTypeFlag(&u.ch.sContext.s, MEM_Null);
57963
57964  rc = u.ch.pModule->xColumn(pCur->pVtabCursor, &u.ch.sContext, pOp->p2);
57965  sqlite3DbFree(db, p->zErrMsg);
57966  p->zErrMsg = u.ch.pVtab->zErrMsg;
57967  u.ch.pVtab->zErrMsg = 0;
57968  if( u.ch.sContext.isError ){
57969    rc = u.ch.sContext.isError;
57970  }
57971
57972  /* Copy the result of the function to the P3 register. We
57973  ** do this regardless of whether or not an error occurred to ensure any
57974  ** dynamic allocation in u.ch.sContext.s (a Mem struct) is  released.
57975  */
57976  sqlite3VdbeChangeEncoding(&u.ch.sContext.s, encoding);
57977  sqlite3VdbeMemMove(u.ch.pDest, &u.ch.sContext.s);
57978  REGISTER_TRACE(pOp->p3, u.ch.pDest);
57979  UPDATE_MAX_BLOBSIZE(u.ch.pDest);
57980
57981  if( sqlite3VdbeMemTooBig(u.ch.pDest) ){
57982    goto too_big;
57983  }
57984  break;
57985}
57986#endif /* SQLITE_OMIT_VIRTUALTABLE */
57987
57988#ifndef SQLITE_OMIT_VIRTUALTABLE
57989/* Opcode: VNext P1 P2 * * *
57990**
57991** Advance virtual table P1 to the next row in its result set and
57992** jump to instruction P2.  Or, if the virtual table has reached
57993** the end of its result set, then fall through to the next instruction.
57994*/
57995case OP_VNext: {   /* jump */
57996#if 0  /* local variables moved into u.ci */
57997  sqlite3_vtab *pVtab;
57998  const sqlite3_module *pModule;
57999  int res;
58000  VdbeCursor *pCur;
58001#endif /* local variables moved into u.ci */
58002
58003  u.ci.res = 0;
58004  u.ci.pCur = p->apCsr[pOp->p1];
58005  assert( u.ci.pCur->pVtabCursor );
58006  if( u.ci.pCur->nullRow ){
58007    break;
58008  }
58009  u.ci.pVtab = u.ci.pCur->pVtabCursor->pVtab;
58010  u.ci.pModule = u.ci.pVtab->pModule;
58011  assert( u.ci.pModule->xNext );
58012
58013  /* Invoke the xNext() method of the module. There is no way for the
58014  ** underlying implementation to return an error if one occurs during
58015  ** xNext(). Instead, if an error occurs, true is returned (indicating that
58016  ** data is available) and the error code returned when xColumn or
58017  ** some other method is next invoked on the save virtual table cursor.
58018  */
58019  p->inVtabMethod = 1;
58020  rc = u.ci.pModule->xNext(u.ci.pCur->pVtabCursor);
58021  p->inVtabMethod = 0;
58022  sqlite3DbFree(db, p->zErrMsg);
58023  p->zErrMsg = u.ci.pVtab->zErrMsg;
58024  u.ci.pVtab->zErrMsg = 0;
58025  if( rc==SQLITE_OK ){
58026    u.ci.res = u.ci.pModule->xEof(u.ci.pCur->pVtabCursor);
58027  }
58028
58029  if( !u.ci.res ){
58030    /* If there is data, jump to P2 */
58031    pc = pOp->p2 - 1;
58032  }
58033  break;
58034}
58035#endif /* SQLITE_OMIT_VIRTUALTABLE */
58036
58037#ifndef SQLITE_OMIT_VIRTUALTABLE
58038/* Opcode: VRename P1 * * P4 *
58039**
58040** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
58041** This opcode invokes the corresponding xRename method. The value
58042** in register P1 is passed as the zName argument to the xRename method.
58043*/
58044case OP_VRename: {
58045#if 0  /* local variables moved into u.cj */
58046  sqlite3_vtab *pVtab;
58047  Mem *pName;
58048#endif /* local variables moved into u.cj */
58049
58050  u.cj.pVtab = pOp->p4.pVtab->pVtab;
58051  u.cj.pName = &aMem[pOp->p1];
58052  assert( u.cj.pVtab->pModule->xRename );
58053  REGISTER_TRACE(pOp->p1, u.cj.pName);
58054  assert( u.cj.pName->flags & MEM_Str );
58055  rc = u.cj.pVtab->pModule->xRename(u.cj.pVtab, u.cj.pName->z);
58056  sqlite3DbFree(db, p->zErrMsg);
58057  p->zErrMsg = u.cj.pVtab->zErrMsg;
58058  u.cj.pVtab->zErrMsg = 0;
58059
58060  break;
58061}
58062#endif
58063
58064#ifndef SQLITE_OMIT_VIRTUALTABLE
58065/* Opcode: VUpdate P1 P2 P3 P4 *
58066**
58067** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
58068** This opcode invokes the corresponding xUpdate method. P2 values
58069** are contiguous memory cells starting at P3 to pass to the xUpdate
58070** invocation. The value in register (P3+P2-1) corresponds to the
58071** p2th element of the argv array passed to xUpdate.
58072**
58073** The xUpdate method will do a DELETE or an INSERT or both.
58074** The argv[0] element (which corresponds to memory cell P3)
58075** is the rowid of a row to delete.  If argv[0] is NULL then no
58076** deletion occurs.  The argv[1] element is the rowid of the new
58077** row.  This can be NULL to have the virtual table select the new
58078** rowid for itself.  The subsequent elements in the array are
58079** the values of columns in the new row.
58080**
58081** If P2==1 then no insert is performed.  argv[0] is the rowid of
58082** a row to delete.
58083**
58084** P1 is a boolean flag. If it is set to true and the xUpdate call
58085** is successful, then the value returned by sqlite3_last_insert_rowid()
58086** is set to the value of the rowid for the row just inserted.
58087*/
58088case OP_VUpdate: {
58089#if 0  /* local variables moved into u.ck */
58090  sqlite3_vtab *pVtab;
58091  sqlite3_module *pModule;
58092  int nArg;
58093  int i;
58094  sqlite_int64 rowid;
58095  Mem **apArg;
58096  Mem *pX;
58097#endif /* local variables moved into u.ck */
58098
58099  u.ck.pVtab = pOp->p4.pVtab->pVtab;
58100  u.ck.pModule = (sqlite3_module *)u.ck.pVtab->pModule;
58101  u.ck.nArg = pOp->p2;
58102  assert( pOp->p4type==P4_VTAB );
58103  if( ALWAYS(u.ck.pModule->xUpdate) ){
58104    u.ck.apArg = p->apArg;
58105    u.ck.pX = &aMem[pOp->p3];
58106    for(u.ck.i=0; u.ck.i<u.ck.nArg; u.ck.i++){
58107      sqlite3VdbeMemStoreType(u.ck.pX);
58108      u.ck.apArg[u.ck.i] = u.ck.pX;
58109      u.ck.pX++;
58110    }
58111    rc = u.ck.pModule->xUpdate(u.ck.pVtab, u.ck.nArg, u.ck.apArg, &u.ck.rowid);
58112    sqlite3DbFree(db, p->zErrMsg);
58113    p->zErrMsg = u.ck.pVtab->zErrMsg;
58114    u.ck.pVtab->zErrMsg = 0;
58115    if( rc==SQLITE_OK && pOp->p1 ){
58116      assert( u.ck.nArg>1 && u.ck.apArg[0] && (u.ck.apArg[0]->flags&MEM_Null) );
58117      db->lastRowid = u.ck.rowid;
58118    }
58119    p->nChange++;
58120  }
58121  break;
58122}
58123#endif /* SQLITE_OMIT_VIRTUALTABLE */
58124
58125#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
58126/* Opcode: Pagecount P1 P2 * * *
58127**
58128** Write the current number of pages in database P1 to memory cell P2.
58129*/
58130case OP_Pagecount: {            /* out2-prerelease */
58131#if 0  /* local variables moved into u.cl */
58132  int p1;
58133  int nPage;
58134  Pager *pPager;
58135#endif /* local variables moved into u.cl */
58136
58137  u.cl.p1 = pOp->p1;
58138  u.cl.pPager = sqlite3BtreePager(db->aDb[u.cl.p1].pBt);
58139  rc = sqlite3PagerPagecount(u.cl.pPager, &u.cl.nPage);
58140  /* OP_Pagecount is always called from within a read transaction.  The
58141  ** page count has already been successfully read and cached.  So the
58142  ** sqlite3PagerPagecount() call above cannot fail. */
58143  if( ALWAYS(rc==SQLITE_OK) ){
58144    pOut->u.i = u.cl.nPage;
58145  }
58146  break;
58147}
58148#endif
58149
58150#ifndef SQLITE_OMIT_TRACE
58151/* Opcode: Trace * * * P4 *
58152**
58153** If tracing is enabled (by the sqlite3_trace()) interface, then
58154** the UTF-8 string contained in P4 is emitted on the trace callback.
58155*/
58156case OP_Trace: {
58157#if 0  /* local variables moved into u.cm */
58158  char *zTrace;
58159#endif /* local variables moved into u.cm */
58160
58161  u.cm.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
58162  if( u.cm.zTrace ){
58163    if( db->xTrace ){
58164      char *z = sqlite3VdbeExpandSql(p, u.cm.zTrace);
58165      db->xTrace(db->pTraceArg, z);
58166      sqlite3DbFree(db, z);
58167    }
58168#ifdef SQLITE_DEBUG
58169    if( (db->flags & SQLITE_SqlTrace)!=0 ){
58170      sqlite3DebugPrintf("SQL-trace: %s\n", u.cm.zTrace);
58171    }
58172#endif /* SQLITE_DEBUG */
58173  }
58174  break;
58175}
58176#endif
58177
58178
58179/* Opcode: Noop * * * * *
58180**
58181** Do nothing.  This instruction is often useful as a jump
58182** destination.
58183*/
58184/*
58185** The magic Explain opcode are only inserted when explain==2 (which
58186** is to say when the EXPLAIN QUERY PLAN syntax is used.)
58187** This opcode records information from the optimizer.  It is the
58188** the same as a no-op.  This opcodesnever appears in a real VM program.
58189*/
58190default: {          /* This is really OP_Noop and OP_Explain */
58191  break;
58192}
58193
58194/*****************************************************************************
58195** The cases of the switch statement above this line should all be indented
58196** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
58197** readability.  From this point on down, the normal indentation rules are
58198** restored.
58199*****************************************************************************/
58200    }
58201
58202#ifdef VDBE_PROFILE
58203    {
58204      u64 elapsed = sqlite3Hwtime() - start;
58205      pOp->cycles += elapsed;
58206      pOp->cnt++;
58207#if 0
58208        fprintf(stdout, "%10llu ", elapsed);
58209        sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
58210#endif
58211    }
58212#endif
58213
58214    /* The following code adds nothing to the actual functionality
58215    ** of the program.  It is only here for testing and debugging.
58216    ** On the other hand, it does burn CPU cycles every time through
58217    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
58218    */
58219#ifndef NDEBUG
58220    assert( pc>=-1 && pc<p->nOp );
58221
58222#ifdef SQLITE_DEBUG
58223    if( p->trace ){
58224      if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
58225      if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
58226        registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
58227      }
58228      if( pOp->opflags & OPFLG_OUT3 ){
58229        registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
58230      }
58231    }
58232#endif  /* SQLITE_DEBUG */
58233#endif  /* NDEBUG */
58234  }  /* The end of the for(;;) loop the loops through opcodes */
58235
58236  /* If we reach this point, it means that execution is finished with
58237  ** an error of some kind.
58238  */
58239vdbe_error_halt:
58240  assert( rc );
58241  p->rc = rc;
58242  sqlite3_log(rc, "prepared statement aborts at %d: [%s]", pc, p->zSql);
58243  sqlite3VdbeHalt(p);
58244  if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
58245  rc = SQLITE_ERROR;
58246  if( resetSchemaOnFault ) sqlite3ResetInternalSchema(db, 0);
58247
58248  /* This is the only way out of this procedure.  We have to
58249  ** release the mutexes on btrees that were acquired at the
58250  ** top. */
58251vdbe_return:
58252  sqlite3BtreeMutexArrayLeave(&p->aMutex);
58253  return rc;
58254
58255  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
58256  ** is encountered.
58257  */
58258too_big:
58259  sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
58260  rc = SQLITE_TOOBIG;
58261  goto vdbe_error_halt;
58262
58263  /* Jump to here if a malloc() fails.
58264  */
58265no_mem:
58266  db->mallocFailed = 1;
58267  sqlite3SetString(&p->zErrMsg, db, "out of memory");
58268  rc = SQLITE_NOMEM;
58269  goto vdbe_error_halt;
58270
58271  /* Jump to here for any other kind of fatal error.  The "rc" variable
58272  ** should hold the error number.
58273  */
58274abort_due_to_error:
58275  assert( p->zErrMsg==0 );
58276  if( db->mallocFailed ) rc = SQLITE_NOMEM;
58277  if( rc!=SQLITE_IOERR_NOMEM ){
58278    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
58279  }
58280  goto vdbe_error_halt;
58281
58282  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
58283  ** flag.
58284  */
58285abort_due_to_interrupt:
58286  assert( db->u1.isInterrupted );
58287  rc = SQLITE_INTERRUPT;
58288  p->rc = rc;
58289  sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
58290  goto vdbe_error_halt;
58291}
58292
58293/************** End of vdbe.c ************************************************/
58294/************** Begin file vdbeblob.c ****************************************/
58295/*
58296** 2007 May 1
58297**
58298** The author disclaims copyright to this source code.  In place of
58299** a legal notice, here is a blessing:
58300**
58301**    May you do good and not evil.
58302**    May you find forgiveness for yourself and forgive others.
58303**    May you share freely, never taking more than you give.
58304**
58305*************************************************************************
58306**
58307** This file contains code used to implement incremental BLOB I/O.
58308*/
58309
58310
58311#ifndef SQLITE_OMIT_INCRBLOB
58312
58313/*
58314** Valid sqlite3_blob* handles point to Incrblob structures.
58315*/
58316typedef struct Incrblob Incrblob;
58317struct Incrblob {
58318  int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
58319  int nByte;              /* Size of open blob, in bytes */
58320  int iOffset;            /* Byte offset of blob in cursor data */
58321  BtCursor *pCsr;         /* Cursor pointing at blob row */
58322  sqlite3_stmt *pStmt;    /* Statement holding cursor open */
58323  sqlite3 *db;            /* The associated database */
58324};
58325
58326/*
58327** Open a blob handle.
58328*/
58329SQLITE_API int sqlite3_blob_open(
58330  sqlite3* db,            /* The database connection */
58331  const char *zDb,        /* The attached database containing the blob */
58332  const char *zTable,     /* The table containing the blob */
58333  const char *zColumn,    /* The column containing the blob */
58334  sqlite_int64 iRow,      /* The row containing the glob */
58335  int flags,              /* True -> read/write access, false -> read-only */
58336  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
58337){
58338  int nAttempt = 0;
58339  int iCol;               /* Index of zColumn in row-record */
58340
58341  /* This VDBE program seeks a btree cursor to the identified
58342  ** db/table/row entry. The reason for using a vdbe program instead
58343  ** of writing code to use the b-tree layer directly is that the
58344  ** vdbe program will take advantage of the various transaction,
58345  ** locking and error handling infrastructure built into the vdbe.
58346  **
58347  ** After seeking the cursor, the vdbe executes an OP_ResultRow.
58348  ** Code external to the Vdbe then "borrows" the b-tree cursor and
58349  ** uses it to implement the blob_read(), blob_write() and
58350  ** blob_bytes() functions.
58351  **
58352  ** The sqlite3_blob_close() function finalizes the vdbe program,
58353  ** which closes the b-tree cursor and (possibly) commits the
58354  ** transaction.
58355  */
58356  static const VdbeOpList openBlob[] = {
58357    {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
58358    {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
58359    {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
58360
58361    /* One of the following two instructions is replaced by an OP_Noop. */
58362    {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
58363    {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
58364
58365    {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
58366    {OP_NotExists, 0, 9, 1},       /* 6: Seek the cursor */
58367    {OP_Column, 0, 0, 1},          /* 7  */
58368    {OP_ResultRow, 1, 0, 0},       /* 8  */
58369    {OP_Close, 0, 0, 0},           /* 9  */
58370    {OP_Halt, 0, 0, 0},            /* 10 */
58371  };
58372
58373  Vdbe *v = 0;
58374  int rc = SQLITE_OK;
58375  char *zErr = 0;
58376  Table *pTab;
58377  Parse *pParse;
58378
58379  *ppBlob = 0;
58380  sqlite3_mutex_enter(db->mutex);
58381  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
58382  if( pParse==0 ){
58383    rc = SQLITE_NOMEM;
58384    goto blob_open_out;
58385  }
58386  do {
58387    memset(pParse, 0, sizeof(Parse));
58388    pParse->db = db;
58389
58390    sqlite3BtreeEnterAll(db);
58391    pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
58392    if( pTab && IsVirtual(pTab) ){
58393      pTab = 0;
58394      sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
58395    }
58396#ifndef SQLITE_OMIT_VIEW
58397    if( pTab && pTab->pSelect ){
58398      pTab = 0;
58399      sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
58400    }
58401#endif
58402    if( !pTab ){
58403      if( pParse->zErrMsg ){
58404        sqlite3DbFree(db, zErr);
58405        zErr = pParse->zErrMsg;
58406        pParse->zErrMsg = 0;
58407      }
58408      rc = SQLITE_ERROR;
58409      sqlite3BtreeLeaveAll(db);
58410      goto blob_open_out;
58411    }
58412
58413    /* Now search pTab for the exact column. */
58414    for(iCol=0; iCol < pTab->nCol; iCol++) {
58415      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
58416        break;
58417      }
58418    }
58419    if( iCol==pTab->nCol ){
58420      sqlite3DbFree(db, zErr);
58421      zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
58422      rc = SQLITE_ERROR;
58423      sqlite3BtreeLeaveAll(db);
58424      goto blob_open_out;
58425    }
58426
58427    /* If the value is being opened for writing, check that the
58428    ** column is not indexed, and that it is not part of a foreign key.
58429    ** It is against the rules to open a column to which either of these
58430    ** descriptions applies for writing.  */
58431    if( flags ){
58432      const char *zFault = 0;
58433      Index *pIdx;
58434#ifndef SQLITE_OMIT_FOREIGN_KEY
58435      if( db->flags&SQLITE_ForeignKeys ){
58436        /* Check that the column is not part of an FK child key definition. It
58437        ** is not necessary to check if it is part of a parent key, as parent
58438        ** key columns must be indexed. The check below will pick up this
58439        ** case.  */
58440        FKey *pFKey;
58441        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
58442          int j;
58443          for(j=0; j<pFKey->nCol; j++){
58444            if( pFKey->aCol[j].iFrom==iCol ){
58445              zFault = "foreign key";
58446            }
58447          }
58448        }
58449      }
58450#endif
58451      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
58452        int j;
58453        for(j=0; j<pIdx->nColumn; j++){
58454          if( pIdx->aiColumn[j]==iCol ){
58455            zFault = "indexed";
58456          }
58457        }
58458      }
58459      if( zFault ){
58460        sqlite3DbFree(db, zErr);
58461        zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
58462        rc = SQLITE_ERROR;
58463        sqlite3BtreeLeaveAll(db);
58464        goto blob_open_out;
58465      }
58466    }
58467
58468    v = sqlite3VdbeCreate(db);
58469    if( v ){
58470      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
58471      sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
58472      flags = !!flags;                 /* flags = (flags ? 1 : 0); */
58473
58474      /* Configure the OP_Transaction */
58475      sqlite3VdbeChangeP1(v, 0, iDb);
58476      sqlite3VdbeChangeP2(v, 0, flags);
58477
58478      /* Configure the OP_VerifyCookie */
58479      sqlite3VdbeChangeP1(v, 1, iDb);
58480      sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
58481
58482      /* Make sure a mutex is held on the table to be accessed */
58483      sqlite3VdbeUsesBtree(v, iDb);
58484
58485      /* Configure the OP_TableLock instruction */
58486      sqlite3VdbeChangeP1(v, 2, iDb);
58487      sqlite3VdbeChangeP2(v, 2, pTab->tnum);
58488      sqlite3VdbeChangeP3(v, 2, flags);
58489      sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
58490
58491      /* Remove either the OP_OpenWrite or OpenRead. Set the P2
58492      ** parameter of the other to pTab->tnum.  */
58493      sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
58494      sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
58495      sqlite3VdbeChangeP3(v, 3 + flags, iDb);
58496
58497      /* Configure the number of columns. Configure the cursor to
58498      ** think that the table has one more column than it really
58499      ** does. An OP_Column to retrieve this imaginary column will
58500      ** always return an SQL NULL. This is useful because it means
58501      ** we can invoke OP_Column to fill in the vdbe cursors type
58502      ** and offset cache without causing any IO.
58503      */
58504      sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
58505      sqlite3VdbeChangeP2(v, 7, pTab->nCol);
58506      if( !db->mallocFailed ){
58507        sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
58508      }
58509    }
58510
58511    sqlite3BtreeLeaveAll(db);
58512    if( db->mallocFailed ){
58513      goto blob_open_out;
58514    }
58515
58516    sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
58517    rc = sqlite3_step((sqlite3_stmt *)v);
58518    if( rc!=SQLITE_ROW ){
58519      nAttempt++;
58520      rc = sqlite3_finalize((sqlite3_stmt *)v);
58521      sqlite3DbFree(db, zErr);
58522      zErr = sqlite3MPrintf(db, sqlite3_errmsg(db));
58523      v = 0;
58524    }
58525  } while( nAttempt<5 && rc==SQLITE_SCHEMA );
58526
58527  if( rc==SQLITE_ROW ){
58528    /* The row-record has been opened successfully. Check that the
58529    ** column in question contains text or a blob. If it contains
58530    ** text, it is up to the caller to get the encoding right.
58531    */
58532    Incrblob *pBlob;
58533    u32 type = v->apCsr[0]->aType[iCol];
58534
58535    if( type<12 ){
58536      sqlite3DbFree(db, zErr);
58537      zErr = sqlite3MPrintf(db, "cannot open value of type %s",
58538          type==0?"null": type==7?"real": "integer"
58539      );
58540      rc = SQLITE_ERROR;
58541      goto blob_open_out;
58542    }
58543    pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
58544    if( db->mallocFailed ){
58545      sqlite3DbFree(db, pBlob);
58546      goto blob_open_out;
58547    }
58548    pBlob->flags = flags;
58549    pBlob->pCsr =  v->apCsr[0]->pCursor;
58550    sqlite3BtreeEnterCursor(pBlob->pCsr);
58551    sqlite3BtreeCacheOverflow(pBlob->pCsr);
58552    sqlite3BtreeLeaveCursor(pBlob->pCsr);
58553    pBlob->pStmt = (sqlite3_stmt *)v;
58554    pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
58555    pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
58556    pBlob->db = db;
58557    *ppBlob = (sqlite3_blob *)pBlob;
58558    rc = SQLITE_OK;
58559  }else if( rc==SQLITE_OK ){
58560    sqlite3DbFree(db, zErr);
58561    zErr = sqlite3MPrintf(db, "no such rowid: %lld", iRow);
58562    rc = SQLITE_ERROR;
58563  }
58564
58565blob_open_out:
58566  if( v && (rc!=SQLITE_OK || db->mallocFailed) ){
58567    sqlite3VdbeFinalize(v);
58568  }
58569  sqlite3Error(db, rc, zErr);
58570  sqlite3DbFree(db, zErr);
58571  sqlite3StackFree(db, pParse);
58572  rc = sqlite3ApiExit(db, rc);
58573  sqlite3_mutex_leave(db->mutex);
58574  return rc;
58575}
58576
58577/*
58578** Close a blob handle that was previously created using
58579** sqlite3_blob_open().
58580*/
58581SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
58582  Incrblob *p = (Incrblob *)pBlob;
58583  int rc;
58584  sqlite3 *db;
58585
58586  if( p ){
58587    db = p->db;
58588    sqlite3_mutex_enter(db->mutex);
58589    rc = sqlite3_finalize(p->pStmt);
58590    sqlite3DbFree(db, p);
58591    sqlite3_mutex_leave(db->mutex);
58592  }else{
58593    rc = SQLITE_OK;
58594  }
58595  return rc;
58596}
58597
58598/*
58599** Perform a read or write operation on a blob
58600*/
58601static int blobReadWrite(
58602  sqlite3_blob *pBlob,
58603  void *z,
58604  int n,
58605  int iOffset,
58606  int (*xCall)(BtCursor*, u32, u32, void*)
58607){
58608  int rc;
58609  Incrblob *p = (Incrblob *)pBlob;
58610  Vdbe *v;
58611  sqlite3 *db;
58612
58613  if( p==0 ) return SQLITE_MISUSE_BKPT;
58614  db = p->db;
58615  sqlite3_mutex_enter(db->mutex);
58616  v = (Vdbe*)p->pStmt;
58617
58618  if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
58619    /* Request is out of range. Return a transient error. */
58620    rc = SQLITE_ERROR;
58621    sqlite3Error(db, SQLITE_ERROR, 0);
58622  } else if( v==0 ){
58623    /* If there is no statement handle, then the blob-handle has
58624    ** already been invalidated. Return SQLITE_ABORT in this case.
58625    */
58626    rc = SQLITE_ABORT;
58627  }else{
58628    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
58629    ** returned, clean-up the statement handle.
58630    */
58631    assert( db == v->db );
58632    sqlite3BtreeEnterCursor(p->pCsr);
58633    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
58634    sqlite3BtreeLeaveCursor(p->pCsr);
58635    if( rc==SQLITE_ABORT ){
58636      sqlite3VdbeFinalize(v);
58637      p->pStmt = 0;
58638    }else{
58639      db->errCode = rc;
58640      v->rc = rc;
58641    }
58642  }
58643  rc = sqlite3ApiExit(db, rc);
58644  sqlite3_mutex_leave(db->mutex);
58645  return rc;
58646}
58647
58648/*
58649** Read data from a blob handle.
58650*/
58651SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
58652  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
58653}
58654
58655/*
58656** Write data to a blob handle.
58657*/
58658SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
58659  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
58660}
58661
58662/*
58663** Query a blob handle for the size of the data.
58664**
58665** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
58666** so no mutex is required for access.
58667*/
58668SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
58669  Incrblob *p = (Incrblob *)pBlob;
58670  return p ? p->nByte : 0;
58671}
58672
58673#endif /* #ifndef SQLITE_OMIT_INCRBLOB */
58674
58675/************** End of vdbeblob.c ********************************************/
58676/************** Begin file journal.c *****************************************/
58677/*
58678** 2007 August 22
58679**
58680** The author disclaims copyright to this source code.  In place of
58681** a legal notice, here is a blessing:
58682**
58683**    May you do good and not evil.
58684**    May you find forgiveness for yourself and forgive others.
58685**    May you share freely, never taking more than you give.
58686**
58687*************************************************************************
58688**
58689** This file implements a special kind of sqlite3_file object used
58690** by SQLite to create journal files if the atomic-write optimization
58691** is enabled.
58692**
58693** The distinctive characteristic of this sqlite3_file is that the
58694** actual on disk file is created lazily. When the file is created,
58695** the caller specifies a buffer size for an in-memory buffer to
58696** be used to service read() and write() requests. The actual file
58697** on disk is not created or populated until either:
58698**
58699**   1) The in-memory representation grows too large for the allocated
58700**      buffer, or
58701**   2) The sqlite3JournalCreate() function is called.
58702*/
58703#ifdef SQLITE_ENABLE_ATOMIC_WRITE
58704
58705
58706/*
58707** A JournalFile object is a subclass of sqlite3_file used by
58708** as an open file handle for journal files.
58709*/
58710struct JournalFile {
58711  sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
58712  int nBuf;                       /* Size of zBuf[] in bytes */
58713  char *zBuf;                     /* Space to buffer journal writes */
58714  int iSize;                      /* Amount of zBuf[] currently used */
58715  int flags;                      /* xOpen flags */
58716  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
58717  sqlite3_file *pReal;            /* The "real" underlying file descriptor */
58718  const char *zJournal;           /* Name of the journal file */
58719};
58720typedef struct JournalFile JournalFile;
58721
58722/*
58723** If it does not already exists, create and populate the on-disk file
58724** for JournalFile p.
58725*/
58726static int createFile(JournalFile *p){
58727  int rc = SQLITE_OK;
58728  if( !p->pReal ){
58729    sqlite3_file *pReal = (sqlite3_file *)&p[1];
58730    rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
58731    if( rc==SQLITE_OK ){
58732      p->pReal = pReal;
58733      if( p->iSize>0 ){
58734        assert(p->iSize<=p->nBuf);
58735        rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
58736      }
58737    }
58738  }
58739  return rc;
58740}
58741
58742/*
58743** Close the file.
58744*/
58745static int jrnlClose(sqlite3_file *pJfd){
58746  JournalFile *p = (JournalFile *)pJfd;
58747  if( p->pReal ){
58748    sqlite3OsClose(p->pReal);
58749  }
58750  sqlite3_free(p->zBuf);
58751  return SQLITE_OK;
58752}
58753
58754/*
58755** Read data from the file.
58756*/
58757static int jrnlRead(
58758  sqlite3_file *pJfd,    /* The journal file from which to read */
58759  void *zBuf,            /* Put the results here */
58760  int iAmt,              /* Number of bytes to read */
58761  sqlite_int64 iOfst     /* Begin reading at this offset */
58762){
58763  int rc = SQLITE_OK;
58764  JournalFile *p = (JournalFile *)pJfd;
58765  if( p->pReal ){
58766    rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
58767  }else if( (iAmt+iOfst)>p->iSize ){
58768    rc = SQLITE_IOERR_SHORT_READ;
58769  }else{
58770    memcpy(zBuf, &p->zBuf[iOfst], iAmt);
58771  }
58772  return rc;
58773}
58774
58775/*
58776** Write data to the file.
58777*/
58778static int jrnlWrite(
58779  sqlite3_file *pJfd,    /* The journal file into which to write */
58780  const void *zBuf,      /* Take data to be written from here */
58781  int iAmt,              /* Number of bytes to write */
58782  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
58783){
58784  int rc = SQLITE_OK;
58785  JournalFile *p = (JournalFile *)pJfd;
58786  if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
58787    rc = createFile(p);
58788  }
58789  if( rc==SQLITE_OK ){
58790    if( p->pReal ){
58791      rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
58792    }else{
58793      memcpy(&p->zBuf[iOfst], zBuf, iAmt);
58794      if( p->iSize<(iOfst+iAmt) ){
58795        p->iSize = (iOfst+iAmt);
58796      }
58797    }
58798  }
58799  return rc;
58800}
58801
58802/*
58803** Truncate the file.
58804*/
58805static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
58806  int rc = SQLITE_OK;
58807  JournalFile *p = (JournalFile *)pJfd;
58808  if( p->pReal ){
58809    rc = sqlite3OsTruncate(p->pReal, size);
58810  }else if( size<p->iSize ){
58811    p->iSize = size;
58812  }
58813  return rc;
58814}
58815
58816/*
58817** Sync the file.
58818*/
58819static int jrnlSync(sqlite3_file *pJfd, int flags){
58820  int rc;
58821  JournalFile *p = (JournalFile *)pJfd;
58822  if( p->pReal ){
58823    rc = sqlite3OsSync(p->pReal, flags);
58824  }else{
58825    rc = SQLITE_OK;
58826  }
58827  return rc;
58828}
58829
58830/*
58831** Query the size of the file in bytes.
58832*/
58833static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
58834  int rc = SQLITE_OK;
58835  JournalFile *p = (JournalFile *)pJfd;
58836  if( p->pReal ){
58837    rc = sqlite3OsFileSize(p->pReal, pSize);
58838  }else{
58839    *pSize = (sqlite_int64) p->iSize;
58840  }
58841  return rc;
58842}
58843
58844/*
58845** Table of methods for JournalFile sqlite3_file object.
58846*/
58847static struct sqlite3_io_methods JournalFileMethods = {
58848  1,             /* iVersion */
58849  jrnlClose,     /* xClose */
58850  jrnlRead,      /* xRead */
58851  jrnlWrite,     /* xWrite */
58852  jrnlTruncate,  /* xTruncate */
58853  jrnlSync,      /* xSync */
58854  jrnlFileSize,  /* xFileSize */
58855  0,             /* xLock */
58856  0,             /* xUnlock */
58857  0,             /* xCheckReservedLock */
58858  0,             /* xFileControl */
58859  0,             /* xSectorSize */
58860  0              /* xDeviceCharacteristics */
58861};
58862
58863/*
58864** Open a journal file.
58865*/
58866SQLITE_PRIVATE int sqlite3JournalOpen(
58867  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
58868  const char *zName,         /* Name of the journal file */
58869  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
58870  int flags,                 /* Opening flags */
58871  int nBuf                   /* Bytes buffered before opening the file */
58872){
58873  JournalFile *p = (JournalFile *)pJfd;
58874  memset(p, 0, sqlite3JournalSize(pVfs));
58875  if( nBuf>0 ){
58876    p->zBuf = sqlite3MallocZero(nBuf);
58877    if( !p->zBuf ){
58878      return SQLITE_NOMEM;
58879    }
58880  }else{
58881    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
58882  }
58883  p->pMethod = &JournalFileMethods;
58884  p->nBuf = nBuf;
58885  p->flags = flags;
58886  p->zJournal = zName;
58887  p->pVfs = pVfs;
58888  return SQLITE_OK;
58889}
58890
58891/*
58892** If the argument p points to a JournalFile structure, and the underlying
58893** file has not yet been created, create it now.
58894*/
58895SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
58896  if( p->pMethods!=&JournalFileMethods ){
58897    return SQLITE_OK;
58898  }
58899  return createFile((JournalFile *)p);
58900}
58901
58902/*
58903** Return the number of bytes required to store a JournalFile that uses vfs
58904** pVfs to create the underlying on-disk files.
58905*/
58906SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
58907  return (pVfs->szOsFile+sizeof(JournalFile));
58908}
58909#endif
58910
58911/************** End of journal.c *********************************************/
58912/************** Begin file memjournal.c **************************************/
58913/*
58914** 2008 October 7
58915**
58916** The author disclaims copyright to this source code.  In place of
58917** a legal notice, here is a blessing:
58918**
58919**    May you do good and not evil.
58920**    May you find forgiveness for yourself and forgive others.
58921**    May you share freely, never taking more than you give.
58922**
58923*************************************************************************
58924**
58925** This file contains code use to implement an in-memory rollback journal.
58926** The in-memory rollback journal is used to journal transactions for
58927** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
58928*/
58929
58930/* Forward references to internal structures */
58931typedef struct MemJournal MemJournal;
58932typedef struct FilePoint FilePoint;
58933typedef struct FileChunk FileChunk;
58934
58935/* Space to hold the rollback journal is allocated in increments of
58936** this many bytes.
58937**
58938** The size chosen is a little less than a power of two.  That way,
58939** the FileChunk object will have a size that almost exactly fills
58940** a power-of-two allocation.  This mimimizes wasted space in power-of-two
58941** memory allocators.
58942*/
58943#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
58944
58945/* Macro to find the minimum of two numeric values.
58946*/
58947#ifndef MIN
58948# define MIN(x,y) ((x)<(y)?(x):(y))
58949#endif
58950
58951/*
58952** The rollback journal is composed of a linked list of these structures.
58953*/
58954struct FileChunk {
58955  FileChunk *pNext;               /* Next chunk in the journal */
58956  u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
58957};
58958
58959/*
58960** An instance of this object serves as a cursor into the rollback journal.
58961** The cursor can be either for reading or writing.
58962*/
58963struct FilePoint {
58964  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
58965  FileChunk *pChunk;              /* Specific chunk into which cursor points */
58966};
58967
58968/*
58969** This subclass is a subclass of sqlite3_file.  Each open memory-journal
58970** is an instance of this class.
58971*/
58972struct MemJournal {
58973  sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
58974  FileChunk *pFirst;              /* Head of in-memory chunk-list */
58975  FilePoint endpoint;             /* Pointer to the end of the file */
58976  FilePoint readpoint;            /* Pointer to the end of the last xRead() */
58977};
58978
58979/*
58980** Read data from the in-memory journal file.  This is the implementation
58981** of the sqlite3_vfs.xRead method.
58982*/
58983static int memjrnlRead(
58984  sqlite3_file *pJfd,    /* The journal file from which to read */
58985  void *zBuf,            /* Put the results here */
58986  int iAmt,              /* Number of bytes to read */
58987  sqlite_int64 iOfst     /* Begin reading at this offset */
58988){
58989  MemJournal *p = (MemJournal *)pJfd;
58990  u8 *zOut = zBuf;
58991  int nRead = iAmt;
58992  int iChunkOffset;
58993  FileChunk *pChunk;
58994
58995  /* SQLite never tries to read past the end of a rollback journal file */
58996  assert( iOfst+iAmt<=p->endpoint.iOffset );
58997
58998  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
58999    sqlite3_int64 iOff = 0;
59000    for(pChunk=p->pFirst;
59001        ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
59002        pChunk=pChunk->pNext
59003    ){
59004      iOff += JOURNAL_CHUNKSIZE;
59005    }
59006  }else{
59007    pChunk = p->readpoint.pChunk;
59008  }
59009
59010  iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
59011  do {
59012    int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
59013    int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
59014    memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
59015    zOut += nCopy;
59016    nRead -= iSpace;
59017    iChunkOffset = 0;
59018  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
59019  p->readpoint.iOffset = iOfst+iAmt;
59020  p->readpoint.pChunk = pChunk;
59021
59022  return SQLITE_OK;
59023}
59024
59025/*
59026** Write data to the file.
59027*/
59028static int memjrnlWrite(
59029  sqlite3_file *pJfd,    /* The journal file into which to write */
59030  const void *zBuf,      /* Take data to be written from here */
59031  int iAmt,              /* Number of bytes to write */
59032  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
59033){
59034  MemJournal *p = (MemJournal *)pJfd;
59035  int nWrite = iAmt;
59036  u8 *zWrite = (u8 *)zBuf;
59037
59038  /* An in-memory journal file should only ever be appended to. Random
59039  ** access writes are not required by sqlite.
59040  */
59041  assert( iOfst==p->endpoint.iOffset );
59042  UNUSED_PARAMETER(iOfst);
59043
59044  while( nWrite>0 ){
59045    FileChunk *pChunk = p->endpoint.pChunk;
59046    int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
59047    int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
59048
59049    if( iChunkOffset==0 ){
59050      /* New chunk is required to extend the file. */
59051      FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
59052      if( !pNew ){
59053        return SQLITE_IOERR_NOMEM;
59054      }
59055      pNew->pNext = 0;
59056      if( pChunk ){
59057        assert( p->pFirst );
59058        pChunk->pNext = pNew;
59059      }else{
59060        assert( !p->pFirst );
59061        p->pFirst = pNew;
59062      }
59063      p->endpoint.pChunk = pNew;
59064    }
59065
59066    memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
59067    zWrite += iSpace;
59068    nWrite -= iSpace;
59069    p->endpoint.iOffset += iSpace;
59070  }
59071
59072  return SQLITE_OK;
59073}
59074
59075/*
59076** Truncate the file.
59077*/
59078static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
59079  MemJournal *p = (MemJournal *)pJfd;
59080  FileChunk *pChunk;
59081  assert(size==0);
59082  UNUSED_PARAMETER(size);
59083  pChunk = p->pFirst;
59084  while( pChunk ){
59085    FileChunk *pTmp = pChunk;
59086    pChunk = pChunk->pNext;
59087    sqlite3_free(pTmp);
59088  }
59089  sqlite3MemJournalOpen(pJfd);
59090  return SQLITE_OK;
59091}
59092
59093/*
59094** Close the file.
59095*/
59096static int memjrnlClose(sqlite3_file *pJfd){
59097  memjrnlTruncate(pJfd, 0);
59098  return SQLITE_OK;
59099}
59100
59101
59102/*
59103** Sync the file.
59104**
59105** Syncing an in-memory journal is a no-op.  And, in fact, this routine
59106** is never called in a working implementation.  This implementation
59107** exists purely as a contingency, in case some malfunction in some other
59108** part of SQLite causes Sync to be called by mistake.
59109*/
59110static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){   /*NO_TEST*/
59111  UNUSED_PARAMETER2(NotUsed, NotUsed2);                        /*NO_TEST*/
59112  assert( 0 );                                                 /*NO_TEST*/
59113  return SQLITE_OK;                                            /*NO_TEST*/
59114}                                                              /*NO_TEST*/
59115
59116/*
59117** Query the size of the file in bytes.
59118*/
59119static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
59120  MemJournal *p = (MemJournal *)pJfd;
59121  *pSize = (sqlite_int64) p->endpoint.iOffset;
59122  return SQLITE_OK;
59123}
59124
59125/*
59126** Table of methods for MemJournal sqlite3_file object.
59127*/
59128static struct sqlite3_io_methods MemJournalMethods = {
59129  1,                /* iVersion */
59130  memjrnlClose,     /* xClose */
59131  memjrnlRead,      /* xRead */
59132  memjrnlWrite,     /* xWrite */
59133  memjrnlTruncate,  /* xTruncate */
59134  memjrnlSync,      /* xSync */
59135  memjrnlFileSize,  /* xFileSize */
59136  0,                /* xLock */
59137  0,                /* xUnlock */
59138  0,                /* xCheckReservedLock */
59139  0,                /* xFileControl */
59140  0,                /* xSectorSize */
59141  0                 /* xDeviceCharacteristics */
59142};
59143
59144/*
59145** Open a journal file.
59146*/
59147SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
59148  MemJournal *p = (MemJournal *)pJfd;
59149  assert( EIGHT_BYTE_ALIGNMENT(p) );
59150  memset(p, 0, sqlite3MemJournalSize());
59151  p->pMethod = &MemJournalMethods;
59152}
59153
59154/*
59155** Return true if the file-handle passed as an argument is
59156** an in-memory journal
59157*/
59158SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
59159  return pJfd->pMethods==&MemJournalMethods;
59160}
59161
59162/*
59163** Return the number of bytes required to store a MemJournal that uses vfs
59164** pVfs to create the underlying on-disk files.
59165*/
59166SQLITE_PRIVATE int sqlite3MemJournalSize(void){
59167  return sizeof(MemJournal);
59168}
59169
59170/************** End of memjournal.c ******************************************/
59171/************** Begin file walker.c ******************************************/
59172/*
59173** 2008 August 16
59174**
59175** The author disclaims copyright to this source code.  In place of
59176** a legal notice, here is a blessing:
59177**
59178**    May you do good and not evil.
59179**    May you find forgiveness for yourself and forgive others.
59180**    May you share freely, never taking more than you give.
59181**
59182*************************************************************************
59183** This file contains routines used for walking the parser tree for
59184** an SQL statement.
59185*/
59186
59187
59188/*
59189** Walk an expression tree.  Invoke the callback once for each node
59190** of the expression, while decending.  (In other words, the callback
59191** is invoked before visiting children.)
59192**
59193** The return value from the callback should be one of the WRC_*
59194** constants to specify how to proceed with the walk.
59195**
59196**    WRC_Continue      Continue descending down the tree.
59197**
59198**    WRC_Prune         Do not descend into child nodes.  But allow
59199**                      the walk to continue with sibling nodes.
59200**
59201**    WRC_Abort         Do no more callbacks.  Unwind the stack and
59202**                      return the top-level walk call.
59203**
59204** The return value from this routine is WRC_Abort to abandon the tree walk
59205** and WRC_Continue to continue.
59206*/
59207SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
59208  int rc;
59209  if( pExpr==0 ) return WRC_Continue;
59210  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
59211  testcase( ExprHasProperty(pExpr, EP_Reduced) );
59212  rc = pWalker->xExprCallback(pWalker, pExpr);
59213  if( rc==WRC_Continue
59214              && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
59215    if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
59216    if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
59217    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
59218      if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
59219    }else{
59220      if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
59221    }
59222  }
59223  return rc & WRC_Abort;
59224}
59225
59226/*
59227** Call sqlite3WalkExpr() for every expression in list p or until
59228** an abort request is seen.
59229*/
59230SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
59231  int i;
59232  struct ExprList_item *pItem;
59233  if( p ){
59234    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
59235      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
59236    }
59237  }
59238  return WRC_Continue;
59239}
59240
59241/*
59242** Walk all expressions associated with SELECT statement p.  Do
59243** not invoke the SELECT callback on p, but do (of course) invoke
59244** any expr callbacks and SELECT callbacks that come from subqueries.
59245** Return WRC_Abort or WRC_Continue.
59246*/
59247SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
59248  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
59249  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
59250  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
59251  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
59252  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
59253  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
59254  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
59255  return WRC_Continue;
59256}
59257
59258/*
59259** Walk the parse trees associated with all subqueries in the
59260** FROM clause of SELECT statement p.  Do not invoke the select
59261** callback on p, but do invoke it on each FROM clause subquery
59262** and on any subqueries further down in the tree.  Return
59263** WRC_Abort or WRC_Continue;
59264*/
59265SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
59266  SrcList *pSrc;
59267  int i;
59268  struct SrcList_item *pItem;
59269
59270  pSrc = p->pSrc;
59271  if( ALWAYS(pSrc) ){
59272    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
59273      if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
59274        return WRC_Abort;
59275      }
59276    }
59277  }
59278  return WRC_Continue;
59279}
59280
59281/*
59282** Call sqlite3WalkExpr() for every expression in Select statement p.
59283** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
59284** on the compound select chain, p->pPrior.
59285**
59286** Return WRC_Continue under normal conditions.  Return WRC_Abort if
59287** there is an abort request.
59288**
59289** If the Walker does not have an xSelectCallback() then this routine
59290** is a no-op returning WRC_Continue.
59291*/
59292SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
59293  int rc;
59294  if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
59295  rc = WRC_Continue;
59296  while( p  ){
59297    rc = pWalker->xSelectCallback(pWalker, p);
59298    if( rc ) break;
59299    if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
59300    if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
59301    p = p->pPrior;
59302  }
59303  return rc & WRC_Abort;
59304}
59305
59306/************** End of walker.c **********************************************/
59307/************** Begin file resolve.c *****************************************/
59308/*
59309** 2008 August 18
59310**
59311** The author disclaims copyright to this source code.  In place of
59312** a legal notice, here is a blessing:
59313**
59314**    May you do good and not evil.
59315**    May you find forgiveness for yourself and forgive others.
59316**    May you share freely, never taking more than you give.
59317**
59318*************************************************************************
59319**
59320** This file contains routines used for walking the parser tree and
59321** resolve all identifiers by associating them with a particular
59322** table and column.
59323*/
59324
59325/*
59326** Turn the pExpr expression into an alias for the iCol-th column of the
59327** result set in pEList.
59328**
59329** If the result set column is a simple column reference, then this routine
59330** makes an exact copy.  But for any other kind of expression, this
59331** routine make a copy of the result set column as the argument to the
59332** TK_AS operator.  The TK_AS operator causes the expression to be
59333** evaluated just once and then reused for each alias.
59334**
59335** The reason for suppressing the TK_AS term when the expression is a simple
59336** column reference is so that the column reference will be recognized as
59337** usable by indices within the WHERE clause processing logic.
59338**
59339** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
59340** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
59341**
59342**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
59343**
59344** Is equivalent to:
59345**
59346**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
59347**
59348** The result of random()%5 in the GROUP BY clause is probably different
59349** from the result in the result-set.  We might fix this someday.  Or
59350** then again, we might not...
59351*/
59352static void resolveAlias(
59353  Parse *pParse,         /* Parsing context */
59354  ExprList *pEList,      /* A result set */
59355  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
59356  Expr *pExpr,           /* Transform this into an alias to the result set */
59357  const char *zType      /* "GROUP" or "ORDER" or "" */
59358){
59359  Expr *pOrig;           /* The iCol-th column of the result set */
59360  Expr *pDup;            /* Copy of pOrig */
59361  sqlite3 *db;           /* The database connection */
59362
59363  assert( iCol>=0 && iCol<pEList->nExpr );
59364  pOrig = pEList->a[iCol].pExpr;
59365  assert( pOrig!=0 );
59366  assert( pOrig->flags & EP_Resolved );
59367  db = pParse->db;
59368  if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
59369    pDup = sqlite3ExprDup(db, pOrig, 0);
59370    pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
59371    if( pDup==0 ) return;
59372    if( pEList->a[iCol].iAlias==0 ){
59373      pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
59374    }
59375    pDup->iTable = pEList->a[iCol].iAlias;
59376  }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
59377    pDup = sqlite3ExprDup(db, pOrig, 0);
59378    if( pDup==0 ) return;
59379  }else{
59380    char *zToken = pOrig->u.zToken;
59381    assert( zToken!=0 );
59382    pOrig->u.zToken = 0;
59383    pDup = sqlite3ExprDup(db, pOrig, 0);
59384    pOrig->u.zToken = zToken;
59385    if( pDup==0 ) return;
59386    assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
59387    pDup->flags2 |= EP2_MallocedToken;
59388    pDup->u.zToken = sqlite3DbStrDup(db, zToken);
59389  }
59390  if( pExpr->flags & EP_ExpCollate ){
59391    pDup->pColl = pExpr->pColl;
59392    pDup->flags |= EP_ExpCollate;
59393  }
59394
59395  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
59396  ** prevents ExprDelete() from deleting the Expr structure itself,
59397  ** allowing it to be repopulated by the memcpy() on the following line.
59398  */
59399  ExprSetProperty(pExpr, EP_Static);
59400  sqlite3ExprDelete(db, pExpr);
59401  memcpy(pExpr, pDup, sizeof(*pExpr));
59402  sqlite3DbFree(db, pDup);
59403}
59404
59405/*
59406** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
59407** that name in the set of source tables in pSrcList and make the pExpr
59408** expression node refer back to that source column.  The following changes
59409** are made to pExpr:
59410**
59411**    pExpr->iDb           Set the index in db->aDb[] of the database X
59412**                         (even if X is implied).
59413**    pExpr->iTable        Set to the cursor number for the table obtained
59414**                         from pSrcList.
59415**    pExpr->pTab          Points to the Table structure of X.Y (even if
59416**                         X and/or Y are implied.)
59417**    pExpr->iColumn       Set to the column number within the table.
59418**    pExpr->op            Set to TK_COLUMN.
59419**    pExpr->pLeft         Any expression this points to is deleted
59420**    pExpr->pRight        Any expression this points to is deleted.
59421**
59422** The zDb variable is the name of the database (the "X").  This value may be
59423** NULL meaning that name is of the form Y.Z or Z.  Any available database
59424** can be used.  The zTable variable is the name of the table (the "Y").  This
59425** value can be NULL if zDb is also NULL.  If zTable is NULL it
59426** means that the form of the name is Z and that columns from any table
59427** can be used.
59428**
59429** If the name cannot be resolved unambiguously, leave an error message
59430** in pParse and return WRC_Abort.  Return WRC_Prune on success.
59431*/
59432static int lookupName(
59433  Parse *pParse,       /* The parsing context */
59434  const char *zDb,     /* Name of the database containing table, or NULL */
59435  const char *zTab,    /* Name of table containing column, or NULL */
59436  const char *zCol,    /* Name of the column. */
59437  NameContext *pNC,    /* The name context used to resolve the name */
59438  Expr *pExpr          /* Make this EXPR node point to the selected column */
59439){
59440  int i, j;            /* Loop counters */
59441  int cnt = 0;                      /* Number of matching column names */
59442  int cntTab = 0;                   /* Number of matching table names */
59443  sqlite3 *db = pParse->db;         /* The database connection */
59444  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
59445  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
59446  NameContext *pTopNC = pNC;        /* First namecontext in the list */
59447  Schema *pSchema = 0;              /* Schema of the expression */
59448  int isTrigger = 0;
59449
59450  assert( pNC );     /* the name context cannot be NULL. */
59451  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
59452  assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
59453
59454  /* Initialize the node to no-match */
59455  pExpr->iTable = -1;
59456  pExpr->pTab = 0;
59457  ExprSetIrreducible(pExpr);
59458
59459  /* Start at the inner-most context and move outward until a match is found */
59460  while( pNC && cnt==0 ){
59461    ExprList *pEList;
59462    SrcList *pSrcList = pNC->pSrcList;
59463
59464    if( pSrcList ){
59465      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
59466        Table *pTab;
59467        int iDb;
59468        Column *pCol;
59469
59470        pTab = pItem->pTab;
59471        assert( pTab!=0 && pTab->zName!=0 );
59472        iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
59473        assert( pTab->nCol>0 );
59474        if( zTab ){
59475          if( pItem->zAlias ){
59476            char *zTabName = pItem->zAlias;
59477            if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
59478          }else{
59479            char *zTabName = pTab->zName;
59480            if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
59481              continue;
59482            }
59483            if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
59484              continue;
59485            }
59486          }
59487        }
59488        if( 0==(cntTab++) ){
59489          pExpr->iTable = pItem->iCursor;
59490          pExpr->pTab = pTab;
59491          pSchema = pTab->pSchema;
59492          pMatch = pItem;
59493        }
59494        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
59495          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
59496            IdList *pUsing;
59497            cnt++;
59498            pExpr->iTable = pItem->iCursor;
59499            pExpr->pTab = pTab;
59500            pMatch = pItem;
59501            pSchema = pTab->pSchema;
59502            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
59503            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
59504            if( i<pSrcList->nSrc-1 ){
59505              if( pItem[1].jointype & JT_NATURAL ){
59506                /* If this match occurred in the left table of a natural join,
59507                ** then skip the right table to avoid a duplicate match */
59508                pItem++;
59509                i++;
59510              }else if( (pUsing = pItem[1].pUsing)!=0 ){
59511                /* If this match occurs on a column that is in the USING clause
59512                ** of a join, skip the search of the right table of the join
59513                ** to avoid a duplicate match there. */
59514                int k;
59515                for(k=0; k<pUsing->nId; k++){
59516                  if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
59517                    pItem++;
59518                    i++;
59519                    break;
59520                  }
59521                }
59522              }
59523            }
59524            break;
59525          }
59526        }
59527      }
59528    }
59529
59530#ifndef SQLITE_OMIT_TRIGGER
59531    /* If we have not already resolved the name, then maybe
59532    ** it is a new.* or old.* trigger argument reference
59533    */
59534    if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
59535      int op = pParse->eTriggerOp;
59536      Table *pTab = 0;
59537      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
59538      if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
59539        pExpr->iTable = 1;
59540        pTab = pParse->pTriggerTab;
59541      }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
59542        pExpr->iTable = 0;
59543        pTab = pParse->pTriggerTab;
59544      }
59545
59546      if( pTab ){
59547        int iCol;
59548        pSchema = pTab->pSchema;
59549        cntTab++;
59550        for(iCol=0; iCol<pTab->nCol; iCol++){
59551          Column *pCol = &pTab->aCol[iCol];
59552          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
59553            if( iCol==pTab->iPKey ){
59554              iCol = -1;
59555            }
59556            break;
59557          }
59558        }
59559        if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
59560          iCol = -1;        /* IMP: R-44911-55124 */
59561        }
59562        if( iCol<pTab->nCol ){
59563          cnt++;
59564          if( iCol<0 ){
59565            pExpr->affinity = SQLITE_AFF_INTEGER;
59566          }else if( pExpr->iTable==0 ){
59567            testcase( iCol==31 );
59568            testcase( iCol==32 );
59569            pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
59570          }else{
59571            testcase( iCol==31 );
59572            testcase( iCol==32 );
59573            pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
59574          }
59575          pExpr->iColumn = (i16)iCol;
59576          pExpr->pTab = pTab;
59577          isTrigger = 1;
59578        }
59579      }
59580    }
59581#endif /* !defined(SQLITE_OMIT_TRIGGER) */
59582
59583    /*
59584    ** Perhaps the name is a reference to the ROWID
59585    */
59586    if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
59587      cnt = 1;
59588      pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
59589      pExpr->affinity = SQLITE_AFF_INTEGER;
59590    }
59591
59592    /*
59593    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
59594    ** might refer to an result-set alias.  This happens, for example, when
59595    ** we are resolving names in the WHERE clause of the following command:
59596    **
59597    **     SELECT a+b AS x FROM table WHERE x<10;
59598    **
59599    ** In cases like this, replace pExpr with a copy of the expression that
59600    ** forms the result set entry ("a+b" in the example) and return immediately.
59601    ** Note that the expression in the result set should have already been
59602    ** resolved by the time the WHERE clause is resolved.
59603    */
59604    if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
59605      for(j=0; j<pEList->nExpr; j++){
59606        char *zAs = pEList->a[j].zName;
59607        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
59608          Expr *pOrig;
59609          assert( pExpr->pLeft==0 && pExpr->pRight==0 );
59610          assert( pExpr->x.pList==0 );
59611          assert( pExpr->x.pSelect==0 );
59612          pOrig = pEList->a[j].pExpr;
59613          if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
59614            sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
59615            return WRC_Abort;
59616          }
59617          resolveAlias(pParse, pEList, j, pExpr, "");
59618          cnt = 1;
59619          pMatch = 0;
59620          assert( zTab==0 && zDb==0 );
59621          goto lookupname_end;
59622        }
59623      }
59624    }
59625
59626    /* Advance to the next name context.  The loop will exit when either
59627    ** we have a match (cnt>0) or when we run out of name contexts.
59628    */
59629    if( cnt==0 ){
59630      pNC = pNC->pNext;
59631    }
59632  }
59633
59634  /*
59635  ** If X and Y are NULL (in other words if only the column name Z is
59636  ** supplied) and the value of Z is enclosed in double-quotes, then
59637  ** Z is a string literal if it doesn't match any column names.  In that
59638  ** case, we need to return right away and not make any changes to
59639  ** pExpr.
59640  **
59641  ** Because no reference was made to outer contexts, the pNC->nRef
59642  ** fields are not changed in any context.
59643  */
59644  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
59645    pExpr->op = TK_STRING;
59646    pExpr->pTab = 0;
59647    return WRC_Prune;
59648  }
59649
59650  /*
59651  ** cnt==0 means there was not match.  cnt>1 means there were two or
59652  ** more matches.  Either way, we have an error.
59653  */
59654  if( cnt!=1 ){
59655    const char *zErr;
59656    zErr = cnt==0 ? "no such column" : "ambiguous column name";
59657    if( zDb ){
59658      sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
59659    }else if( zTab ){
59660      sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
59661    }else{
59662      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
59663    }
59664    pTopNC->nErr++;
59665  }
59666
59667  /* If a column from a table in pSrcList is referenced, then record
59668  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
59669  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
59670  ** column number is greater than the number of bits in the bitmask
59671  ** then set the high-order bit of the bitmask.
59672  */
59673  if( pExpr->iColumn>=0 && pMatch!=0 ){
59674    int n = pExpr->iColumn;
59675    testcase( n==BMS-1 );
59676    if( n>=BMS ){
59677      n = BMS-1;
59678    }
59679    assert( pMatch->iCursor==pExpr->iTable );
59680    pMatch->colUsed |= ((Bitmask)1)<<n;
59681  }
59682
59683  /* Clean up and return
59684  */
59685  sqlite3ExprDelete(db, pExpr->pLeft);
59686  pExpr->pLeft = 0;
59687  sqlite3ExprDelete(db, pExpr->pRight);
59688  pExpr->pRight = 0;
59689  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
59690lookupname_end:
59691  if( cnt==1 ){
59692    assert( pNC!=0 );
59693    sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
59694    /* Increment the nRef value on all name contexts from TopNC up to
59695    ** the point where the name matched. */
59696    for(;;){
59697      assert( pTopNC!=0 );
59698      pTopNC->nRef++;
59699      if( pTopNC==pNC ) break;
59700      pTopNC = pTopNC->pNext;
59701    }
59702    return WRC_Prune;
59703  } else {
59704    return WRC_Abort;
59705  }
59706}
59707
59708/*
59709** Allocate and return a pointer to an expression to load the column iCol
59710** from datasource iSrc datasource in SrcList pSrc.
59711*/
59712SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
59713  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
59714  if( p ){
59715    struct SrcList_item *pItem = &pSrc->a[iSrc];
59716    p->pTab = pItem->pTab;
59717    p->iTable = pItem->iCursor;
59718    if( p->pTab->iPKey==iCol ){
59719      p->iColumn = -1;
59720    }else{
59721      p->iColumn = (ynVar)iCol;
59722      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
59723    }
59724    ExprSetProperty(p, EP_Resolved);
59725  }
59726  return p;
59727}
59728
59729/*
59730** This routine is callback for sqlite3WalkExpr().
59731**
59732** Resolve symbolic names into TK_COLUMN operators for the current
59733** node in the expression tree.  Return 0 to continue the search down
59734** the tree or 2 to abort the tree walk.
59735**
59736** This routine also does error checking and name resolution for
59737** function names.  The operator for aggregate functions is changed
59738** to TK_AGG_FUNCTION.
59739*/
59740static int resolveExprStep(Walker *pWalker, Expr *pExpr){
59741  NameContext *pNC;
59742  Parse *pParse;
59743
59744  pNC = pWalker->u.pNC;
59745  assert( pNC!=0 );
59746  pParse = pNC->pParse;
59747  assert( pParse==pWalker->pParse );
59748
59749  if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
59750  ExprSetProperty(pExpr, EP_Resolved);
59751#ifndef NDEBUG
59752  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
59753    SrcList *pSrcList = pNC->pSrcList;
59754    int i;
59755    for(i=0; i<pNC->pSrcList->nSrc; i++){
59756      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
59757    }
59758  }
59759#endif
59760  switch( pExpr->op ){
59761
59762#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
59763    /* The special operator TK_ROW means use the rowid for the first
59764    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
59765    ** clause processing on UPDATE and DELETE statements.
59766    */
59767    case TK_ROW: {
59768      SrcList *pSrcList = pNC->pSrcList;
59769      struct SrcList_item *pItem;
59770      assert( pSrcList && pSrcList->nSrc==1 );
59771      pItem = pSrcList->a;
59772      pExpr->op = TK_COLUMN;
59773      pExpr->pTab = pItem->pTab;
59774      pExpr->iTable = pItem->iCursor;
59775      pExpr->iColumn = -1;
59776      pExpr->affinity = SQLITE_AFF_INTEGER;
59777      break;
59778    }
59779#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
59780
59781    /* A lone identifier is the name of a column.
59782    */
59783    case TK_ID: {
59784      return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
59785    }
59786
59787    /* A table name and column name:     ID.ID
59788    ** Or a database, table and column:  ID.ID.ID
59789    */
59790    case TK_DOT: {
59791      const char *zColumn;
59792      const char *zTable;
59793      const char *zDb;
59794      Expr *pRight;
59795
59796      /* if( pSrcList==0 ) break; */
59797      pRight = pExpr->pRight;
59798      if( pRight->op==TK_ID ){
59799        zDb = 0;
59800        zTable = pExpr->pLeft->u.zToken;
59801        zColumn = pRight->u.zToken;
59802      }else{
59803        assert( pRight->op==TK_DOT );
59804        zDb = pExpr->pLeft->u.zToken;
59805        zTable = pRight->pLeft->u.zToken;
59806        zColumn = pRight->pRight->u.zToken;
59807      }
59808      return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
59809    }
59810
59811    /* Resolve function names
59812    */
59813    case TK_CONST_FUNC:
59814    case TK_FUNCTION: {
59815      ExprList *pList = pExpr->x.pList;    /* The argument list */
59816      int n = pList ? pList->nExpr : 0;    /* Number of arguments */
59817      int no_such_func = 0;       /* True if no such function exists */
59818      int wrong_num_args = 0;     /* True if wrong number of arguments */
59819      int is_agg = 0;             /* True if is an aggregate function */
59820      int auth;                   /* Authorization to use the function */
59821      int nId;                    /* Number of characters in function name */
59822      const char *zId;            /* The function name. */
59823      FuncDef *pDef;              /* Information about the function */
59824      u8 enc = ENC(pParse->db);   /* The database encoding */
59825
59826      testcase( pExpr->op==TK_CONST_FUNC );
59827      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
59828      zId = pExpr->u.zToken;
59829      nId = sqlite3Strlen30(zId);
59830      pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
59831      if( pDef==0 ){
59832        pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
59833        if( pDef==0 ){
59834          no_such_func = 1;
59835        }else{
59836          wrong_num_args = 1;
59837        }
59838      }else{
59839        is_agg = pDef->xFunc==0;
59840      }
59841#ifndef SQLITE_OMIT_AUTHORIZATION
59842      if( pDef ){
59843        auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
59844        if( auth!=SQLITE_OK ){
59845          if( auth==SQLITE_DENY ){
59846            sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
59847                                    pDef->zName);
59848            pNC->nErr++;
59849          }
59850          pExpr->op = TK_NULL;
59851          return WRC_Prune;
59852        }
59853      }
59854#endif
59855      if( is_agg && !pNC->allowAgg ){
59856        sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
59857        pNC->nErr++;
59858        is_agg = 0;
59859      }else if( no_such_func ){
59860        sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
59861        pNC->nErr++;
59862      }else if( wrong_num_args ){
59863        sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
59864             nId, zId);
59865        pNC->nErr++;
59866      }
59867      if( is_agg ){
59868        pExpr->op = TK_AGG_FUNCTION;
59869        pNC->hasAgg = 1;
59870      }
59871      if( is_agg ) pNC->allowAgg = 0;
59872      sqlite3WalkExprList(pWalker, pList);
59873      if( is_agg ) pNC->allowAgg = 1;
59874      /* FIX ME:  Compute pExpr->affinity based on the expected return
59875      ** type of the function
59876      */
59877      return WRC_Prune;
59878    }
59879#ifndef SQLITE_OMIT_SUBQUERY
59880    case TK_SELECT:
59881    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
59882#endif
59883    case TK_IN: {
59884      testcase( pExpr->op==TK_IN );
59885      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
59886        int nRef = pNC->nRef;
59887#ifndef SQLITE_OMIT_CHECK
59888        if( pNC->isCheck ){
59889          sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
59890        }
59891#endif
59892        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
59893        assert( pNC->nRef>=nRef );
59894        if( nRef!=pNC->nRef ){
59895          ExprSetProperty(pExpr, EP_VarSelect);
59896        }
59897      }
59898      break;
59899    }
59900#ifndef SQLITE_OMIT_CHECK
59901    case TK_VARIABLE: {
59902      if( pNC->isCheck ){
59903        sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
59904      }
59905      break;
59906    }
59907#endif
59908  }
59909  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
59910}
59911
59912/*
59913** pEList is a list of expressions which are really the result set of the
59914** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
59915** This routine checks to see if pE is a simple identifier which corresponds
59916** to the AS-name of one of the terms of the expression list.  If it is,
59917** this routine return an integer between 1 and N where N is the number of
59918** elements in pEList, corresponding to the matching entry.  If there is
59919** no match, or if pE is not a simple identifier, then this routine
59920** return 0.
59921**
59922** pEList has been resolved.  pE has not.
59923*/
59924static int resolveAsName(
59925  Parse *pParse,     /* Parsing context for error messages */
59926  ExprList *pEList,  /* List of expressions to scan */
59927  Expr *pE           /* Expression we are trying to match */
59928){
59929  int i;             /* Loop counter */
59930
59931  UNUSED_PARAMETER(pParse);
59932
59933  if( pE->op==TK_ID ){
59934    char *zCol = pE->u.zToken;
59935    for(i=0; i<pEList->nExpr; i++){
59936      char *zAs = pEList->a[i].zName;
59937      if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
59938        return i+1;
59939      }
59940    }
59941  }
59942  return 0;
59943}
59944
59945/*
59946** pE is a pointer to an expression which is a single term in the
59947** ORDER BY of a compound SELECT.  The expression has not been
59948** name resolved.
59949**
59950** At the point this routine is called, we already know that the
59951** ORDER BY term is not an integer index into the result set.  That
59952** case is handled by the calling routine.
59953**
59954** Attempt to match pE against result set columns in the left-most
59955** SELECT statement.  Return the index i of the matching column,
59956** as an indication to the caller that it should sort by the i-th column.
59957** The left-most column is 1.  In other words, the value returned is the
59958** same integer value that would be used in the SQL statement to indicate
59959** the column.
59960**
59961** If there is no match, return 0.  Return -1 if an error occurs.
59962*/
59963static int resolveOrderByTermToExprList(
59964  Parse *pParse,     /* Parsing context for error messages */
59965  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
59966  Expr *pE           /* The specific ORDER BY term */
59967){
59968  int i;             /* Loop counter */
59969  ExprList *pEList;  /* The columns of the result set */
59970  NameContext nc;    /* Name context for resolving pE */
59971  sqlite3 *db;       /* Database connection */
59972  int rc;            /* Return code from subprocedures */
59973  u8 savedSuppErr;   /* Saved value of db->suppressErr */
59974
59975  assert( sqlite3ExprIsInteger(pE, &i)==0 );
59976  pEList = pSelect->pEList;
59977
59978  /* Resolve all names in the ORDER BY term expression
59979  */
59980  memset(&nc, 0, sizeof(nc));
59981  nc.pParse = pParse;
59982  nc.pSrcList = pSelect->pSrc;
59983  nc.pEList = pEList;
59984  nc.allowAgg = 1;
59985  nc.nErr = 0;
59986  db = pParse->db;
59987  savedSuppErr = db->suppressErr;
59988  db->suppressErr = 1;
59989  rc = sqlite3ResolveExprNames(&nc, pE);
59990  db->suppressErr = savedSuppErr;
59991  if( rc ) return 0;
59992
59993  /* Try to match the ORDER BY expression against an expression
59994  ** in the result set.  Return an 1-based index of the matching
59995  ** result-set entry.
59996  */
59997  for(i=0; i<pEList->nExpr; i++){
59998    if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
59999      return i+1;
60000    }
60001  }
60002
60003  /* If no match, return 0. */
60004  return 0;
60005}
60006
60007/*
60008** Generate an ORDER BY or GROUP BY term out-of-range error.
60009*/
60010static void resolveOutOfRangeError(
60011  Parse *pParse,         /* The error context into which to write the error */
60012  const char *zType,     /* "ORDER" or "GROUP" */
60013  int i,                 /* The index (1-based) of the term out of range */
60014  int mx                 /* Largest permissible value of i */
60015){
60016  sqlite3ErrorMsg(pParse,
60017    "%r %s BY term out of range - should be "
60018    "between 1 and %d", i, zType, mx);
60019}
60020
60021/*
60022** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
60023** each term of the ORDER BY clause is a constant integer between 1
60024** and N where N is the number of columns in the compound SELECT.
60025**
60026** ORDER BY terms that are already an integer between 1 and N are
60027** unmodified.  ORDER BY terms that are integers outside the range of
60028** 1 through N generate an error.  ORDER BY terms that are expressions
60029** are matched against result set expressions of compound SELECT
60030** beginning with the left-most SELECT and working toward the right.
60031** At the first match, the ORDER BY expression is transformed into
60032** the integer column number.
60033**
60034** Return the number of errors seen.
60035*/
60036static int resolveCompoundOrderBy(
60037  Parse *pParse,        /* Parsing context.  Leave error messages here */
60038  Select *pSelect       /* The SELECT statement containing the ORDER BY */
60039){
60040  int i;
60041  ExprList *pOrderBy;
60042  ExprList *pEList;
60043  sqlite3 *db;
60044  int moreToDo = 1;
60045
60046  pOrderBy = pSelect->pOrderBy;
60047  if( pOrderBy==0 ) return 0;
60048  db = pParse->db;
60049#if SQLITE_MAX_COLUMN
60050  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
60051    sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
60052    return 1;
60053  }
60054#endif
60055  for(i=0; i<pOrderBy->nExpr; i++){
60056    pOrderBy->a[i].done = 0;
60057  }
60058  pSelect->pNext = 0;
60059  while( pSelect->pPrior ){
60060    pSelect->pPrior->pNext = pSelect;
60061    pSelect = pSelect->pPrior;
60062  }
60063  while( pSelect && moreToDo ){
60064    struct ExprList_item *pItem;
60065    moreToDo = 0;
60066    pEList = pSelect->pEList;
60067    assert( pEList!=0 );
60068    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
60069      int iCol = -1;
60070      Expr *pE, *pDup;
60071      if( pItem->done ) continue;
60072      pE = pItem->pExpr;
60073      if( sqlite3ExprIsInteger(pE, &iCol) ){
60074        if( iCol<=0 || iCol>pEList->nExpr ){
60075          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
60076          return 1;
60077        }
60078      }else{
60079        iCol = resolveAsName(pParse, pEList, pE);
60080        if( iCol==0 ){
60081          pDup = sqlite3ExprDup(db, pE, 0);
60082          if( !db->mallocFailed ){
60083            assert(pDup);
60084            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
60085          }
60086          sqlite3ExprDelete(db, pDup);
60087        }
60088      }
60089      if( iCol>0 ){
60090        CollSeq *pColl = pE->pColl;
60091        int flags = pE->flags & EP_ExpCollate;
60092        sqlite3ExprDelete(db, pE);
60093        pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
60094        if( pE==0 ) return 1;
60095        pE->pColl = pColl;
60096        pE->flags |= EP_IntValue | flags;
60097        pE->u.iValue = iCol;
60098        pItem->iCol = (u16)iCol;
60099        pItem->done = 1;
60100      }else{
60101        moreToDo = 1;
60102      }
60103    }
60104    pSelect = pSelect->pNext;
60105  }
60106  for(i=0; i<pOrderBy->nExpr; i++){
60107    if( pOrderBy->a[i].done==0 ){
60108      sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
60109            "column in the result set", i+1);
60110      return 1;
60111    }
60112  }
60113  return 0;
60114}
60115
60116/*
60117** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
60118** the SELECT statement pSelect.  If any term is reference to a
60119** result set expression (as determined by the ExprList.a.iCol field)
60120** then convert that term into a copy of the corresponding result set
60121** column.
60122**
60123** If any errors are detected, add an error message to pParse and
60124** return non-zero.  Return zero if no errors are seen.
60125*/
60126SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
60127  Parse *pParse,        /* Parsing context.  Leave error messages here */
60128  Select *pSelect,      /* The SELECT statement containing the clause */
60129  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
60130  const char *zType     /* "ORDER" or "GROUP" */
60131){
60132  int i;
60133  sqlite3 *db = pParse->db;
60134  ExprList *pEList;
60135  struct ExprList_item *pItem;
60136
60137  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
60138#if SQLITE_MAX_COLUMN
60139  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
60140    sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
60141    return 1;
60142  }
60143#endif
60144  pEList = pSelect->pEList;
60145  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
60146  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
60147    if( pItem->iCol ){
60148      if( pItem->iCol>pEList->nExpr ){
60149        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
60150        return 1;
60151      }
60152      resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
60153    }
60154  }
60155  return 0;
60156}
60157
60158/*
60159** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
60160** The Name context of the SELECT statement is pNC.  zType is either
60161** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
60162**
60163** This routine resolves each term of the clause into an expression.
60164** If the order-by term is an integer I between 1 and N (where N is the
60165** number of columns in the result set of the SELECT) then the expression
60166** in the resolution is a copy of the I-th result-set expression.  If
60167** the order-by term is an identify that corresponds to the AS-name of
60168** a result-set expression, then the term resolves to a copy of the
60169** result-set expression.  Otherwise, the expression is resolved in
60170** the usual way - using sqlite3ResolveExprNames().
60171**
60172** This routine returns the number of errors.  If errors occur, then
60173** an appropriate error message might be left in pParse.  (OOM errors
60174** excepted.)
60175*/
60176static int resolveOrderGroupBy(
60177  NameContext *pNC,     /* The name context of the SELECT statement */
60178  Select *pSelect,      /* The SELECT statement holding pOrderBy */
60179  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
60180  const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
60181){
60182  int i;                         /* Loop counter */
60183  int iCol;                      /* Column number */
60184  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
60185  Parse *pParse;                 /* Parsing context */
60186  int nResult;                   /* Number of terms in the result set */
60187
60188  if( pOrderBy==0 ) return 0;
60189  nResult = pSelect->pEList->nExpr;
60190  pParse = pNC->pParse;
60191  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
60192    Expr *pE = pItem->pExpr;
60193    iCol = resolveAsName(pParse, pSelect->pEList, pE);
60194    if( iCol>0 ){
60195      /* If an AS-name match is found, mark this ORDER BY column as being
60196      ** a copy of the iCol-th result-set column.  The subsequent call to
60197      ** sqlite3ResolveOrderGroupBy() will convert the expression to a
60198      ** copy of the iCol-th result-set expression. */
60199      pItem->iCol = (u16)iCol;
60200      continue;
60201    }
60202    if( sqlite3ExprIsInteger(pE, &iCol) ){
60203      /* The ORDER BY term is an integer constant.  Again, set the column
60204      ** number so that sqlite3ResolveOrderGroupBy() will convert the
60205      ** order-by term to a copy of the result-set expression */
60206      if( iCol<1 ){
60207        resolveOutOfRangeError(pParse, zType, i+1, nResult);
60208        return 1;
60209      }
60210      pItem->iCol = (u16)iCol;
60211      continue;
60212    }
60213
60214    /* Otherwise, treat the ORDER BY term as an ordinary expression */
60215    pItem->iCol = 0;
60216    if( sqlite3ResolveExprNames(pNC, pE) ){
60217      return 1;
60218    }
60219  }
60220  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
60221}
60222
60223/*
60224** Resolve names in the SELECT statement p and all of its descendents.
60225*/
60226static int resolveSelectStep(Walker *pWalker, Select *p){
60227  NameContext *pOuterNC;  /* Context that contains this SELECT */
60228  NameContext sNC;        /* Name context of this SELECT */
60229  int isCompound;         /* True if p is a compound select */
60230  int nCompound;          /* Number of compound terms processed so far */
60231  Parse *pParse;          /* Parsing context */
60232  ExprList *pEList;       /* Result set expression list */
60233  int i;                  /* Loop counter */
60234  ExprList *pGroupBy;     /* The GROUP BY clause */
60235  Select *pLeftmost;      /* Left-most of SELECT of a compound */
60236  sqlite3 *db;            /* Database connection */
60237
60238
60239  assert( p!=0 );
60240  if( p->selFlags & SF_Resolved ){
60241    return WRC_Prune;
60242  }
60243  pOuterNC = pWalker->u.pNC;
60244  pParse = pWalker->pParse;
60245  db = pParse->db;
60246
60247  /* Normally sqlite3SelectExpand() will be called first and will have
60248  ** already expanded this SELECT.  However, if this is a subquery within
60249  ** an expression, sqlite3ResolveExprNames() will be called without a
60250  ** prior call to sqlite3SelectExpand().  When that happens, let
60251  ** sqlite3SelectPrep() do all of the processing for this SELECT.
60252  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
60253  ** this routine in the correct order.
60254  */
60255  if( (p->selFlags & SF_Expanded)==0 ){
60256    sqlite3SelectPrep(pParse, p, pOuterNC);
60257    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
60258  }
60259
60260  isCompound = p->pPrior!=0;
60261  nCompound = 0;
60262  pLeftmost = p;
60263  while( p ){
60264    assert( (p->selFlags & SF_Expanded)!=0 );
60265    assert( (p->selFlags & SF_Resolved)==0 );
60266    p->selFlags |= SF_Resolved;
60267
60268    /* Resolve the expressions in the LIMIT and OFFSET clauses. These
60269    ** are not allowed to refer to any names, so pass an empty NameContext.
60270    */
60271    memset(&sNC, 0, sizeof(sNC));
60272    sNC.pParse = pParse;
60273    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
60274        sqlite3ResolveExprNames(&sNC, p->pOffset) ){
60275      return WRC_Abort;
60276    }
60277
60278    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
60279    ** resolve the result-set expression list.
60280    */
60281    sNC.allowAgg = 1;
60282    sNC.pSrcList = p->pSrc;
60283    sNC.pNext = pOuterNC;
60284
60285    /* Resolve names in the result set. */
60286    pEList = p->pEList;
60287    assert( pEList!=0 );
60288    for(i=0; i<pEList->nExpr; i++){
60289      Expr *pX = pEList->a[i].pExpr;
60290      if( sqlite3ResolveExprNames(&sNC, pX) ){
60291        return WRC_Abort;
60292      }
60293    }
60294
60295    /* Recursively resolve names in all subqueries
60296    */
60297    for(i=0; i<p->pSrc->nSrc; i++){
60298      struct SrcList_item *pItem = &p->pSrc->a[i];
60299      if( pItem->pSelect ){
60300        const char *zSavedContext = pParse->zAuthContext;
60301        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
60302        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
60303        pParse->zAuthContext = zSavedContext;
60304        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
60305      }
60306    }
60307
60308    /* If there are no aggregate functions in the result-set, and no GROUP BY
60309    ** expression, do not allow aggregates in any of the other expressions.
60310    */
60311    assert( (p->selFlags & SF_Aggregate)==0 );
60312    pGroupBy = p->pGroupBy;
60313    if( pGroupBy || sNC.hasAgg ){
60314      p->selFlags |= SF_Aggregate;
60315    }else{
60316      sNC.allowAgg = 0;
60317    }
60318
60319    /* If a HAVING clause is present, then there must be a GROUP BY clause.
60320    */
60321    if( p->pHaving && !pGroupBy ){
60322      sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
60323      return WRC_Abort;
60324    }
60325
60326    /* Add the expression list to the name-context before parsing the
60327    ** other expressions in the SELECT statement. This is so that
60328    ** expressions in the WHERE clause (etc.) can refer to expressions by
60329    ** aliases in the result set.
60330    **
60331    ** Minor point: If this is the case, then the expression will be
60332    ** re-evaluated for each reference to it.
60333    */
60334    sNC.pEList = p->pEList;
60335    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
60336       sqlite3ResolveExprNames(&sNC, p->pHaving)
60337    ){
60338      return WRC_Abort;
60339    }
60340
60341    /* The ORDER BY and GROUP BY clauses may not refer to terms in
60342    ** outer queries
60343    */
60344    sNC.pNext = 0;
60345    sNC.allowAgg = 1;
60346
60347    /* Process the ORDER BY clause for singleton SELECT statements.
60348    ** The ORDER BY clause for compounds SELECT statements is handled
60349    ** below, after all of the result-sets for all of the elements of
60350    ** the compound have been resolved.
60351    */
60352    if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
60353      return WRC_Abort;
60354    }
60355    if( db->mallocFailed ){
60356      return WRC_Abort;
60357    }
60358
60359    /* Resolve the GROUP BY clause.  At the same time, make sure
60360    ** the GROUP BY clause does not contain aggregate functions.
60361    */
60362    if( pGroupBy ){
60363      struct ExprList_item *pItem;
60364
60365      if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
60366        return WRC_Abort;
60367      }
60368      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
60369        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
60370          sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
60371              "the GROUP BY clause");
60372          return WRC_Abort;
60373        }
60374      }
60375    }
60376
60377    /* Advance to the next term of the compound
60378    */
60379    p = p->pPrior;
60380    nCompound++;
60381  }
60382
60383  /* Resolve the ORDER BY on a compound SELECT after all terms of
60384  ** the compound have been resolved.
60385  */
60386  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
60387    return WRC_Abort;
60388  }
60389
60390  return WRC_Prune;
60391}
60392
60393/*
60394** This routine walks an expression tree and resolves references to
60395** table columns and result-set columns.  At the same time, do error
60396** checking on function usage and set a flag if any aggregate functions
60397** are seen.
60398**
60399** To resolve table columns references we look for nodes (or subtrees) of the
60400** form X.Y.Z or Y.Z or just Z where
60401**
60402**      X:   The name of a database.  Ex:  "main" or "temp" or
60403**           the symbolic name assigned to an ATTACH-ed database.
60404**
60405**      Y:   The name of a table in a FROM clause.  Or in a trigger
60406**           one of the special names "old" or "new".
60407**
60408**      Z:   The name of a column in table Y.
60409**
60410** The node at the root of the subtree is modified as follows:
60411**
60412**    Expr.op        Changed to TK_COLUMN
60413**    Expr.pTab      Points to the Table object for X.Y
60414**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
60415**    Expr.iTable    The VDBE cursor number for X.Y
60416**
60417**
60418** To resolve result-set references, look for expression nodes of the
60419** form Z (with no X and Y prefix) where the Z matches the right-hand
60420** size of an AS clause in the result-set of a SELECT.  The Z expression
60421** is replaced by a copy of the left-hand side of the result-set expression.
60422** Table-name and function resolution occurs on the substituted expression
60423** tree.  For example, in:
60424**
60425**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
60426**
60427** The "x" term of the order by is replaced by "a+b" to render:
60428**
60429**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
60430**
60431** Function calls are checked to make sure that the function is
60432** defined and that the correct number of arguments are specified.
60433** If the function is an aggregate function, then the pNC->hasAgg is
60434** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
60435** If an expression contains aggregate functions then the EP_Agg
60436** property on the expression is set.
60437**
60438** An error message is left in pParse if anything is amiss.  The number
60439** if errors is returned.
60440*/
60441SQLITE_PRIVATE int sqlite3ResolveExprNames(
60442  NameContext *pNC,       /* Namespace to resolve expressions in. */
60443  Expr *pExpr             /* The expression to be analyzed. */
60444){
60445  int savedHasAgg;
60446  Walker w;
60447
60448  if( pExpr==0 ) return 0;
60449#if SQLITE_MAX_EXPR_DEPTH>0
60450  {
60451    Parse *pParse = pNC->pParse;
60452    if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
60453      return 1;
60454    }
60455    pParse->nHeight += pExpr->nHeight;
60456  }
60457#endif
60458  savedHasAgg = pNC->hasAgg;
60459  pNC->hasAgg = 0;
60460  w.xExprCallback = resolveExprStep;
60461  w.xSelectCallback = resolveSelectStep;
60462  w.pParse = pNC->pParse;
60463  w.u.pNC = pNC;
60464  sqlite3WalkExpr(&w, pExpr);
60465#if SQLITE_MAX_EXPR_DEPTH>0
60466  pNC->pParse->nHeight -= pExpr->nHeight;
60467#endif
60468  if( pNC->nErr>0 || w.pParse->nErr>0 ){
60469    ExprSetProperty(pExpr, EP_Error);
60470  }
60471  if( pNC->hasAgg ){
60472    ExprSetProperty(pExpr, EP_Agg);
60473  }else if( savedHasAgg ){
60474    pNC->hasAgg = 1;
60475  }
60476  return ExprHasProperty(pExpr, EP_Error);
60477}
60478
60479
60480/*
60481** Resolve all names in all expressions of a SELECT and in all
60482** decendents of the SELECT, including compounds off of p->pPrior,
60483** subqueries in expressions, and subqueries used as FROM clause
60484** terms.
60485**
60486** See sqlite3ResolveExprNames() for a description of the kinds of
60487** transformations that occur.
60488**
60489** All SELECT statements should have been expanded using
60490** sqlite3SelectExpand() prior to invoking this routine.
60491*/
60492SQLITE_PRIVATE void sqlite3ResolveSelectNames(
60493  Parse *pParse,         /* The parser context */
60494  Select *p,             /* The SELECT statement being coded. */
60495  NameContext *pOuterNC  /* Name context for parent SELECT statement */
60496){
60497  Walker w;
60498
60499  assert( p!=0 );
60500  w.xExprCallback = resolveExprStep;
60501  w.xSelectCallback = resolveSelectStep;
60502  w.pParse = pParse;
60503  w.u.pNC = pOuterNC;
60504  sqlite3WalkSelect(&w, p);
60505}
60506
60507/************** End of resolve.c *********************************************/
60508/************** Begin file expr.c ********************************************/
60509/*
60510** 2001 September 15
60511**
60512** The author disclaims copyright to this source code.  In place of
60513** a legal notice, here is a blessing:
60514**
60515**    May you do good and not evil.
60516**    May you find forgiveness for yourself and forgive others.
60517**    May you share freely, never taking more than you give.
60518**
60519*************************************************************************
60520** This file contains routines used for analyzing expressions and
60521** for generating VDBE code that evaluates expressions in SQLite.
60522*/
60523
60524/*
60525** Return the 'affinity' of the expression pExpr if any.
60526**
60527** If pExpr is a column, a reference to a column via an 'AS' alias,
60528** or a sub-select with a column as the return value, then the
60529** affinity of that column is returned. Otherwise, 0x00 is returned,
60530** indicating no affinity for the expression.
60531**
60532** i.e. the WHERE clause expresssions in the following statements all
60533** have an affinity:
60534**
60535** CREATE TABLE t1(a);
60536** SELECT * FROM t1 WHERE a;
60537** SELECT a AS b FROM t1 WHERE b;
60538** SELECT * FROM t1 WHERE (select a from t1);
60539*/
60540SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
60541  int op = pExpr->op;
60542  if( op==TK_SELECT ){
60543    assert( pExpr->flags&EP_xIsSelect );
60544    return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
60545  }
60546#ifndef SQLITE_OMIT_CAST
60547  if( op==TK_CAST ){
60548    assert( !ExprHasProperty(pExpr, EP_IntValue) );
60549    return sqlite3AffinityType(pExpr->u.zToken);
60550  }
60551#endif
60552  if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
60553   && pExpr->pTab!=0
60554  ){
60555    /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
60556    ** a TK_COLUMN but was previously evaluated and cached in a register */
60557    int j = pExpr->iColumn;
60558    if( j<0 ) return SQLITE_AFF_INTEGER;
60559    assert( pExpr->pTab && j<pExpr->pTab->nCol );
60560    return pExpr->pTab->aCol[j].affinity;
60561  }
60562  return pExpr->affinity;
60563}
60564
60565/*
60566** Set the collating sequence for expression pExpr to be the collating
60567** sequence named by pToken.   Return a pointer to the revised expression.
60568** The collating sequence is marked as "explicit" using the EP_ExpCollate
60569** flag.  An explicit collating sequence will override implicit
60570** collating sequences.
60571*/
60572SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
60573  char *zColl = 0;            /* Dequoted name of collation sequence */
60574  CollSeq *pColl;
60575  sqlite3 *db = pParse->db;
60576  zColl = sqlite3NameFromToken(db, pCollName);
60577  if( pExpr && zColl ){
60578    pColl = sqlite3LocateCollSeq(pParse, zColl);
60579    if( pColl ){
60580      pExpr->pColl = pColl;
60581      pExpr->flags |= EP_ExpCollate;
60582    }
60583  }
60584  sqlite3DbFree(db, zColl);
60585  return pExpr;
60586}
60587
60588/*
60589** Return the default collation sequence for the expression pExpr. If
60590** there is no default collation type, return 0.
60591*/
60592SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
60593  CollSeq *pColl = 0;
60594  Expr *p = pExpr;
60595  while( ALWAYS(p) ){
60596    int op;
60597    pColl = p->pColl;
60598    if( pColl ) break;
60599    op = p->op;
60600    if( p->pTab!=0 && (
60601        op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
60602    )){
60603      /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
60604      ** a TK_COLUMN but was previously evaluated and cached in a register */
60605      const char *zColl;
60606      int j = p->iColumn;
60607      if( j>=0 ){
60608        sqlite3 *db = pParse->db;
60609        zColl = p->pTab->aCol[j].zColl;
60610        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
60611        pExpr->pColl = pColl;
60612      }
60613      break;
60614    }
60615    if( op!=TK_CAST && op!=TK_UPLUS ){
60616      break;
60617    }
60618    p = p->pLeft;
60619  }
60620  if( sqlite3CheckCollSeq(pParse, pColl) ){
60621    pColl = 0;
60622  }
60623  return pColl;
60624}
60625
60626/*
60627** pExpr is an operand of a comparison operator.  aff2 is the
60628** type affinity of the other operand.  This routine returns the
60629** type affinity that should be used for the comparison operator.
60630*/
60631SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
60632  char aff1 = sqlite3ExprAffinity(pExpr);
60633  if( aff1 && aff2 ){
60634    /* Both sides of the comparison are columns. If one has numeric
60635    ** affinity, use that. Otherwise use no affinity.
60636    */
60637    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
60638      return SQLITE_AFF_NUMERIC;
60639    }else{
60640      return SQLITE_AFF_NONE;
60641    }
60642  }else if( !aff1 && !aff2 ){
60643    /* Neither side of the comparison is a column.  Compare the
60644    ** results directly.
60645    */
60646    return SQLITE_AFF_NONE;
60647  }else{
60648    /* One side is a column, the other is not. Use the columns affinity. */
60649    assert( aff1==0 || aff2==0 );
60650    return (aff1 + aff2);
60651  }
60652}
60653
60654/*
60655** pExpr is a comparison operator.  Return the type affinity that should
60656** be applied to both operands prior to doing the comparison.
60657*/
60658static char comparisonAffinity(Expr *pExpr){
60659  char aff;
60660  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
60661          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
60662          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
60663  assert( pExpr->pLeft );
60664  aff = sqlite3ExprAffinity(pExpr->pLeft);
60665  if( pExpr->pRight ){
60666    aff = sqlite3CompareAffinity(pExpr->pRight, aff);
60667  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
60668    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
60669  }else if( !aff ){
60670    aff = SQLITE_AFF_NONE;
60671  }
60672  return aff;
60673}
60674
60675/*
60676** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
60677** idx_affinity is the affinity of an indexed column. Return true
60678** if the index with affinity idx_affinity may be used to implement
60679** the comparison in pExpr.
60680*/
60681SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
60682  char aff = comparisonAffinity(pExpr);
60683  switch( aff ){
60684    case SQLITE_AFF_NONE:
60685      return 1;
60686    case SQLITE_AFF_TEXT:
60687      return idx_affinity==SQLITE_AFF_TEXT;
60688    default:
60689      return sqlite3IsNumericAffinity(idx_affinity);
60690  }
60691}
60692
60693/*
60694** Return the P5 value that should be used for a binary comparison
60695** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
60696*/
60697static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
60698  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
60699  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
60700  return aff;
60701}
60702
60703/*
60704** Return a pointer to the collation sequence that should be used by
60705** a binary comparison operator comparing pLeft and pRight.
60706**
60707** If the left hand expression has a collating sequence type, then it is
60708** used. Otherwise the collation sequence for the right hand expression
60709** is used, or the default (BINARY) if neither expression has a collating
60710** type.
60711**
60712** Argument pRight (but not pLeft) may be a null pointer. In this case,
60713** it is not considered.
60714*/
60715SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
60716  Parse *pParse,
60717  Expr *pLeft,
60718  Expr *pRight
60719){
60720  CollSeq *pColl;
60721  assert( pLeft );
60722  if( pLeft->flags & EP_ExpCollate ){
60723    assert( pLeft->pColl );
60724    pColl = pLeft->pColl;
60725  }else if( pRight && pRight->flags & EP_ExpCollate ){
60726    assert( pRight->pColl );
60727    pColl = pRight->pColl;
60728  }else{
60729    pColl = sqlite3ExprCollSeq(pParse, pLeft);
60730    if( !pColl ){
60731      pColl = sqlite3ExprCollSeq(pParse, pRight);
60732    }
60733  }
60734  return pColl;
60735}
60736
60737/*
60738** Generate code for a comparison operator.
60739*/
60740static int codeCompare(
60741  Parse *pParse,    /* The parsing (and code generating) context */
60742  Expr *pLeft,      /* The left operand */
60743  Expr *pRight,     /* The right operand */
60744  int opcode,       /* The comparison opcode */
60745  int in1, int in2, /* Register holding operands */
60746  int dest,         /* Jump here if true.  */
60747  int jumpIfNull    /* If true, jump if either operand is NULL */
60748){
60749  int p5;
60750  int addr;
60751  CollSeq *p4;
60752
60753  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
60754  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
60755  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
60756                           (void*)p4, P4_COLLSEQ);
60757  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
60758  if( (p5 & SQLITE_AFF_MASK)!=SQLITE_AFF_NONE ){
60759    sqlite3ExprCacheAffinityChange(pParse, in1, 1);
60760    sqlite3ExprCacheAffinityChange(pParse, in2, 1);
60761  }
60762  return addr;
60763}
60764
60765#if SQLITE_MAX_EXPR_DEPTH>0
60766/*
60767** Check that argument nHeight is less than or equal to the maximum
60768** expression depth allowed. If it is not, leave an error message in
60769** pParse.
60770*/
60771SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
60772  int rc = SQLITE_OK;
60773  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
60774  if( nHeight>mxHeight ){
60775    sqlite3ErrorMsg(pParse,
60776       "Expression tree is too large (maximum depth %d)", mxHeight
60777    );
60778    rc = SQLITE_ERROR;
60779  }
60780  return rc;
60781}
60782
60783/* The following three functions, heightOfExpr(), heightOfExprList()
60784** and heightOfSelect(), are used to determine the maximum height
60785** of any expression tree referenced by the structure passed as the
60786** first argument.
60787**
60788** If this maximum height is greater than the current value pointed
60789** to by pnHeight, the second parameter, then set *pnHeight to that
60790** value.
60791*/
60792static void heightOfExpr(Expr *p, int *pnHeight){
60793  if( p ){
60794    if( p->nHeight>*pnHeight ){
60795      *pnHeight = p->nHeight;
60796    }
60797  }
60798}
60799static void heightOfExprList(ExprList *p, int *pnHeight){
60800  if( p ){
60801    int i;
60802    for(i=0; i<p->nExpr; i++){
60803      heightOfExpr(p->a[i].pExpr, pnHeight);
60804    }
60805  }
60806}
60807static void heightOfSelect(Select *p, int *pnHeight){
60808  if( p ){
60809    heightOfExpr(p->pWhere, pnHeight);
60810    heightOfExpr(p->pHaving, pnHeight);
60811    heightOfExpr(p->pLimit, pnHeight);
60812    heightOfExpr(p->pOffset, pnHeight);
60813    heightOfExprList(p->pEList, pnHeight);
60814    heightOfExprList(p->pGroupBy, pnHeight);
60815    heightOfExprList(p->pOrderBy, pnHeight);
60816    heightOfSelect(p->pPrior, pnHeight);
60817  }
60818}
60819
60820/*
60821** Set the Expr.nHeight variable in the structure passed as an
60822** argument. An expression with no children, Expr.pList or
60823** Expr.pSelect member has a height of 1. Any other expression
60824** has a height equal to the maximum height of any other
60825** referenced Expr plus one.
60826*/
60827static void exprSetHeight(Expr *p){
60828  int nHeight = 0;
60829  heightOfExpr(p->pLeft, &nHeight);
60830  heightOfExpr(p->pRight, &nHeight);
60831  if( ExprHasProperty(p, EP_xIsSelect) ){
60832    heightOfSelect(p->x.pSelect, &nHeight);
60833  }else{
60834    heightOfExprList(p->x.pList, &nHeight);
60835  }
60836  p->nHeight = nHeight + 1;
60837}
60838
60839/*
60840** Set the Expr.nHeight variable using the exprSetHeight() function. If
60841** the height is greater than the maximum allowed expression depth,
60842** leave an error in pParse.
60843*/
60844SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
60845  exprSetHeight(p);
60846  sqlite3ExprCheckHeight(pParse, p->nHeight);
60847}
60848
60849/*
60850** Return the maximum height of any expression tree referenced
60851** by the select statement passed as an argument.
60852*/
60853SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
60854  int nHeight = 0;
60855  heightOfSelect(p, &nHeight);
60856  return nHeight;
60857}
60858#else
60859  #define exprSetHeight(y)
60860#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
60861
60862/*
60863** This routine is the core allocator for Expr nodes.
60864**
60865** Construct a new expression node and return a pointer to it.  Memory
60866** for this node and for the pToken argument is a single allocation
60867** obtained from sqlite3DbMalloc().  The calling function
60868** is responsible for making sure the node eventually gets freed.
60869**
60870** If dequote is true, then the token (if it exists) is dequoted.
60871** If dequote is false, no dequoting is performance.  The deQuote
60872** parameter is ignored if pToken is NULL or if the token does not
60873** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
60874** then the EP_DblQuoted flag is set on the expression node.
60875**
60876** Special case:  If op==TK_INTEGER and pToken points to a string that
60877** can be translated into a 32-bit integer, then the token is not
60878** stored in u.zToken.  Instead, the integer values is written
60879** into u.iValue and the EP_IntValue flag is set.  No extra storage
60880** is allocated to hold the integer text and the dequote flag is ignored.
60881*/
60882SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
60883  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
60884  int op,                 /* Expression opcode */
60885  const Token *pToken,    /* Token argument.  Might be NULL */
60886  int dequote             /* True to dequote */
60887){
60888  Expr *pNew;
60889  int nExtra = 0;
60890  int iValue = 0;
60891
60892  if( pToken ){
60893    if( op!=TK_INTEGER || pToken->z==0
60894          || sqlite3GetInt32(pToken->z, &iValue)==0 ){
60895      nExtra = pToken->n+1;
60896    }
60897  }
60898  pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
60899  if( pNew ){
60900    pNew->op = (u8)op;
60901    pNew->iAgg = -1;
60902    if( pToken ){
60903      if( nExtra==0 ){
60904        pNew->flags |= EP_IntValue;
60905        pNew->u.iValue = iValue;
60906      }else{
60907        int c;
60908        pNew->u.zToken = (char*)&pNew[1];
60909        memcpy(pNew->u.zToken, pToken->z, pToken->n);
60910        pNew->u.zToken[pToken->n] = 0;
60911        if( dequote && nExtra>=3
60912             && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
60913          sqlite3Dequote(pNew->u.zToken);
60914          if( c=='"' ) pNew->flags |= EP_DblQuoted;
60915        }
60916      }
60917    }
60918#if SQLITE_MAX_EXPR_DEPTH>0
60919    pNew->nHeight = 1;
60920#endif
60921  }
60922  return pNew;
60923}
60924
60925/*
60926** Allocate a new expression node from a zero-terminated token that has
60927** already been dequoted.
60928*/
60929SQLITE_PRIVATE Expr *sqlite3Expr(
60930  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
60931  int op,                 /* Expression opcode */
60932  const char *zToken      /* Token argument.  Might be NULL */
60933){
60934  Token x;
60935  x.z = zToken;
60936  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
60937  return sqlite3ExprAlloc(db, op, &x, 0);
60938}
60939
60940/*
60941** Attach subtrees pLeft and pRight to the Expr node pRoot.
60942**
60943** If pRoot==NULL that means that a memory allocation error has occurred.
60944** In that case, delete the subtrees pLeft and pRight.
60945*/
60946SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
60947  sqlite3 *db,
60948  Expr *pRoot,
60949  Expr *pLeft,
60950  Expr *pRight
60951){
60952  if( pRoot==0 ){
60953    assert( db->mallocFailed );
60954    sqlite3ExprDelete(db, pLeft);
60955    sqlite3ExprDelete(db, pRight);
60956  }else{
60957    if( pRight ){
60958      pRoot->pRight = pRight;
60959      if( pRight->flags & EP_ExpCollate ){
60960        pRoot->flags |= EP_ExpCollate;
60961        pRoot->pColl = pRight->pColl;
60962      }
60963    }
60964    if( pLeft ){
60965      pRoot->pLeft = pLeft;
60966      if( pLeft->flags & EP_ExpCollate ){
60967        pRoot->flags |= EP_ExpCollate;
60968        pRoot->pColl = pLeft->pColl;
60969      }
60970    }
60971    exprSetHeight(pRoot);
60972  }
60973}
60974
60975/*
60976** Allocate a Expr node which joins as many as two subtrees.
60977**
60978** One or both of the subtrees can be NULL.  Return a pointer to the new
60979** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
60980** free the subtrees and return NULL.
60981*/
60982SQLITE_PRIVATE Expr *sqlite3PExpr(
60983  Parse *pParse,          /* Parsing context */
60984  int op,                 /* Expression opcode */
60985  Expr *pLeft,            /* Left operand */
60986  Expr *pRight,           /* Right operand */
60987  const Token *pToken     /* Argument token */
60988){
60989  Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
60990  sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
60991  return p;
60992}
60993
60994/*
60995** Join two expressions using an AND operator.  If either expression is
60996** NULL, then just return the other expression.
60997*/
60998SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
60999  if( pLeft==0 ){
61000    return pRight;
61001  }else if( pRight==0 ){
61002    return pLeft;
61003  }else{
61004    Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
61005    sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
61006    return pNew;
61007  }
61008}
61009
61010/*
61011** Construct a new expression node for a function with multiple
61012** arguments.
61013*/
61014SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
61015  Expr *pNew;
61016  sqlite3 *db = pParse->db;
61017  assert( pToken );
61018  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
61019  if( pNew==0 ){
61020    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
61021    return 0;
61022  }
61023  pNew->x.pList = pList;
61024  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
61025  sqlite3ExprSetHeight(pParse, pNew);
61026  return pNew;
61027}
61028
61029/*
61030** Assign a variable number to an expression that encodes a wildcard
61031** in the original SQL statement.
61032**
61033** Wildcards consisting of a single "?" are assigned the next sequential
61034** variable number.
61035**
61036** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
61037** sure "nnn" is not too be to avoid a denial of service attack when
61038** the SQL statement comes from an external source.
61039**
61040** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
61041** as the previous instance of the same wildcard.  Or if this is the first
61042** instance of the wildcard, the next sequenial variable number is
61043** assigned.
61044*/
61045SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
61046  sqlite3 *db = pParse->db;
61047  const char *z;
61048
61049  if( pExpr==0 ) return;
61050  assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
61051  z = pExpr->u.zToken;
61052  assert( z!=0 );
61053  assert( z[0]!=0 );
61054  if( z[1]==0 ){
61055    /* Wildcard of the form "?".  Assign the next variable number */
61056    assert( z[0]=='?' );
61057    pExpr->iColumn = (ynVar)(++pParse->nVar);
61058  }else if( z[0]=='?' ){
61059    /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
61060    ** use it as the variable number */
61061    int i = atoi((char*)&z[1]);
61062    pExpr->iColumn = (ynVar)i;
61063    testcase( i==0 );
61064    testcase( i==1 );
61065    testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
61066    testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
61067    if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
61068      sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
61069          db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
61070    }
61071    if( i>pParse->nVar ){
61072      pParse->nVar = i;
61073    }
61074  }else{
61075    /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
61076    ** number as the prior appearance of the same name, or if the name
61077    ** has never appeared before, reuse the same variable number
61078    */
61079    int i;
61080    u32 n;
61081    n = sqlite3Strlen30(z);
61082    for(i=0; i<pParse->nVarExpr; i++){
61083      Expr *pE = pParse->apVarExpr[i];
61084      assert( pE!=0 );
61085      if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
61086        pExpr->iColumn = pE->iColumn;
61087        break;
61088      }
61089    }
61090    if( i>=pParse->nVarExpr ){
61091      pExpr->iColumn = (ynVar)(++pParse->nVar);
61092      if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
61093        pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
61094        pParse->apVarExpr =
61095            sqlite3DbReallocOrFree(
61096              db,
61097              pParse->apVarExpr,
61098              pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
61099            );
61100      }
61101      if( !db->mallocFailed ){
61102        assert( pParse->apVarExpr!=0 );
61103        pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
61104      }
61105    }
61106  }
61107  if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
61108    sqlite3ErrorMsg(pParse, "too many SQL variables");
61109  }
61110}
61111
61112/*
61113** Recursively delete an expression tree.
61114*/
61115SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
61116  if( p==0 ) return;
61117  if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
61118    sqlite3ExprDelete(db, p->pLeft);
61119    sqlite3ExprDelete(db, p->pRight);
61120    if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
61121      sqlite3DbFree(db, p->u.zToken);
61122    }
61123    if( ExprHasProperty(p, EP_xIsSelect) ){
61124      sqlite3SelectDelete(db, p->x.pSelect);
61125    }else{
61126      sqlite3ExprListDelete(db, p->x.pList);
61127    }
61128  }
61129  if( !ExprHasProperty(p, EP_Static) ){
61130    sqlite3DbFree(db, p);
61131  }
61132}
61133
61134/*
61135** Return the number of bytes allocated for the expression structure
61136** passed as the first argument. This is always one of EXPR_FULLSIZE,
61137** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
61138*/
61139static int exprStructSize(Expr *p){
61140  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
61141  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
61142  return EXPR_FULLSIZE;
61143}
61144
61145/*
61146** The dupedExpr*Size() routines each return the number of bytes required
61147** to store a copy of an expression or expression tree.  They differ in
61148** how much of the tree is measured.
61149**
61150**     dupedExprStructSize()     Size of only the Expr structure
61151**     dupedExprNodeSize()       Size of Expr + space for token
61152**     dupedExprSize()           Expr + token + subtree components
61153**
61154***************************************************************************
61155**
61156** The dupedExprStructSize() function returns two values OR-ed together:
61157** (1) the space required for a copy of the Expr structure only and
61158** (2) the EP_xxx flags that indicate what the structure size should be.
61159** The return values is always one of:
61160**
61161**      EXPR_FULLSIZE
61162**      EXPR_REDUCEDSIZE   | EP_Reduced
61163**      EXPR_TOKENONLYSIZE | EP_TokenOnly
61164**
61165** The size of the structure can be found by masking the return value
61166** of this routine with 0xfff.  The flags can be found by masking the
61167** return value with EP_Reduced|EP_TokenOnly.
61168**
61169** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
61170** (unreduced) Expr objects as they or originally constructed by the parser.
61171** During expression analysis, extra information is computed and moved into
61172** later parts of teh Expr object and that extra information might get chopped
61173** off if the expression is reduced.  Note also that it does not work to
61174** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
61175** to reduce a pristine expression tree from the parser.  The implementation
61176** of dupedExprStructSize() contain multiple assert() statements that attempt
61177** to enforce this constraint.
61178*/
61179static int dupedExprStructSize(Expr *p, int flags){
61180  int nSize;
61181  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
61182  if( 0==(flags&EXPRDUP_REDUCE) ){
61183    nSize = EXPR_FULLSIZE;
61184  }else{
61185    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
61186    assert( !ExprHasProperty(p, EP_FromJoin) );
61187    assert( (p->flags2 & EP2_MallocedToken)==0 );
61188    assert( (p->flags2 & EP2_Irreducible)==0 );
61189    if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
61190      nSize = EXPR_REDUCEDSIZE | EP_Reduced;
61191    }else{
61192      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
61193    }
61194  }
61195  return nSize;
61196}
61197
61198/*
61199** This function returns the space in bytes required to store the copy
61200** of the Expr structure and a copy of the Expr.u.zToken string (if that
61201** string is defined.)
61202*/
61203static int dupedExprNodeSize(Expr *p, int flags){
61204  int nByte = dupedExprStructSize(p, flags) & 0xfff;
61205  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
61206    nByte += sqlite3Strlen30(p->u.zToken)+1;
61207  }
61208  return ROUND8(nByte);
61209}
61210
61211/*
61212** Return the number of bytes required to create a duplicate of the
61213** expression passed as the first argument. The second argument is a
61214** mask containing EXPRDUP_XXX flags.
61215**
61216** The value returned includes space to create a copy of the Expr struct
61217** itself and the buffer referred to by Expr.u.zToken, if any.
61218**
61219** If the EXPRDUP_REDUCE flag is set, then the return value includes
61220** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
61221** and Expr.pRight variables (but not for any structures pointed to or
61222** descended from the Expr.x.pList or Expr.x.pSelect variables).
61223*/
61224static int dupedExprSize(Expr *p, int flags){
61225  int nByte = 0;
61226  if( p ){
61227    nByte = dupedExprNodeSize(p, flags);
61228    if( flags&EXPRDUP_REDUCE ){
61229      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
61230    }
61231  }
61232  return nByte;
61233}
61234
61235/*
61236** This function is similar to sqlite3ExprDup(), except that if pzBuffer
61237** is not NULL then *pzBuffer is assumed to point to a buffer large enough
61238** to store the copy of expression p, the copies of p->u.zToken
61239** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
61240** if any. Before returning, *pzBuffer is set to the first byte passed the
61241** portion of the buffer copied into by this function.
61242*/
61243static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
61244  Expr *pNew = 0;                      /* Value to return */
61245  if( p ){
61246    const int isReduced = (flags&EXPRDUP_REDUCE);
61247    u8 *zAlloc;
61248    u32 staticFlag = 0;
61249
61250    assert( pzBuffer==0 || isReduced );
61251
61252    /* Figure out where to write the new Expr structure. */
61253    if( pzBuffer ){
61254      zAlloc = *pzBuffer;
61255      staticFlag = EP_Static;
61256    }else{
61257      zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
61258    }
61259    pNew = (Expr *)zAlloc;
61260
61261    if( pNew ){
61262      /* Set nNewSize to the size allocated for the structure pointed to
61263      ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
61264      ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
61265      ** by the copy of the p->u.zToken string (if any).
61266      */
61267      const unsigned nStructSize = dupedExprStructSize(p, flags);
61268      const int nNewSize = nStructSize & 0xfff;
61269      int nToken;
61270      if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
61271        nToken = sqlite3Strlen30(p->u.zToken) + 1;
61272      }else{
61273        nToken = 0;
61274      }
61275      if( isReduced ){
61276        assert( ExprHasProperty(p, EP_Reduced)==0 );
61277        memcpy(zAlloc, p, nNewSize);
61278      }else{
61279        int nSize = exprStructSize(p);
61280        memcpy(zAlloc, p, nSize);
61281        memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
61282      }
61283
61284      /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
61285      pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
61286      pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
61287      pNew->flags |= staticFlag;
61288
61289      /* Copy the p->u.zToken string, if any. */
61290      if( nToken ){
61291        char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
61292        memcpy(zToken, p->u.zToken, nToken);
61293      }
61294
61295      if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
61296        /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
61297        if( ExprHasProperty(p, EP_xIsSelect) ){
61298          pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
61299        }else{
61300          pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
61301        }
61302      }
61303
61304      /* Fill in pNew->pLeft and pNew->pRight. */
61305      if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
61306        zAlloc += dupedExprNodeSize(p, flags);
61307        if( ExprHasProperty(pNew, EP_Reduced) ){
61308          pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
61309          pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
61310        }
61311        if( pzBuffer ){
61312          *pzBuffer = zAlloc;
61313        }
61314      }else{
61315        pNew->flags2 = 0;
61316        if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
61317          pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
61318          pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
61319        }
61320      }
61321
61322    }
61323  }
61324  return pNew;
61325}
61326
61327/*
61328** The following group of routines make deep copies of expressions,
61329** expression lists, ID lists, and select statements.  The copies can
61330** be deleted (by being passed to their respective ...Delete() routines)
61331** without effecting the originals.
61332**
61333** The expression list, ID, and source lists return by sqlite3ExprListDup(),
61334** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
61335** by subsequent calls to sqlite*ListAppend() routines.
61336**
61337** Any tables that the SrcList might point to are not duplicated.
61338**
61339** The flags parameter contains a combination of the EXPRDUP_XXX flags.
61340** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
61341** truncated version of the usual Expr structure that will be stored as
61342** part of the in-memory representation of the database schema.
61343*/
61344SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
61345  return exprDup(db, p, flags, 0);
61346}
61347SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
61348  ExprList *pNew;
61349  struct ExprList_item *pItem, *pOldItem;
61350  int i;
61351  if( p==0 ) return 0;
61352  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
61353  if( pNew==0 ) return 0;
61354  pNew->iECursor = 0;
61355  pNew->nExpr = pNew->nAlloc = p->nExpr;
61356  pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
61357  if( pItem==0 ){
61358    sqlite3DbFree(db, pNew);
61359    return 0;
61360  }
61361  pOldItem = p->a;
61362  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
61363    Expr *pOldExpr = pOldItem->pExpr;
61364    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
61365    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
61366    pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
61367    pItem->sortOrder = pOldItem->sortOrder;
61368    pItem->done = 0;
61369    pItem->iCol = pOldItem->iCol;
61370    pItem->iAlias = pOldItem->iAlias;
61371  }
61372  return pNew;
61373}
61374
61375/*
61376** If cursors, triggers, views and subqueries are all omitted from
61377** the build, then none of the following routines, except for
61378** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
61379** called with a NULL argument.
61380*/
61381#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
61382 || !defined(SQLITE_OMIT_SUBQUERY)
61383SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
61384  SrcList *pNew;
61385  int i;
61386  int nByte;
61387  if( p==0 ) return 0;
61388  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
61389  pNew = sqlite3DbMallocRaw(db, nByte );
61390  if( pNew==0 ) return 0;
61391  pNew->nSrc = pNew->nAlloc = p->nSrc;
61392  for(i=0; i<p->nSrc; i++){
61393    struct SrcList_item *pNewItem = &pNew->a[i];
61394    struct SrcList_item *pOldItem = &p->a[i];
61395    Table *pTab;
61396    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
61397    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
61398    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
61399    pNewItem->jointype = pOldItem->jointype;
61400    pNewItem->iCursor = pOldItem->iCursor;
61401    pNewItem->isPopulated = pOldItem->isPopulated;
61402    pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
61403    pNewItem->notIndexed = pOldItem->notIndexed;
61404    pNewItem->pIndex = pOldItem->pIndex;
61405    pTab = pNewItem->pTab = pOldItem->pTab;
61406    if( pTab ){
61407      pTab->nRef++;
61408    }
61409    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
61410    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
61411    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
61412    pNewItem->colUsed = pOldItem->colUsed;
61413  }
61414  return pNew;
61415}
61416SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
61417  IdList *pNew;
61418  int i;
61419  if( p==0 ) return 0;
61420  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
61421  if( pNew==0 ) return 0;
61422  pNew->nId = pNew->nAlloc = p->nId;
61423  pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
61424  if( pNew->a==0 ){
61425    sqlite3DbFree(db, pNew);
61426    return 0;
61427  }
61428  for(i=0; i<p->nId; i++){
61429    struct IdList_item *pNewItem = &pNew->a[i];
61430    struct IdList_item *pOldItem = &p->a[i];
61431    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
61432    pNewItem->idx = pOldItem->idx;
61433  }
61434  return pNew;
61435}
61436SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
61437  Select *pNew;
61438  if( p==0 ) return 0;
61439  pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
61440  if( pNew==0 ) return 0;
61441  pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
61442  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
61443  pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
61444  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
61445  pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
61446  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
61447  pNew->op = p->op;
61448  pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
61449  pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
61450  pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
61451  pNew->iLimit = 0;
61452  pNew->iOffset = 0;
61453  pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
61454  pNew->pRightmost = 0;
61455  pNew->addrOpenEphm[0] = -1;
61456  pNew->addrOpenEphm[1] = -1;
61457  pNew->addrOpenEphm[2] = -1;
61458  return pNew;
61459}
61460#else
61461SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
61462  assert( p==0 );
61463  return 0;
61464}
61465#endif
61466
61467
61468/*
61469** Add a new element to the end of an expression list.  If pList is
61470** initially NULL, then create a new expression list.
61471**
61472** If a memory allocation error occurs, the entire list is freed and
61473** NULL is returned.  If non-NULL is returned, then it is guaranteed
61474** that the new entry was successfully appended.
61475*/
61476SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
61477  Parse *pParse,          /* Parsing context */
61478  ExprList *pList,        /* List to which to append. Might be NULL */
61479  Expr *pExpr             /* Expression to be appended. Might be NULL */
61480){
61481  sqlite3 *db = pParse->db;
61482  if( pList==0 ){
61483    pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
61484    if( pList==0 ){
61485      goto no_mem;
61486    }
61487    assert( pList->nAlloc==0 );
61488  }
61489  if( pList->nAlloc<=pList->nExpr ){
61490    struct ExprList_item *a;
61491    int n = pList->nAlloc*2 + 4;
61492    a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
61493    if( a==0 ){
61494      goto no_mem;
61495    }
61496    pList->a = a;
61497    pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
61498  }
61499  assert( pList->a!=0 );
61500  if( 1 ){
61501    struct ExprList_item *pItem = &pList->a[pList->nExpr++];
61502    memset(pItem, 0, sizeof(*pItem));
61503    pItem->pExpr = pExpr;
61504  }
61505  return pList;
61506
61507no_mem:
61508  /* Avoid leaking memory if malloc has failed. */
61509  sqlite3ExprDelete(db, pExpr);
61510  sqlite3ExprListDelete(db, pList);
61511  return 0;
61512}
61513
61514/*
61515** Set the ExprList.a[].zName element of the most recently added item
61516** on the expression list.
61517**
61518** pList might be NULL following an OOM error.  But pName should never be
61519** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
61520** is set.
61521*/
61522SQLITE_PRIVATE void sqlite3ExprListSetName(
61523  Parse *pParse,          /* Parsing context */
61524  ExprList *pList,        /* List to which to add the span. */
61525  Token *pName,           /* Name to be added */
61526  int dequote             /* True to cause the name to be dequoted */
61527){
61528  assert( pList!=0 || pParse->db->mallocFailed!=0 );
61529  if( pList ){
61530    struct ExprList_item *pItem;
61531    assert( pList->nExpr>0 );
61532    pItem = &pList->a[pList->nExpr-1];
61533    assert( pItem->zName==0 );
61534    pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
61535    if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
61536  }
61537}
61538
61539/*
61540** Set the ExprList.a[].zSpan element of the most recently added item
61541** on the expression list.
61542**
61543** pList might be NULL following an OOM error.  But pSpan should never be
61544** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
61545** is set.
61546*/
61547SQLITE_PRIVATE void sqlite3ExprListSetSpan(
61548  Parse *pParse,          /* Parsing context */
61549  ExprList *pList,        /* List to which to add the span. */
61550  ExprSpan *pSpan         /* The span to be added */
61551){
61552  sqlite3 *db = pParse->db;
61553  assert( pList!=0 || db->mallocFailed!=0 );
61554  if( pList ){
61555    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
61556    assert( pList->nExpr>0 );
61557    assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
61558    sqlite3DbFree(db, pItem->zSpan);
61559    pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
61560                                    (int)(pSpan->zEnd - pSpan->zStart));
61561  }
61562}
61563
61564/*
61565** If the expression list pEList contains more than iLimit elements,
61566** leave an error message in pParse.
61567*/
61568SQLITE_PRIVATE void sqlite3ExprListCheckLength(
61569  Parse *pParse,
61570  ExprList *pEList,
61571  const char *zObject
61572){
61573  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
61574  testcase( pEList && pEList->nExpr==mx );
61575  testcase( pEList && pEList->nExpr==mx+1 );
61576  if( pEList && pEList->nExpr>mx ){
61577    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
61578  }
61579}
61580
61581/*
61582** Delete an entire expression list.
61583*/
61584SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
61585  int i;
61586  struct ExprList_item *pItem;
61587  if( pList==0 ) return;
61588  assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
61589  assert( pList->nExpr<=pList->nAlloc );
61590  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
61591    sqlite3ExprDelete(db, pItem->pExpr);
61592    sqlite3DbFree(db, pItem->zName);
61593    sqlite3DbFree(db, pItem->zSpan);
61594  }
61595  sqlite3DbFree(db, pList->a);
61596  sqlite3DbFree(db, pList);
61597}
61598
61599/*
61600** These routines are Walker callbacks.  Walker.u.pi is a pointer
61601** to an integer.  These routines are checking an expression to see
61602** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
61603** not constant.
61604**
61605** These callback routines are used to implement the following:
61606**
61607**     sqlite3ExprIsConstant()
61608**     sqlite3ExprIsConstantNotJoin()
61609**     sqlite3ExprIsConstantOrFunction()
61610**
61611*/
61612static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
61613
61614  /* If pWalker->u.i is 3 then any term of the expression that comes from
61615  ** the ON or USING clauses of a join disqualifies the expression
61616  ** from being considered constant. */
61617  if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
61618    pWalker->u.i = 0;
61619    return WRC_Abort;
61620  }
61621
61622  switch( pExpr->op ){
61623    /* Consider functions to be constant if all their arguments are constant
61624    ** and pWalker->u.i==2 */
61625    case TK_FUNCTION:
61626      if( pWalker->u.i==2 ) return 0;
61627      /* Fall through */
61628    case TK_ID:
61629    case TK_COLUMN:
61630    case TK_AGG_FUNCTION:
61631    case TK_AGG_COLUMN:
61632      testcase( pExpr->op==TK_ID );
61633      testcase( pExpr->op==TK_COLUMN );
61634      testcase( pExpr->op==TK_AGG_FUNCTION );
61635      testcase( pExpr->op==TK_AGG_COLUMN );
61636      pWalker->u.i = 0;
61637      return WRC_Abort;
61638    default:
61639      testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
61640      testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
61641      return WRC_Continue;
61642  }
61643}
61644static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
61645  UNUSED_PARAMETER(NotUsed);
61646  pWalker->u.i = 0;
61647  return WRC_Abort;
61648}
61649static int exprIsConst(Expr *p, int initFlag){
61650  Walker w;
61651  w.u.i = initFlag;
61652  w.xExprCallback = exprNodeIsConstant;
61653  w.xSelectCallback = selectNodeIsConstant;
61654  sqlite3WalkExpr(&w, p);
61655  return w.u.i;
61656}
61657
61658/*
61659** Walk an expression tree.  Return 1 if the expression is constant
61660** and 0 if it involves variables or function calls.
61661**
61662** For the purposes of this function, a double-quoted string (ex: "abc")
61663** is considered a variable but a single-quoted string (ex: 'abc') is
61664** a constant.
61665*/
61666SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
61667  return exprIsConst(p, 1);
61668}
61669
61670/*
61671** Walk an expression tree.  Return 1 if the expression is constant
61672** that does no originate from the ON or USING clauses of a join.
61673** Return 0 if it involves variables or function calls or terms from
61674** an ON or USING clause.
61675*/
61676SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
61677  return exprIsConst(p, 3);
61678}
61679
61680/*
61681** Walk an expression tree.  Return 1 if the expression is constant
61682** or a function call with constant arguments.  Return and 0 if there
61683** are any variables.
61684**
61685** For the purposes of this function, a double-quoted string (ex: "abc")
61686** is considered a variable but a single-quoted string (ex: 'abc') is
61687** a constant.
61688*/
61689SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
61690  return exprIsConst(p, 2);
61691}
61692
61693/*
61694** If the expression p codes a constant integer that is small enough
61695** to fit in a 32-bit integer, return 1 and put the value of the integer
61696** in *pValue.  If the expression is not an integer or if it is too big
61697** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
61698*/
61699SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
61700  int rc = 0;
61701  if( p->flags & EP_IntValue ){
61702    *pValue = p->u.iValue;
61703    return 1;
61704  }
61705  switch( p->op ){
61706    case TK_INTEGER: {
61707      rc = sqlite3GetInt32(p->u.zToken, pValue);
61708      assert( rc==0 );
61709      break;
61710    }
61711    case TK_UPLUS: {
61712      rc = sqlite3ExprIsInteger(p->pLeft, pValue);
61713      break;
61714    }
61715    case TK_UMINUS: {
61716      int v;
61717      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
61718        *pValue = -v;
61719        rc = 1;
61720      }
61721      break;
61722    }
61723    default: break;
61724  }
61725  if( rc ){
61726    assert( ExprHasAnyProperty(p, EP_Reduced|EP_TokenOnly)
61727               || (p->flags2 & EP2_MallocedToken)==0 );
61728    p->op = TK_INTEGER;
61729    p->flags |= EP_IntValue;
61730    p->u.iValue = *pValue;
61731  }
61732  return rc;
61733}
61734
61735/*
61736** Return FALSE if there is no chance that the expression can be NULL.
61737**
61738** If the expression might be NULL or if the expression is too complex
61739** to tell return TRUE.
61740**
61741** This routine is used as an optimization, to skip OP_IsNull opcodes
61742** when we know that a value cannot be NULL.  Hence, a false positive
61743** (returning TRUE when in fact the expression can never be NULL) might
61744** be a small performance hit but is otherwise harmless.  On the other
61745** hand, a false negative (returning FALSE when the result could be NULL)
61746** will likely result in an incorrect answer.  So when in doubt, return
61747** TRUE.
61748*/
61749SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
61750  u8 op;
61751  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
61752  op = p->op;
61753  if( op==TK_REGISTER ) op = p->op2;
61754  switch( op ){
61755    case TK_INTEGER:
61756    case TK_STRING:
61757    case TK_FLOAT:
61758    case TK_BLOB:
61759      return 0;
61760    default:
61761      return 1;
61762  }
61763}
61764
61765/*
61766** Generate an OP_IsNull instruction that tests register iReg and jumps
61767** to location iDest if the value in iReg is NULL.  The value in iReg
61768** was computed by pExpr.  If we can look at pExpr at compile-time and
61769** determine that it can never generate a NULL, then the OP_IsNull operation
61770** can be omitted.
61771*/
61772SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
61773  Vdbe *v,            /* The VDBE under construction */
61774  const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
61775  int iReg,           /* Test the value in this register for NULL */
61776  int iDest           /* Jump here if the value is null */
61777){
61778  if( sqlite3ExprCanBeNull(pExpr) ){
61779    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
61780  }
61781}
61782
61783/*
61784** Return TRUE if the given expression is a constant which would be
61785** unchanged by OP_Affinity with the affinity given in the second
61786** argument.
61787**
61788** This routine is used to determine if the OP_Affinity operation
61789** can be omitted.  When in doubt return FALSE.  A false negative
61790** is harmless.  A false positive, however, can result in the wrong
61791** answer.
61792*/
61793SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
61794  u8 op;
61795  if( aff==SQLITE_AFF_NONE ) return 1;
61796  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
61797  op = p->op;
61798  if( op==TK_REGISTER ) op = p->op2;
61799  switch( op ){
61800    case TK_INTEGER: {
61801      return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
61802    }
61803    case TK_FLOAT: {
61804      return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
61805    }
61806    case TK_STRING: {
61807      return aff==SQLITE_AFF_TEXT;
61808    }
61809    case TK_BLOB: {
61810      return 1;
61811    }
61812    case TK_COLUMN: {
61813      assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
61814      return p->iColumn<0
61815          && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
61816    }
61817    default: {
61818      return 0;
61819    }
61820  }
61821}
61822
61823/*
61824** Return TRUE if the given string is a row-id column name.
61825*/
61826SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
61827  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
61828  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
61829  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
61830  return 0;
61831}
61832
61833/*
61834** Return true if we are able to the IN operator optimization on a
61835** query of the form
61836**
61837**       x IN (SELECT ...)
61838**
61839** Where the SELECT... clause is as specified by the parameter to this
61840** routine.
61841**
61842** The Select object passed in has already been preprocessed and no
61843** errors have been found.
61844*/
61845#ifndef SQLITE_OMIT_SUBQUERY
61846static int isCandidateForInOpt(Select *p){
61847  SrcList *pSrc;
61848  ExprList *pEList;
61849  Table *pTab;
61850  if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
61851  if( p->pPrior ) return 0;              /* Not a compound SELECT */
61852  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
61853    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
61854    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
61855    return 0; /* No DISTINCT keyword and no aggregate functions */
61856  }
61857  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
61858  if( p->pLimit ) return 0;              /* Has no LIMIT clause */
61859  assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
61860  if( p->pWhere ) return 0;              /* Has no WHERE clause */
61861  pSrc = p->pSrc;
61862  assert( pSrc!=0 );
61863  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
61864  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
61865  pTab = pSrc->a[0].pTab;
61866  if( NEVER(pTab==0) ) return 0;
61867  assert( pTab->pSelect==0 );            /* FROM clause is not a view */
61868  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
61869  pEList = p->pEList;
61870  if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
61871  if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
61872  return 1;
61873}
61874#endif /* SQLITE_OMIT_SUBQUERY */
61875
61876/*
61877** This function is used by the implementation of the IN (...) operator.
61878** It's job is to find or create a b-tree structure that may be used
61879** either to test for membership of the (...) set or to iterate through
61880** its members, skipping duplicates.
61881**
61882** The index of the cursor opened on the b-tree (database table, database index
61883** or ephermal table) is stored in pX->iTable before this function returns.
61884** The returned value of this function indicates the b-tree type, as follows:
61885**
61886**   IN_INDEX_ROWID - The cursor was opened on a database table.
61887**   IN_INDEX_INDEX - The cursor was opened on a database index.
61888**   IN_INDEX_EPH -   The cursor was opened on a specially created and
61889**                    populated epheremal table.
61890**
61891** An existing b-tree may only be used if the SELECT is of the simple
61892** form:
61893**
61894**     SELECT <column> FROM <table>
61895**
61896** If the prNotFound parameter is 0, then the b-tree will be used to iterate
61897** through the set members, skipping any duplicates. In this case an
61898** epheremal table must be used unless the selected <column> is guaranteed
61899** to be unique - either because it is an INTEGER PRIMARY KEY or it
61900** has a UNIQUE constraint or UNIQUE index.
61901**
61902** If the prNotFound parameter is not 0, then the b-tree will be used
61903** for fast set membership tests. In this case an epheremal table must
61904** be used unless <column> is an INTEGER PRIMARY KEY or an index can
61905** be found with <column> as its left-most column.
61906**
61907** When the b-tree is being used for membership tests, the calling function
61908** needs to know whether or not the structure contains an SQL NULL
61909** value in order to correctly evaluate expressions like "X IN (Y, Z)".
61910** If there is any chance that the (...) might contain a NULL value at
61911** runtime, then a register is allocated and the register number written
61912** to *prNotFound. If there is no chance that the (...) contains a
61913** NULL value, then *prNotFound is left unchanged.
61914**
61915** If a register is allocated and its location stored in *prNotFound, then
61916** its initial value is NULL.  If the (...) does not remain constant
61917** for the duration of the query (i.e. the SELECT within the (...)
61918** is a correlated subquery) then the value of the allocated register is
61919** reset to NULL each time the subquery is rerun. This allows the
61920** caller to use vdbe code equivalent to the following:
61921**
61922**   if( register==NULL ){
61923**     has_null = <test if data structure contains null>
61924**     register = 1
61925**   }
61926**
61927** in order to avoid running the <test if data structure contains null>
61928** test more often than is necessary.
61929*/
61930#ifndef SQLITE_OMIT_SUBQUERY
61931SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
61932  Select *p;                            /* SELECT to the right of IN operator */
61933  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
61934  int iTab = pParse->nTab++;            /* Cursor of the RHS table */
61935  int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
61936
61937  assert( pX->op==TK_IN );
61938
61939  /* Check to see if an existing table or index can be used to
61940  ** satisfy the query.  This is preferable to generating a new
61941  ** ephemeral table.
61942  */
61943  p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
61944  if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
61945    sqlite3 *db = pParse->db;              /* Database connection */
61946    Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
61947    int iCol = pExpr->iColumn;             /* Index of column <column> */
61948    Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
61949    Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
61950    int iDb;                               /* Database idx for pTab */
61951
61952    /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
61953    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
61954    sqlite3CodeVerifySchema(pParse, iDb);
61955    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
61956
61957    /* This function is only called from two places. In both cases the vdbe
61958    ** has already been allocated. So assume sqlite3GetVdbe() is always
61959    ** successful here.
61960    */
61961    assert(v);
61962    if( iCol<0 ){
61963      int iMem = ++pParse->nMem;
61964      int iAddr;
61965
61966      iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
61967      sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
61968
61969      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
61970      eType = IN_INDEX_ROWID;
61971
61972      sqlite3VdbeJumpHere(v, iAddr);
61973    }else{
61974      Index *pIdx;                         /* Iterator variable */
61975
61976      /* The collation sequence used by the comparison. If an index is to
61977      ** be used in place of a temp-table, it must be ordered according
61978      ** to this collation sequence.  */
61979      CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
61980
61981      /* Check that the affinity that will be used to perform the
61982      ** comparison is the same as the affinity of the column. If
61983      ** it is not, it is not possible to use any index.
61984      */
61985      char aff = comparisonAffinity(pX);
61986      int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
61987
61988      for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
61989        if( (pIdx->aiColumn[0]==iCol)
61990         && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
61991         && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
61992        ){
61993          int iMem = ++pParse->nMem;
61994          int iAddr;
61995          char *pKey;
61996
61997          pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
61998          iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
61999          sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
62000
62001          sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
62002                               pKey,P4_KEYINFO_HANDOFF);
62003          VdbeComment((v, "%s", pIdx->zName));
62004          eType = IN_INDEX_INDEX;
62005
62006          sqlite3VdbeJumpHere(v, iAddr);
62007          if( prNotFound && !pTab->aCol[iCol].notNull ){
62008            *prNotFound = ++pParse->nMem;
62009          }
62010        }
62011      }
62012    }
62013  }
62014
62015  if( eType==0 ){
62016    /* Could not found an existing table or index to use as the RHS b-tree.
62017    ** We will have to generate an ephemeral table to do the job.
62018    */
62019    int rMayHaveNull = 0;
62020    eType = IN_INDEX_EPH;
62021    if( prNotFound ){
62022      *prNotFound = rMayHaveNull = ++pParse->nMem;
62023    }else if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
62024      eType = IN_INDEX_ROWID;
62025    }
62026    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
62027  }else{
62028    pX->iTable = iTab;
62029  }
62030  return eType;
62031}
62032#endif
62033
62034/*
62035** Generate code for scalar subqueries used as an expression
62036** and IN operators.  Examples:
62037**
62038**     (SELECT a FROM b)          -- subquery
62039**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
62040**     x IN (4,5,11)              -- IN operator with list on right-hand side
62041**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
62042**
62043** The pExpr parameter describes the expression that contains the IN
62044** operator or subquery.
62045**
62046** If parameter isRowid is non-zero, then expression pExpr is guaranteed
62047** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
62048** to some integer key column of a table B-Tree. In this case, use an
62049** intkey B-Tree to store the set of IN(...) values instead of the usual
62050** (slower) variable length keys B-Tree.
62051**
62052** If rMayHaveNull is non-zero, that means that the operation is an IN
62053** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
62054** Furthermore, the IN is in a WHERE clause and that we really want
62055** to iterate over the RHS of the IN operator in order to quickly locate
62056** all corresponding LHS elements.  All this routine does is initialize
62057** the register given by rMayHaveNull to NULL.  Calling routines will take
62058** care of changing this register value to non-NULL if the RHS is NULL-free.
62059**
62060** If rMayHaveNull is zero, that means that the subquery is being used
62061** for membership testing only.  There is no need to initialize any
62062** registers to indicate the presense or absence of NULLs on the RHS.
62063**
62064** For a SELECT or EXISTS operator, return the register that holds the
62065** result.  For IN operators or if an error occurs, the return value is 0.
62066*/
62067#ifndef SQLITE_OMIT_SUBQUERY
62068SQLITE_PRIVATE int sqlite3CodeSubselect(
62069  Parse *pParse,          /* Parsing context */
62070  Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
62071  int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
62072  int isRowid             /* If true, LHS of IN operator is a rowid */
62073){
62074  int testAddr = 0;                       /* One-time test address */
62075  int rReg = 0;                           /* Register storing resulting */
62076  Vdbe *v = sqlite3GetVdbe(pParse);
62077  if( NEVER(v==0) ) return 0;
62078  sqlite3ExprCachePush(pParse);
62079
62080  /* This code must be run in its entirety every time it is encountered
62081  ** if any of the following is true:
62082  **
62083  **    *  The right-hand side is a correlated subquery
62084  **    *  The right-hand side is an expression list containing variables
62085  **    *  We are inside a trigger
62086  **
62087  ** If all of the above are false, then we can run this code just once
62088  ** save the results, and reuse the same result on subsequent invocations.
62089  */
62090  if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
62091    int mem = ++pParse->nMem;
62092    sqlite3VdbeAddOp1(v, OP_If, mem);
62093    testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
62094    assert( testAddr>0 || pParse->db->mallocFailed );
62095  }
62096
62097  switch( pExpr->op ){
62098    case TK_IN: {
62099      char affinity;
62100      KeyInfo keyInfo;
62101      int addr;        /* Address of OP_OpenEphemeral instruction */
62102      Expr *pLeft = pExpr->pLeft;
62103
62104      if( rMayHaveNull ){
62105        sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
62106      }
62107
62108      affinity = sqlite3ExprAffinity(pLeft);
62109
62110      /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
62111      ** expression it is handled the same way.  An ephemeral table is
62112      ** filled with single-field index keys representing the results
62113      ** from the SELECT or the <exprlist>.
62114      **
62115      ** If the 'x' expression is a column value, or the SELECT...
62116      ** statement returns a column value, then the affinity of that
62117      ** column is used to build the index keys. If both 'x' and the
62118      ** SELECT... statement are columns, then numeric affinity is used
62119      ** if either column has NUMERIC or INTEGER affinity. If neither
62120      ** 'x' nor the SELECT... statement are columns, then numeric affinity
62121      ** is used.
62122      */
62123      pExpr->iTable = pParse->nTab++;
62124      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
62125      memset(&keyInfo, 0, sizeof(keyInfo));
62126      keyInfo.nField = 1;
62127
62128      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
62129        /* Case 1:     expr IN (SELECT ...)
62130        **
62131        ** Generate code to write the results of the select into the temporary
62132        ** table allocated and opened above.
62133        */
62134        SelectDest dest;
62135        ExprList *pEList;
62136
62137        assert( !isRowid );
62138        sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
62139        dest.affinity = (u8)affinity;
62140        assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
62141        if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
62142          return 0;
62143        }
62144        pEList = pExpr->x.pSelect->pEList;
62145        if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
62146          keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
62147              pEList->a[0].pExpr);
62148        }
62149      }else if( pExpr->x.pList!=0 ){
62150        /* Case 2:     expr IN (exprlist)
62151        **
62152        ** For each expression, build an index key from the evaluation and
62153        ** store it in the temporary table. If <expr> is a column, then use
62154        ** that columns affinity when building index keys. If <expr> is not
62155        ** a column, use numeric affinity.
62156        */
62157        int i;
62158        ExprList *pList = pExpr->x.pList;
62159        struct ExprList_item *pItem;
62160        int r1, r2, r3;
62161
62162        if( !affinity ){
62163          affinity = SQLITE_AFF_NONE;
62164        }
62165        keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
62166
62167        /* Loop through each expression in <exprlist>. */
62168        r1 = sqlite3GetTempReg(pParse);
62169        r2 = sqlite3GetTempReg(pParse);
62170        sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
62171        for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
62172          Expr *pE2 = pItem->pExpr;
62173          int iValToIns;
62174
62175          /* If the expression is not constant then we will need to
62176          ** disable the test that was generated above that makes sure
62177          ** this code only executes once.  Because for a non-constant
62178          ** expression we need to rerun this code each time.
62179          */
62180          if( testAddr && !sqlite3ExprIsConstant(pE2) ){
62181            sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
62182            testAddr = 0;
62183          }
62184
62185          /* Evaluate the expression and insert it into the temp table */
62186          if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
62187            sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
62188          }else{
62189            r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
62190            if( isRowid ){
62191              sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
62192                                sqlite3VdbeCurrentAddr(v)+2);
62193              sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
62194            }else{
62195              sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
62196              sqlite3ExprCacheAffinityChange(pParse, r3, 1);
62197              sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
62198            }
62199          }
62200        }
62201        sqlite3ReleaseTempReg(pParse, r1);
62202        sqlite3ReleaseTempReg(pParse, r2);
62203      }
62204      if( !isRowid ){
62205        sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
62206      }
62207      break;
62208    }
62209
62210    case TK_EXISTS:
62211    case TK_SELECT:
62212    default: {
62213      /* If this has to be a scalar SELECT.  Generate code to put the
62214      ** value of this select in a memory cell and record the number
62215      ** of the memory cell in iColumn.  If this is an EXISTS, write
62216      ** an integer 0 (not exists) or 1 (exists) into a memory cell
62217      ** and record that memory cell in iColumn.
62218      */
62219      static const Token one = { "1", 1 };  /* Token for literal value 1 */
62220      Select *pSel;                         /* SELECT statement to encode */
62221      SelectDest dest;                      /* How to deal with SELECt result */
62222
62223      testcase( pExpr->op==TK_EXISTS );
62224      testcase( pExpr->op==TK_SELECT );
62225      assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
62226
62227      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
62228      pSel = pExpr->x.pSelect;
62229      sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
62230      if( pExpr->op==TK_SELECT ){
62231        dest.eDest = SRT_Mem;
62232        sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
62233        VdbeComment((v, "Init subquery result"));
62234      }else{
62235        dest.eDest = SRT_Exists;
62236        sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
62237        VdbeComment((v, "Init EXISTS result"));
62238      }
62239      sqlite3ExprDelete(pParse->db, pSel->pLimit);
62240      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
62241      if( sqlite3Select(pParse, pSel, &dest) ){
62242        return 0;
62243      }
62244      rReg = dest.iParm;
62245      ExprSetIrreducible(pExpr);
62246      break;
62247    }
62248  }
62249
62250  if( testAddr ){
62251    sqlite3VdbeJumpHere(v, testAddr-1);
62252  }
62253  sqlite3ExprCachePop(pParse, 1);
62254
62255  return rReg;
62256}
62257#endif /* SQLITE_OMIT_SUBQUERY */
62258
62259#ifndef SQLITE_OMIT_SUBQUERY
62260/*
62261** Generate code for an IN expression.
62262**
62263**      x IN (SELECT ...)
62264**      x IN (value, value, ...)
62265**
62266** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
62267** is an array of zero or more values.  The expression is true if the LHS is
62268** contained within the RHS.  The value of the expression is unknown (NULL)
62269** if the LHS is NULL or if the LHS is not contained within the RHS and the
62270** RHS contains one or more NULL values.
62271**
62272** This routine generates code will jump to destIfFalse if the LHS is not
62273** contained within the RHS.  If due to NULLs we cannot determine if the LHS
62274** is contained in the RHS then jump to destIfNull.  If the LHS is contained
62275** within the RHS then fall through.
62276*/
62277static void sqlite3ExprCodeIN(
62278  Parse *pParse,        /* Parsing and code generating context */
62279  Expr *pExpr,          /* The IN expression */
62280  int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
62281  int destIfNull        /* Jump here if the results are unknown due to NULLs */
62282){
62283  int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
62284  char affinity;        /* Comparison affinity to use */
62285  int eType;            /* Type of the RHS */
62286  int r1;               /* Temporary use register */
62287  Vdbe *v;              /* Statement under construction */
62288
62289  /* Compute the RHS.   After this step, the table with cursor
62290  ** pExpr->iTable will contains the values that make up the RHS.
62291  */
62292  v = pParse->pVdbe;
62293  assert( v!=0 );       /* OOM detected prior to this routine */
62294  VdbeNoopComment((v, "begin IN expr"));
62295  eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
62296
62297  /* Figure out the affinity to use to create a key from the results
62298  ** of the expression. affinityStr stores a static string suitable for
62299  ** P4 of OP_MakeRecord.
62300  */
62301  affinity = comparisonAffinity(pExpr);
62302
62303  /* Code the LHS, the <expr> from "<expr> IN (...)".
62304  */
62305  sqlite3ExprCachePush(pParse);
62306  r1 = sqlite3GetTempReg(pParse);
62307  sqlite3ExprCode(pParse, pExpr->pLeft, r1);
62308  sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
62309
62310
62311  if( eType==IN_INDEX_ROWID ){
62312    /* In this case, the RHS is the ROWID of table b-tree
62313    */
62314    sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
62315    sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
62316  }else{
62317    /* In this case, the RHS is an index b-tree.
62318    */
62319    sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
62320
62321    /* If the set membership test fails, then the result of the
62322    ** "x IN (...)" expression must be either 0 or NULL. If the set
62323    ** contains no NULL values, then the result is 0. If the set
62324    ** contains one or more NULL values, then the result of the
62325    ** expression is also NULL.
62326    */
62327    if( rRhsHasNull==0 || destIfFalse==destIfNull ){
62328      /* This branch runs if it is known at compile time that the RHS
62329      ** cannot contain NULL values. This happens as the result
62330      ** of a "NOT NULL" constraint in the database schema.
62331      **
62332      ** Also run this branch if NULL is equivalent to FALSE
62333      ** for this particular IN operator.
62334      */
62335      sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
62336
62337    }else{
62338      /* In this branch, the RHS of the IN might contain a NULL and
62339      ** the presence of a NULL on the RHS makes a difference in the
62340      ** outcome.
62341      */
62342      int j1, j2, j3;
62343
62344      /* First check to see if the LHS is contained in the RHS.  If so,
62345      ** then the presence of NULLs in the RHS does not matter, so jump
62346      ** over all of the code that follows.
62347      */
62348      j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
62349
62350      /* Here we begin generating code that runs if the LHS is not
62351      ** contained within the RHS.  Generate additional code that
62352      ** tests the RHS for NULLs.  If the RHS contains a NULL then
62353      ** jump to destIfNull.  If there are no NULLs in the RHS then
62354      ** jump to destIfFalse.
62355      */
62356      j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
62357      j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
62358      sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
62359      sqlite3VdbeJumpHere(v, j3);
62360      sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
62361      sqlite3VdbeJumpHere(v, j2);
62362
62363      /* Jump to the appropriate target depending on whether or not
62364      ** the RHS contains a NULL
62365      */
62366      sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
62367      sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
62368
62369      /* The OP_Found at the top of this branch jumps here when true,
62370      ** causing the overall IN expression evaluation to fall through.
62371      */
62372      sqlite3VdbeJumpHere(v, j1);
62373    }
62374  }
62375  sqlite3ReleaseTempReg(pParse, r1);
62376  sqlite3ExprCachePop(pParse, 1);
62377  VdbeComment((v, "end IN expr"));
62378}
62379#endif /* SQLITE_OMIT_SUBQUERY */
62380
62381/*
62382** Duplicate an 8-byte value
62383*/
62384static char *dup8bytes(Vdbe *v, const char *in){
62385  char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
62386  if( out ){
62387    memcpy(out, in, 8);
62388  }
62389  return out;
62390}
62391
62392/*
62393** Generate an instruction that will put the floating point
62394** value described by z[0..n-1] into register iMem.
62395**
62396** The z[] string will probably not be zero-terminated.  But the
62397** z[n] character is guaranteed to be something that does not look
62398** like the continuation of the number.
62399*/
62400static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
62401  if( ALWAYS(z!=0) ){
62402    double value;
62403    char *zV;
62404    sqlite3AtoF(z, &value);
62405    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
62406    if( negateFlag ) value = -value;
62407    zV = dup8bytes(v, (char*)&value);
62408    sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
62409  }
62410}
62411
62412
62413/*
62414** Generate an instruction that will put the integer describe by
62415** text z[0..n-1] into register iMem.
62416**
62417** The z[] string will probably not be zero-terminated.  But the
62418** z[n] character is guaranteed to be something that does not look
62419** like the continuation of the number.
62420*/
62421static void codeInteger(Vdbe *v, Expr *pExpr, int negFlag, int iMem){
62422  if( pExpr->flags & EP_IntValue ){
62423    int i = pExpr->u.iValue;
62424    if( negFlag ) i = -i;
62425    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
62426  }else{
62427    const char *z = pExpr->u.zToken;
62428    assert( z!=0 );
62429    if( sqlite3FitsIn64Bits(z, negFlag) ){
62430      i64 value;
62431      char *zV;
62432      sqlite3Atoi64(z, &value);
62433      if( negFlag ) value = -value;
62434      zV = dup8bytes(v, (char*)&value);
62435      sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
62436    }else{
62437      codeReal(v, z, negFlag, iMem);
62438    }
62439  }
62440}
62441
62442/*
62443** Clear a cache entry.
62444*/
62445static void cacheEntryClear(Parse *pParse, struct yColCache *p){
62446  if( p->tempReg ){
62447    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
62448      pParse->aTempReg[pParse->nTempReg++] = p->iReg;
62449    }
62450    p->tempReg = 0;
62451  }
62452}
62453
62454
62455/*
62456** Record in the column cache that a particular column from a
62457** particular table is stored in a particular register.
62458*/
62459SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
62460  int i;
62461  int minLru;
62462  int idxLru;
62463  struct yColCache *p;
62464
62465  assert( iReg>0 );  /* Register numbers are always positive */
62466  assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
62467
62468  /* The SQLITE_ColumnCache flag disables the column cache.  This is used
62469  ** for testing only - to verify that SQLite always gets the same answer
62470  ** with and without the column cache.
62471  */
62472  if( pParse->db->flags & SQLITE_ColumnCache ) return;
62473
62474  /* First replace any existing entry.
62475  **
62476  ** Actually, the way the column cache is currently used, we are guaranteed
62477  ** that the object will never already be in cache.  Verify this guarantee.
62478  */
62479#ifndef NDEBUG
62480  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62481#if 0 /* This code wold remove the entry from the cache if it existed */
62482    if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
62483      cacheEntryClear(pParse, p);
62484      p->iLevel = pParse->iCacheLevel;
62485      p->iReg = iReg;
62486      p->lru = pParse->iCacheCnt++;
62487      return;
62488    }
62489#endif
62490    assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
62491  }
62492#endif
62493
62494  /* Find an empty slot and replace it */
62495  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62496    if( p->iReg==0 ){
62497      p->iLevel = pParse->iCacheLevel;
62498      p->iTable = iTab;
62499      p->iColumn = iCol;
62500      p->iReg = iReg;
62501      p->tempReg = 0;
62502      p->lru = pParse->iCacheCnt++;
62503      return;
62504    }
62505  }
62506
62507  /* Replace the last recently used */
62508  minLru = 0x7fffffff;
62509  idxLru = -1;
62510  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62511    if( p->lru<minLru ){
62512      idxLru = i;
62513      minLru = p->lru;
62514    }
62515  }
62516  if( ALWAYS(idxLru>=0) ){
62517    p = &pParse->aColCache[idxLru];
62518    p->iLevel = pParse->iCacheLevel;
62519    p->iTable = iTab;
62520    p->iColumn = iCol;
62521    p->iReg = iReg;
62522    p->tempReg = 0;
62523    p->lru = pParse->iCacheCnt++;
62524    return;
62525  }
62526}
62527
62528/*
62529** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
62530** Purge the range of registers from the column cache.
62531*/
62532SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
62533  int i;
62534  int iLast = iReg + nReg - 1;
62535  struct yColCache *p;
62536  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62537    int r = p->iReg;
62538    if( r>=iReg && r<=iLast ){
62539      cacheEntryClear(pParse, p);
62540      p->iReg = 0;
62541    }
62542  }
62543}
62544
62545/*
62546** Remember the current column cache context.  Any new entries added
62547** added to the column cache after this call are removed when the
62548** corresponding pop occurs.
62549*/
62550SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
62551  pParse->iCacheLevel++;
62552}
62553
62554/*
62555** Remove from the column cache any entries that were added since the
62556** the previous N Push operations.  In other words, restore the cache
62557** to the state it was in N Pushes ago.
62558*/
62559SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
62560  int i;
62561  struct yColCache *p;
62562  assert( N>0 );
62563  assert( pParse->iCacheLevel>=N );
62564  pParse->iCacheLevel -= N;
62565  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62566    if( p->iReg && p->iLevel>pParse->iCacheLevel ){
62567      cacheEntryClear(pParse, p);
62568      p->iReg = 0;
62569    }
62570  }
62571}
62572
62573/*
62574** When a cached column is reused, make sure that its register is
62575** no longer available as a temp register.  ticket #3879:  that same
62576** register might be in the cache in multiple places, so be sure to
62577** get them all.
62578*/
62579static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
62580  int i;
62581  struct yColCache *p;
62582  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62583    if( p->iReg==iReg ){
62584      p->tempReg = 0;
62585    }
62586  }
62587}
62588
62589/*
62590** Generate code that will extract the iColumn-th column from
62591** table pTab and store the column value in a register.  An effort
62592** is made to store the column value in register iReg, but this is
62593** not guaranteed.  The location of the column value is returned.
62594**
62595** There must be an open cursor to pTab in iTable when this routine
62596** is called.  If iColumn<0 then code is generated that extracts the rowid.
62597*/
62598SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
62599  Parse *pParse,   /* Parsing and code generating context */
62600  Table *pTab,     /* Description of the table we are reading from */
62601  int iColumn,     /* Index of the table column */
62602  int iTable,      /* The cursor pointing to the table */
62603  int iReg         /* Store results here */
62604){
62605  Vdbe *v = pParse->pVdbe;
62606  int i;
62607  struct yColCache *p;
62608
62609  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62610    if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
62611      p->lru = pParse->iCacheCnt++;
62612      sqlite3ExprCachePinRegister(pParse, p->iReg);
62613      return p->iReg;
62614    }
62615  }
62616  assert( v!=0 );
62617  if( iColumn<0 ){
62618    sqlite3VdbeAddOp2(v, OP_Rowid, iTable, iReg);
62619  }else if( ALWAYS(pTab!=0) ){
62620    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
62621    sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
62622    sqlite3ColumnDefault(v, pTab, iColumn, iReg);
62623  }
62624  sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
62625  return iReg;
62626}
62627
62628/*
62629** Clear all column cache entries.
62630*/
62631SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
62632  int i;
62633  struct yColCache *p;
62634
62635  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62636    if( p->iReg ){
62637      cacheEntryClear(pParse, p);
62638      p->iReg = 0;
62639    }
62640  }
62641}
62642
62643/*
62644** Record the fact that an affinity change has occurred on iCount
62645** registers starting with iStart.
62646*/
62647SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
62648  sqlite3ExprCacheRemove(pParse, iStart, iCount);
62649}
62650
62651/*
62652** Generate code to move content from registers iFrom...iFrom+nReg-1
62653** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
62654*/
62655SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
62656  int i;
62657  struct yColCache *p;
62658  if( NEVER(iFrom==iTo) ) return;
62659  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
62660  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62661    int x = p->iReg;
62662    if( x>=iFrom && x<iFrom+nReg ){
62663      p->iReg += iTo-iFrom;
62664    }
62665  }
62666}
62667
62668/*
62669** Generate code to copy content from registers iFrom...iFrom+nReg-1
62670** over to iTo..iTo+nReg-1.
62671*/
62672SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
62673  int i;
62674  if( NEVER(iFrom==iTo) ) return;
62675  for(i=0; i<nReg; i++){
62676    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
62677  }
62678}
62679
62680#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
62681/*
62682** Return true if any register in the range iFrom..iTo (inclusive)
62683** is used as part of the column cache.
62684**
62685** This routine is used within assert() and testcase() macros only
62686** and does not appear in a normal build.
62687*/
62688static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
62689  int i;
62690  struct yColCache *p;
62691  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62692    int r = p->iReg;
62693    if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
62694  }
62695  return 0;
62696}
62697#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
62698
62699/*
62700** If the last instruction coded is an ephemeral copy of any of
62701** the registers in the nReg registers beginning with iReg, then
62702** convert the last instruction from OP_SCopy to OP_Copy.
62703*/
62704SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
62705  VdbeOp *pOp;
62706  Vdbe *v;
62707
62708  assert( pParse->db->mallocFailed==0 );
62709  v = pParse->pVdbe;
62710  assert( v!=0 );
62711  pOp = sqlite3VdbeGetOp(v, -1);
62712  assert( pOp!=0 );
62713  if( pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
62714    pOp->opcode = OP_Copy;
62715  }
62716}
62717
62718/*
62719** Generate code to store the value of the iAlias-th alias in register
62720** target.  The first time this is called, pExpr is evaluated to compute
62721** the value of the alias.  The value is stored in an auxiliary register
62722** and the number of that register is returned.  On subsequent calls,
62723** the register number is returned without generating any code.
62724**
62725** Note that in order for this to work, code must be generated in the
62726** same order that it is executed.
62727**
62728** Aliases are numbered starting with 1.  So iAlias is in the range
62729** of 1 to pParse->nAlias inclusive.
62730**
62731** pParse->aAlias[iAlias-1] records the register number where the value
62732** of the iAlias-th alias is stored.  If zero, that means that the
62733** alias has not yet been computed.
62734*/
62735static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
62736#if 0
62737  sqlite3 *db = pParse->db;
62738  int iReg;
62739  if( pParse->nAliasAlloc<pParse->nAlias ){
62740    pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
62741                                 sizeof(pParse->aAlias[0])*pParse->nAlias );
62742    testcase( db->mallocFailed && pParse->nAliasAlloc>0 );
62743    if( db->mallocFailed ) return 0;
62744    memset(&pParse->aAlias[pParse->nAliasAlloc], 0,
62745           (pParse->nAlias-pParse->nAliasAlloc)*sizeof(pParse->aAlias[0]));
62746    pParse->nAliasAlloc = pParse->nAlias;
62747  }
62748  assert( iAlias>0 && iAlias<=pParse->nAlias );
62749  iReg = pParse->aAlias[iAlias-1];
62750  if( iReg==0 ){
62751    if( pParse->iCacheLevel>0 ){
62752      iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
62753    }else{
62754      iReg = ++pParse->nMem;
62755      sqlite3ExprCode(pParse, pExpr, iReg);
62756      pParse->aAlias[iAlias-1] = iReg;
62757    }
62758  }
62759  return iReg;
62760#else
62761  UNUSED_PARAMETER(iAlias);
62762  return sqlite3ExprCodeTarget(pParse, pExpr, target);
62763#endif
62764}
62765
62766/*
62767** Generate code into the current Vdbe to evaluate the given
62768** expression.  Attempt to store the results in register "target".
62769** Return the register where results are stored.
62770**
62771** With this routine, there is no guarantee that results will
62772** be stored in target.  The result might be stored in some other
62773** register if it is convenient to do so.  The calling function
62774** must check the return code and move the results to the desired
62775** register.
62776*/
62777SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
62778  Vdbe *v = pParse->pVdbe;  /* The VM under construction */
62779  int op;                   /* The opcode being coded */
62780  int inReg = target;       /* Results stored in register inReg */
62781  int regFree1 = 0;         /* If non-zero free this temporary register */
62782  int regFree2 = 0;         /* If non-zero free this temporary register */
62783  int r1, r2, r3, r4;       /* Various register numbers */
62784  sqlite3 *db = pParse->db; /* The database connection */
62785
62786  assert( target>0 && target<=pParse->nMem );
62787  if( v==0 ){
62788    assert( pParse->db->mallocFailed );
62789    return 0;
62790  }
62791
62792  if( pExpr==0 ){
62793    op = TK_NULL;
62794  }else{
62795    op = pExpr->op;
62796  }
62797  switch( op ){
62798    case TK_AGG_COLUMN: {
62799      AggInfo *pAggInfo = pExpr->pAggInfo;
62800      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
62801      if( !pAggInfo->directMode ){
62802        assert( pCol->iMem>0 );
62803        inReg = pCol->iMem;
62804        break;
62805      }else if( pAggInfo->useSortingIdx ){
62806        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
62807                              pCol->iSorterColumn, target);
62808        break;
62809      }
62810      /* Otherwise, fall thru into the TK_COLUMN case */
62811    }
62812    case TK_COLUMN: {
62813      if( pExpr->iTable<0 ){
62814        /* This only happens when coding check constraints */
62815        assert( pParse->ckBase>0 );
62816        inReg = pExpr->iColumn + pParse->ckBase;
62817      }else{
62818        inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
62819                                 pExpr->iColumn, pExpr->iTable, target);
62820      }
62821      break;
62822    }
62823    case TK_INTEGER: {
62824      codeInteger(v, pExpr, 0, target);
62825      break;
62826    }
62827    case TK_FLOAT: {
62828      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62829      codeReal(v, pExpr->u.zToken, 0, target);
62830      break;
62831    }
62832    case TK_STRING: {
62833      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62834      sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
62835      break;
62836    }
62837    case TK_NULL: {
62838      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
62839      break;
62840    }
62841#ifndef SQLITE_OMIT_BLOB_LITERAL
62842    case TK_BLOB: {
62843      int n;
62844      const char *z;
62845      char *zBlob;
62846      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62847      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
62848      assert( pExpr->u.zToken[1]=='\'' );
62849      z = &pExpr->u.zToken[2];
62850      n = sqlite3Strlen30(z) - 1;
62851      assert( z[n]=='\'' );
62852      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
62853      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
62854      break;
62855    }
62856#endif
62857    case TK_VARIABLE: {
62858      VdbeOp *pOp;
62859      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62860      assert( pExpr->u.zToken!=0 );
62861      assert( pExpr->u.zToken[0]!=0 );
62862      if( pExpr->u.zToken[1]==0
62863         && (pOp = sqlite3VdbeGetOp(v, -1))->opcode==OP_Variable
62864         && pOp->p1+pOp->p3==pExpr->iColumn
62865         && pOp->p2+pOp->p3==target
62866         && pOp->p4.z==0
62867      ){
62868        /* If the previous instruction was a copy of the previous unnamed
62869        ** parameter into the previous register, then simply increment the
62870        ** repeat count on the prior instruction rather than making a new
62871        ** instruction.
62872        */
62873        pOp->p3++;
62874      }else{
62875        sqlite3VdbeAddOp3(v, OP_Variable, pExpr->iColumn, target, 1);
62876        if( pExpr->u.zToken[1]!=0 ){
62877          sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, 0);
62878        }
62879      }
62880      break;
62881    }
62882    case TK_REGISTER: {
62883      inReg = pExpr->iTable;
62884      break;
62885    }
62886    case TK_AS: {
62887      inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
62888      break;
62889    }
62890#ifndef SQLITE_OMIT_CAST
62891    case TK_CAST: {
62892      /* Expressions of the form:   CAST(pLeft AS token) */
62893      int aff, to_op;
62894      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
62895      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62896      aff = sqlite3AffinityType(pExpr->u.zToken);
62897      to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
62898      assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
62899      assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
62900      assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
62901      assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
62902      assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
62903      testcase( to_op==OP_ToText );
62904      testcase( to_op==OP_ToBlob );
62905      testcase( to_op==OP_ToNumeric );
62906      testcase( to_op==OP_ToInt );
62907      testcase( to_op==OP_ToReal );
62908      if( inReg!=target ){
62909        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
62910        inReg = target;
62911      }
62912      sqlite3VdbeAddOp1(v, to_op, inReg);
62913      testcase( usedAsColumnCache(pParse, inReg, inReg) );
62914      sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
62915      break;
62916    }
62917#endif /* SQLITE_OMIT_CAST */
62918    case TK_LT:
62919    case TK_LE:
62920    case TK_GT:
62921    case TK_GE:
62922    case TK_NE:
62923    case TK_EQ: {
62924      assert( TK_LT==OP_Lt );
62925      assert( TK_LE==OP_Le );
62926      assert( TK_GT==OP_Gt );
62927      assert( TK_GE==OP_Ge );
62928      assert( TK_EQ==OP_Eq );
62929      assert( TK_NE==OP_Ne );
62930      testcase( op==TK_LT );
62931      testcase( op==TK_LE );
62932      testcase( op==TK_GT );
62933      testcase( op==TK_GE );
62934      testcase( op==TK_EQ );
62935      testcase( op==TK_NE );
62936      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
62937      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
62938      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
62939                  r1, r2, inReg, SQLITE_STOREP2);
62940      testcase( regFree1==0 );
62941      testcase( regFree2==0 );
62942      break;
62943    }
62944    case TK_IS:
62945    case TK_ISNOT: {
62946      testcase( op==TK_IS );
62947      testcase( op==TK_ISNOT );
62948      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
62949      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
62950      op = (op==TK_IS) ? TK_EQ : TK_NE;
62951      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
62952                  r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
62953      testcase( regFree1==0 );
62954      testcase( regFree2==0 );
62955      break;
62956    }
62957    case TK_AND:
62958    case TK_OR:
62959    case TK_PLUS:
62960    case TK_STAR:
62961    case TK_MINUS:
62962    case TK_REM:
62963    case TK_BITAND:
62964    case TK_BITOR:
62965    case TK_SLASH:
62966    case TK_LSHIFT:
62967    case TK_RSHIFT:
62968    case TK_CONCAT: {
62969      assert( TK_AND==OP_And );
62970      assert( TK_OR==OP_Or );
62971      assert( TK_PLUS==OP_Add );
62972      assert( TK_MINUS==OP_Subtract );
62973      assert( TK_REM==OP_Remainder );
62974      assert( TK_BITAND==OP_BitAnd );
62975      assert( TK_BITOR==OP_BitOr );
62976      assert( TK_SLASH==OP_Divide );
62977      assert( TK_LSHIFT==OP_ShiftLeft );
62978      assert( TK_RSHIFT==OP_ShiftRight );
62979      assert( TK_CONCAT==OP_Concat );
62980      testcase( op==TK_AND );
62981      testcase( op==TK_OR );
62982      testcase( op==TK_PLUS );
62983      testcase( op==TK_MINUS );
62984      testcase( op==TK_REM );
62985      testcase( op==TK_BITAND );
62986      testcase( op==TK_BITOR );
62987      testcase( op==TK_SLASH );
62988      testcase( op==TK_LSHIFT );
62989      testcase( op==TK_RSHIFT );
62990      testcase( op==TK_CONCAT );
62991      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
62992      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
62993      sqlite3VdbeAddOp3(v, op, r2, r1, target);
62994      testcase( regFree1==0 );
62995      testcase( regFree2==0 );
62996      break;
62997    }
62998    case TK_UMINUS: {
62999      Expr *pLeft = pExpr->pLeft;
63000      assert( pLeft );
63001      if( pLeft->op==TK_FLOAT ){
63002        assert( !ExprHasProperty(pExpr, EP_IntValue) );
63003        codeReal(v, pLeft->u.zToken, 1, target);
63004      }else if( pLeft->op==TK_INTEGER ){
63005        codeInteger(v, pLeft, 1, target);
63006      }else{
63007        regFree1 = r1 = sqlite3GetTempReg(pParse);
63008        sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
63009        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
63010        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
63011        testcase( regFree2==0 );
63012      }
63013      inReg = target;
63014      break;
63015    }
63016    case TK_BITNOT:
63017    case TK_NOT: {
63018      assert( TK_BITNOT==OP_BitNot );
63019      assert( TK_NOT==OP_Not );
63020      testcase( op==TK_BITNOT );
63021      testcase( op==TK_NOT );
63022      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63023      testcase( regFree1==0 );
63024      inReg = target;
63025      sqlite3VdbeAddOp2(v, op, r1, inReg);
63026      break;
63027    }
63028    case TK_ISNULL:
63029    case TK_NOTNULL: {
63030      int addr;
63031      assert( TK_ISNULL==OP_IsNull );
63032      assert( TK_NOTNULL==OP_NotNull );
63033      testcase( op==TK_ISNULL );
63034      testcase( op==TK_NOTNULL );
63035      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
63036      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63037      testcase( regFree1==0 );
63038      addr = sqlite3VdbeAddOp1(v, op, r1);
63039      sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
63040      sqlite3VdbeJumpHere(v, addr);
63041      break;
63042    }
63043    case TK_AGG_FUNCTION: {
63044      AggInfo *pInfo = pExpr->pAggInfo;
63045      if( pInfo==0 ){
63046        assert( !ExprHasProperty(pExpr, EP_IntValue) );
63047        sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
63048      }else{
63049        inReg = pInfo->aFunc[pExpr->iAgg].iMem;
63050      }
63051      break;
63052    }
63053    case TK_CONST_FUNC:
63054    case TK_FUNCTION: {
63055      ExprList *pFarg;       /* List of function arguments */
63056      int nFarg;             /* Number of function arguments */
63057      FuncDef *pDef;         /* The function definition object */
63058      int nId;               /* Length of the function name in bytes */
63059      const char *zId;       /* The function name */
63060      int constMask = 0;     /* Mask of function arguments that are constant */
63061      int i;                 /* Loop counter */
63062      u8 enc = ENC(db);      /* The text encoding used by this database */
63063      CollSeq *pColl = 0;    /* A collating sequence */
63064
63065      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
63066      testcase( op==TK_CONST_FUNC );
63067      testcase( op==TK_FUNCTION );
63068      if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
63069        pFarg = 0;
63070      }else{
63071        pFarg = pExpr->x.pList;
63072      }
63073      nFarg = pFarg ? pFarg->nExpr : 0;
63074      assert( !ExprHasProperty(pExpr, EP_IntValue) );
63075      zId = pExpr->u.zToken;
63076      nId = sqlite3Strlen30(zId);
63077      pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
63078      if( pDef==0 ){
63079        sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
63080        break;
63081      }
63082
63083      /* Attempt a direct implementation of the built-in COALESCE() and
63084      ** IFNULL() functions.  This avoids unnecessary evalation of
63085      ** arguments past the first non-NULL argument.
63086      */
63087      if( pDef->flags & SQLITE_FUNC_COALESCE ){
63088        int endCoalesce = sqlite3VdbeMakeLabel(v);
63089        assert( nFarg>=2 );
63090        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
63091        for(i=1; i<nFarg; i++){
63092          sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
63093          sqlite3ExprCacheRemove(pParse, target, 1);
63094          sqlite3ExprCachePush(pParse);
63095          sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
63096          sqlite3ExprCachePop(pParse, 1);
63097        }
63098        sqlite3VdbeResolveLabel(v, endCoalesce);
63099        break;
63100      }
63101
63102
63103      if( pFarg ){
63104        r1 = sqlite3GetTempRange(pParse, nFarg);
63105        sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
63106        sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
63107        sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
63108      }else{
63109        r1 = 0;
63110      }
63111#ifndef SQLITE_OMIT_VIRTUALTABLE
63112      /* Possibly overload the function if the first argument is
63113      ** a virtual table column.
63114      **
63115      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
63116      ** second argument, not the first, as the argument to test to
63117      ** see if it is a column in a virtual table.  This is done because
63118      ** the left operand of infix functions (the operand we want to
63119      ** control overloading) ends up as the second argument to the
63120      ** function.  The expression "A glob B" is equivalent to
63121      ** "glob(B,A).  We want to use the A in "A glob B" to test
63122      ** for function overloading.  But we use the B term in "glob(B,A)".
63123      */
63124      if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
63125        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
63126      }else if( nFarg>0 ){
63127        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
63128      }
63129#endif
63130      for(i=0; i<nFarg; i++){
63131        if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
63132          constMask |= (1<<i);
63133        }
63134        if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
63135          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
63136        }
63137      }
63138      if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
63139        if( !pColl ) pColl = db->pDfltColl;
63140        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
63141      }
63142      sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
63143                        (char*)pDef, P4_FUNCDEF);
63144      sqlite3VdbeChangeP5(v, (u8)nFarg);
63145      if( nFarg ){
63146        sqlite3ReleaseTempRange(pParse, r1, nFarg);
63147      }
63148      break;
63149    }
63150#ifndef SQLITE_OMIT_SUBQUERY
63151    case TK_EXISTS:
63152    case TK_SELECT: {
63153      testcase( op==TK_EXISTS );
63154      testcase( op==TK_SELECT );
63155      inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
63156      break;
63157    }
63158    case TK_IN: {
63159      int destIfFalse = sqlite3VdbeMakeLabel(v);
63160      int destIfNull = sqlite3VdbeMakeLabel(v);
63161      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
63162      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
63163      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
63164      sqlite3VdbeResolveLabel(v, destIfFalse);
63165      sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
63166      sqlite3VdbeResolveLabel(v, destIfNull);
63167      break;
63168    }
63169#endif /* SQLITE_OMIT_SUBQUERY */
63170
63171
63172    /*
63173    **    x BETWEEN y AND z
63174    **
63175    ** This is equivalent to
63176    **
63177    **    x>=y AND x<=z
63178    **
63179    ** X is stored in pExpr->pLeft.
63180    ** Y is stored in pExpr->pList->a[0].pExpr.
63181    ** Z is stored in pExpr->pList->a[1].pExpr.
63182    */
63183    case TK_BETWEEN: {
63184      Expr *pLeft = pExpr->pLeft;
63185      struct ExprList_item *pLItem = pExpr->x.pList->a;
63186      Expr *pRight = pLItem->pExpr;
63187
63188      r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
63189      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
63190      testcase( regFree1==0 );
63191      testcase( regFree2==0 );
63192      r3 = sqlite3GetTempReg(pParse);
63193      r4 = sqlite3GetTempReg(pParse);
63194      codeCompare(pParse, pLeft, pRight, OP_Ge,
63195                  r1, r2, r3, SQLITE_STOREP2);
63196      pLItem++;
63197      pRight = pLItem->pExpr;
63198      sqlite3ReleaseTempReg(pParse, regFree2);
63199      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
63200      testcase( regFree2==0 );
63201      codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
63202      sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
63203      sqlite3ReleaseTempReg(pParse, r3);
63204      sqlite3ReleaseTempReg(pParse, r4);
63205      break;
63206    }
63207    case TK_UPLUS: {
63208      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
63209      break;
63210    }
63211
63212    case TK_TRIGGER: {
63213      /* If the opcode is TK_TRIGGER, then the expression is a reference
63214      ** to a column in the new.* or old.* pseudo-tables available to
63215      ** trigger programs. In this case Expr.iTable is set to 1 for the
63216      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
63217      ** is set to the column of the pseudo-table to read, or to -1 to
63218      ** read the rowid field.
63219      **
63220      ** The expression is implemented using an OP_Param opcode. The p1
63221      ** parameter is set to 0 for an old.rowid reference, or to (i+1)
63222      ** to reference another column of the old.* pseudo-table, where
63223      ** i is the index of the column. For a new.rowid reference, p1 is
63224      ** set to (n+1), where n is the number of columns in each pseudo-table.
63225      ** For a reference to any other column in the new.* pseudo-table, p1
63226      ** is set to (n+2+i), where n and i are as defined previously. For
63227      ** example, if the table on which triggers are being fired is
63228      ** declared as:
63229      **
63230      **   CREATE TABLE t1(a, b);
63231      **
63232      ** Then p1 is interpreted as follows:
63233      **
63234      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
63235      **   p1==1   ->    old.a         p1==4   ->    new.a
63236      **   p1==2   ->    old.b         p1==5   ->    new.b
63237      */
63238      Table *pTab = pExpr->pTab;
63239      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
63240
63241      assert( pExpr->iTable==0 || pExpr->iTable==1 );
63242      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
63243      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
63244      assert( p1>=0 && p1<(pTab->nCol*2+2) );
63245
63246      sqlite3VdbeAddOp2(v, OP_Param, p1, target);
63247      VdbeComment((v, "%s.%s -> $%d",
63248        (pExpr->iTable ? "new" : "old"),
63249        (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
63250        target
63251      ));
63252
63253      /* If the column has REAL affinity, it may currently be stored as an
63254      ** integer. Use OP_RealAffinity to make sure it is really real.  */
63255      if( pExpr->iColumn>=0
63256       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
63257      ){
63258        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
63259      }
63260      break;
63261    }
63262
63263
63264    /*
63265    ** Form A:
63266    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
63267    **
63268    ** Form B:
63269    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
63270    **
63271    ** Form A is can be transformed into the equivalent form B as follows:
63272    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
63273    **        WHEN x=eN THEN rN ELSE y END
63274    **
63275    ** X (if it exists) is in pExpr->pLeft.
63276    ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
63277    ** ELSE clause and no other term matches, then the result of the
63278    ** exprssion is NULL.
63279    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
63280    **
63281    ** The result of the expression is the Ri for the first matching Ei,
63282    ** or if there is no matching Ei, the ELSE term Y, or if there is
63283    ** no ELSE term, NULL.
63284    */
63285    default: assert( op==TK_CASE ); {
63286      int endLabel;                     /* GOTO label for end of CASE stmt */
63287      int nextCase;                     /* GOTO label for next WHEN clause */
63288      int nExpr;                        /* 2x number of WHEN terms */
63289      int i;                            /* Loop counter */
63290      ExprList *pEList;                 /* List of WHEN terms */
63291      struct ExprList_item *aListelem;  /* Array of WHEN terms */
63292      Expr opCompare;                   /* The X==Ei expression */
63293      Expr cacheX;                      /* Cached expression X */
63294      Expr *pX;                         /* The X expression */
63295      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
63296      VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
63297
63298      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
63299      assert((pExpr->x.pList->nExpr % 2) == 0);
63300      assert(pExpr->x.pList->nExpr > 0);
63301      pEList = pExpr->x.pList;
63302      aListelem = pEList->a;
63303      nExpr = pEList->nExpr;
63304      endLabel = sqlite3VdbeMakeLabel(v);
63305      if( (pX = pExpr->pLeft)!=0 ){
63306        cacheX = *pX;
63307        testcase( pX->op==TK_COLUMN );
63308        testcase( pX->op==TK_REGISTER );
63309        cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
63310        testcase( regFree1==0 );
63311        cacheX.op = TK_REGISTER;
63312        opCompare.op = TK_EQ;
63313        opCompare.pLeft = &cacheX;
63314        pTest = &opCompare;
63315      }
63316      for(i=0; i<nExpr; i=i+2){
63317        sqlite3ExprCachePush(pParse);
63318        if( pX ){
63319          assert( pTest!=0 );
63320          opCompare.pRight = aListelem[i].pExpr;
63321        }else{
63322          pTest = aListelem[i].pExpr;
63323        }
63324        nextCase = sqlite3VdbeMakeLabel(v);
63325        testcase( pTest->op==TK_COLUMN );
63326        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
63327        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
63328        testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
63329        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
63330        sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
63331        sqlite3ExprCachePop(pParse, 1);
63332        sqlite3VdbeResolveLabel(v, nextCase);
63333      }
63334      if( pExpr->pRight ){
63335        sqlite3ExprCachePush(pParse);
63336        sqlite3ExprCode(pParse, pExpr->pRight, target);
63337        sqlite3ExprCachePop(pParse, 1);
63338      }else{
63339        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
63340      }
63341      assert( db->mallocFailed || pParse->nErr>0
63342           || pParse->iCacheLevel==iCacheLevel );
63343      sqlite3VdbeResolveLabel(v, endLabel);
63344      break;
63345    }
63346#ifndef SQLITE_OMIT_TRIGGER
63347    case TK_RAISE: {
63348      assert( pExpr->affinity==OE_Rollback
63349           || pExpr->affinity==OE_Abort
63350           || pExpr->affinity==OE_Fail
63351           || pExpr->affinity==OE_Ignore
63352      );
63353      if( !pParse->pTriggerTab ){
63354        sqlite3ErrorMsg(pParse,
63355                       "RAISE() may only be used within a trigger-program");
63356        return 0;
63357      }
63358      if( pExpr->affinity==OE_Abort ){
63359        sqlite3MayAbort(pParse);
63360      }
63361      assert( !ExprHasProperty(pExpr, EP_IntValue) );
63362      if( pExpr->affinity==OE_Ignore ){
63363        sqlite3VdbeAddOp4(
63364            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
63365      }else{
63366        sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
63367      }
63368
63369      break;
63370    }
63371#endif
63372  }
63373  sqlite3ReleaseTempReg(pParse, regFree1);
63374  sqlite3ReleaseTempReg(pParse, regFree2);
63375  return inReg;
63376}
63377
63378/*
63379** Generate code to evaluate an expression and store the results
63380** into a register.  Return the register number where the results
63381** are stored.
63382**
63383** If the register is a temporary register that can be deallocated,
63384** then write its number into *pReg.  If the result register is not
63385** a temporary, then set *pReg to zero.
63386*/
63387SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
63388  int r1 = sqlite3GetTempReg(pParse);
63389  int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
63390  if( r2==r1 ){
63391    *pReg = r1;
63392  }else{
63393    sqlite3ReleaseTempReg(pParse, r1);
63394    *pReg = 0;
63395  }
63396  return r2;
63397}
63398
63399/*
63400** Generate code that will evaluate expression pExpr and store the
63401** results in register target.  The results are guaranteed to appear
63402** in register target.
63403*/
63404SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
63405  int inReg;
63406
63407  assert( target>0 && target<=pParse->nMem );
63408  inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
63409  assert( pParse->pVdbe || pParse->db->mallocFailed );
63410  if( inReg!=target && pParse->pVdbe ){
63411    sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
63412  }
63413  return target;
63414}
63415
63416/*
63417** Generate code that evalutes the given expression and puts the result
63418** in register target.
63419**
63420** Also make a copy of the expression results into another "cache" register
63421** and modify the expression so that the next time it is evaluated,
63422** the result is a copy of the cache register.
63423**
63424** This routine is used for expressions that are used multiple
63425** times.  They are evaluated once and the results of the expression
63426** are reused.
63427*/
63428SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
63429  Vdbe *v = pParse->pVdbe;
63430  int inReg;
63431  inReg = sqlite3ExprCode(pParse, pExpr, target);
63432  assert( target>0 );
63433  /* This routine is called for terms to INSERT or UPDATE.  And the only
63434  ** other place where expressions can be converted into TK_REGISTER is
63435  ** in WHERE clause processing.  So as currently implemented, there is
63436  ** no way for a TK_REGISTER to exist here.  But it seems prudent to
63437  ** keep the ALWAYS() in case the conditions above change with future
63438  ** modifications or enhancements. */
63439  if( ALWAYS(pExpr->op!=TK_REGISTER) ){
63440    int iMem;
63441    iMem = ++pParse->nMem;
63442    sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
63443    pExpr->iTable = iMem;
63444    pExpr->op2 = pExpr->op;
63445    pExpr->op = TK_REGISTER;
63446  }
63447  return inReg;
63448}
63449
63450/*
63451** Return TRUE if pExpr is an constant expression that is appropriate
63452** for factoring out of a loop.  Appropriate expressions are:
63453**
63454**    *  Any expression that evaluates to two or more opcodes.
63455**
63456**    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
63457**       or OP_Variable that does not need to be placed in a
63458**       specific register.
63459**
63460** There is no point in factoring out single-instruction constant
63461** expressions that need to be placed in a particular register.
63462** We could factor them out, but then we would end up adding an
63463** OP_SCopy instruction to move the value into the correct register
63464** later.  We might as well just use the original instruction and
63465** avoid the OP_SCopy.
63466*/
63467static int isAppropriateForFactoring(Expr *p){
63468  if( !sqlite3ExprIsConstantNotJoin(p) ){
63469    return 0;  /* Only constant expressions are appropriate for factoring */
63470  }
63471  if( (p->flags & EP_FixedDest)==0 ){
63472    return 1;  /* Any constant without a fixed destination is appropriate */
63473  }
63474  while( p->op==TK_UPLUS ) p = p->pLeft;
63475  switch( p->op ){
63476#ifndef SQLITE_OMIT_BLOB_LITERAL
63477    case TK_BLOB:
63478#endif
63479    case TK_VARIABLE:
63480    case TK_INTEGER:
63481    case TK_FLOAT:
63482    case TK_NULL:
63483    case TK_STRING: {
63484      testcase( p->op==TK_BLOB );
63485      testcase( p->op==TK_VARIABLE );
63486      testcase( p->op==TK_INTEGER );
63487      testcase( p->op==TK_FLOAT );
63488      testcase( p->op==TK_NULL );
63489      testcase( p->op==TK_STRING );
63490      /* Single-instruction constants with a fixed destination are
63491      ** better done in-line.  If we factor them, they will just end
63492      ** up generating an OP_SCopy to move the value to the destination
63493      ** register. */
63494      return 0;
63495    }
63496    case TK_UMINUS: {
63497      if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
63498        return 0;
63499      }
63500      break;
63501    }
63502    default: {
63503      break;
63504    }
63505  }
63506  return 1;
63507}
63508
63509/*
63510** If pExpr is a constant expression that is appropriate for
63511** factoring out of a loop, then evaluate the expression
63512** into a register and convert the expression into a TK_REGISTER
63513** expression.
63514*/
63515static int evalConstExpr(Walker *pWalker, Expr *pExpr){
63516  Parse *pParse = pWalker->pParse;
63517  switch( pExpr->op ){
63518    case TK_IN:
63519    case TK_REGISTER: {
63520      return WRC_Prune;
63521    }
63522    case TK_FUNCTION:
63523    case TK_AGG_FUNCTION:
63524    case TK_CONST_FUNC: {
63525      /* The arguments to a function have a fixed destination.
63526      ** Mark them this way to avoid generated unneeded OP_SCopy
63527      ** instructions.
63528      */
63529      ExprList *pList = pExpr->x.pList;
63530      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
63531      if( pList ){
63532        int i = pList->nExpr;
63533        struct ExprList_item *pItem = pList->a;
63534        for(; i>0; i--, pItem++){
63535          if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
63536        }
63537      }
63538      break;
63539    }
63540  }
63541  if( isAppropriateForFactoring(pExpr) ){
63542    int r1 = ++pParse->nMem;
63543    int r2;
63544    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
63545    if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
63546    pExpr->op2 = pExpr->op;
63547    pExpr->op = TK_REGISTER;
63548    pExpr->iTable = r2;
63549    return WRC_Prune;
63550  }
63551  return WRC_Continue;
63552}
63553
63554/*
63555** Preevaluate constant subexpressions within pExpr and store the
63556** results in registers.  Modify pExpr so that the constant subexpresions
63557** are TK_REGISTER opcodes that refer to the precomputed values.
63558*/
63559SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
63560  Walker w;
63561  w.xExprCallback = evalConstExpr;
63562  w.xSelectCallback = 0;
63563  w.pParse = pParse;
63564  sqlite3WalkExpr(&w, pExpr);
63565}
63566
63567
63568/*
63569** Generate code that pushes the value of every element of the given
63570** expression list into a sequence of registers beginning at target.
63571**
63572** Return the number of elements evaluated.
63573*/
63574SQLITE_PRIVATE int sqlite3ExprCodeExprList(
63575  Parse *pParse,     /* Parsing context */
63576  ExprList *pList,   /* The expression list to be coded */
63577  int target,        /* Where to write results */
63578  int doHardCopy     /* Make a hard copy of every element */
63579){
63580  struct ExprList_item *pItem;
63581  int i, n;
63582  assert( pList!=0 );
63583  assert( target>0 );
63584  n = pList->nExpr;
63585  for(pItem=pList->a, i=0; i<n; i++, pItem++){
63586    if( pItem->iAlias ){
63587      int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
63588      Vdbe *v = sqlite3GetVdbe(pParse);
63589      if( iReg!=target+i ){
63590        sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
63591      }
63592    }else{
63593      sqlite3ExprCode(pParse, pItem->pExpr, target+i);
63594    }
63595    if( doHardCopy && !pParse->db->mallocFailed ){
63596      sqlite3ExprHardCopy(pParse, target, n);
63597    }
63598  }
63599  return n;
63600}
63601
63602/*
63603** Generate code for a BETWEEN operator.
63604**
63605**    x BETWEEN y AND z
63606**
63607** The above is equivalent to
63608**
63609**    x>=y AND x<=z
63610**
63611** Code it as such, taking care to do the common subexpression
63612** elementation of x.
63613*/
63614static void exprCodeBetween(
63615  Parse *pParse,    /* Parsing and code generating context */
63616  Expr *pExpr,      /* The BETWEEN expression */
63617  int dest,         /* Jump here if the jump is taken */
63618  int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
63619  int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
63620){
63621  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
63622  Expr compLeft;    /* The  x>=y  term */
63623  Expr compRight;   /* The  x<=z  term */
63624  Expr exprX;       /* The  x  subexpression */
63625  int regFree1 = 0; /* Temporary use register */
63626
63627  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
63628  exprX = *pExpr->pLeft;
63629  exprAnd.op = TK_AND;
63630  exprAnd.pLeft = &compLeft;
63631  exprAnd.pRight = &compRight;
63632  compLeft.op = TK_GE;
63633  compLeft.pLeft = &exprX;
63634  compLeft.pRight = pExpr->x.pList->a[0].pExpr;
63635  compRight.op = TK_LE;
63636  compRight.pLeft = &exprX;
63637  compRight.pRight = pExpr->x.pList->a[1].pExpr;
63638  exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
63639  exprX.op = TK_REGISTER;
63640  if( jumpIfTrue ){
63641    sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
63642  }else{
63643    sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
63644  }
63645  sqlite3ReleaseTempReg(pParse, regFree1);
63646
63647  /* Ensure adequate test coverage */
63648  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
63649  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
63650  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
63651  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
63652  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
63653  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
63654  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
63655  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
63656}
63657
63658/*
63659** Generate code for a boolean expression such that a jump is made
63660** to the label "dest" if the expression is true but execution
63661** continues straight thru if the expression is false.
63662**
63663** If the expression evaluates to NULL (neither true nor false), then
63664** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
63665**
63666** This code depends on the fact that certain token values (ex: TK_EQ)
63667** are the same as opcode values (ex: OP_Eq) that implement the corresponding
63668** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
63669** the make process cause these values to align.  Assert()s in the code
63670** below verify that the numbers are aligned correctly.
63671*/
63672SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
63673  Vdbe *v = pParse->pVdbe;
63674  int op = 0;
63675  int regFree1 = 0;
63676  int regFree2 = 0;
63677  int r1, r2;
63678
63679  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
63680  if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
63681  if( NEVER(pExpr==0) ) return;  /* No way this can happen */
63682  op = pExpr->op;
63683  switch( op ){
63684    case TK_AND: {
63685      int d2 = sqlite3VdbeMakeLabel(v);
63686      testcase( jumpIfNull==0 );
63687      sqlite3ExprCachePush(pParse);
63688      sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
63689      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
63690      sqlite3VdbeResolveLabel(v, d2);
63691      sqlite3ExprCachePop(pParse, 1);
63692      break;
63693    }
63694    case TK_OR: {
63695      testcase( jumpIfNull==0 );
63696      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
63697      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
63698      break;
63699    }
63700    case TK_NOT: {
63701      testcase( jumpIfNull==0 );
63702      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
63703      break;
63704    }
63705    case TK_LT:
63706    case TK_LE:
63707    case TK_GT:
63708    case TK_GE:
63709    case TK_NE:
63710    case TK_EQ: {
63711      assert( TK_LT==OP_Lt );
63712      assert( TK_LE==OP_Le );
63713      assert( TK_GT==OP_Gt );
63714      assert( TK_GE==OP_Ge );
63715      assert( TK_EQ==OP_Eq );
63716      assert( TK_NE==OP_Ne );
63717      testcase( op==TK_LT );
63718      testcase( op==TK_LE );
63719      testcase( op==TK_GT );
63720      testcase( op==TK_GE );
63721      testcase( op==TK_EQ );
63722      testcase( op==TK_NE );
63723      testcase( jumpIfNull==0 );
63724      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63725      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63726      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63727                  r1, r2, dest, jumpIfNull);
63728      testcase( regFree1==0 );
63729      testcase( regFree2==0 );
63730      break;
63731    }
63732    case TK_IS:
63733    case TK_ISNOT: {
63734      testcase( op==TK_IS );
63735      testcase( op==TK_ISNOT );
63736      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63737      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63738      op = (op==TK_IS) ? TK_EQ : TK_NE;
63739      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63740                  r1, r2, dest, SQLITE_NULLEQ);
63741      testcase( regFree1==0 );
63742      testcase( regFree2==0 );
63743      break;
63744    }
63745    case TK_ISNULL:
63746    case TK_NOTNULL: {
63747      assert( TK_ISNULL==OP_IsNull );
63748      assert( TK_NOTNULL==OP_NotNull );
63749      testcase( op==TK_ISNULL );
63750      testcase( op==TK_NOTNULL );
63751      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63752      sqlite3VdbeAddOp2(v, op, r1, dest);
63753      testcase( regFree1==0 );
63754      break;
63755    }
63756    case TK_BETWEEN: {
63757      testcase( jumpIfNull==0 );
63758      exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
63759      break;
63760    }
63761    case TK_IN: {
63762      int destIfFalse = sqlite3VdbeMakeLabel(v);
63763      int destIfNull = jumpIfNull ? dest : destIfFalse;
63764      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
63765      sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
63766      sqlite3VdbeResolveLabel(v, destIfFalse);
63767      break;
63768    }
63769    default: {
63770      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
63771      sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
63772      testcase( regFree1==0 );
63773      testcase( jumpIfNull==0 );
63774      break;
63775    }
63776  }
63777  sqlite3ReleaseTempReg(pParse, regFree1);
63778  sqlite3ReleaseTempReg(pParse, regFree2);
63779}
63780
63781/*
63782** Generate code for a boolean expression such that a jump is made
63783** to the label "dest" if the expression is false but execution
63784** continues straight thru if the expression is true.
63785**
63786** If the expression evaluates to NULL (neither true nor false) then
63787** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
63788** is 0.
63789*/
63790SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
63791  Vdbe *v = pParse->pVdbe;
63792  int op = 0;
63793  int regFree1 = 0;
63794  int regFree2 = 0;
63795  int r1, r2;
63796
63797  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
63798  if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
63799  if( pExpr==0 )    return;
63800
63801  /* The value of pExpr->op and op are related as follows:
63802  **
63803  **       pExpr->op            op
63804  **       ---------          ----------
63805  **       TK_ISNULL          OP_NotNull
63806  **       TK_NOTNULL         OP_IsNull
63807  **       TK_NE              OP_Eq
63808  **       TK_EQ              OP_Ne
63809  **       TK_GT              OP_Le
63810  **       TK_LE              OP_Gt
63811  **       TK_GE              OP_Lt
63812  **       TK_LT              OP_Ge
63813  **
63814  ** For other values of pExpr->op, op is undefined and unused.
63815  ** The value of TK_ and OP_ constants are arranged such that we
63816  ** can compute the mapping above using the following expression.
63817  ** Assert()s verify that the computation is correct.
63818  */
63819  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
63820
63821  /* Verify correct alignment of TK_ and OP_ constants
63822  */
63823  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
63824  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
63825  assert( pExpr->op!=TK_NE || op==OP_Eq );
63826  assert( pExpr->op!=TK_EQ || op==OP_Ne );
63827  assert( pExpr->op!=TK_LT || op==OP_Ge );
63828  assert( pExpr->op!=TK_LE || op==OP_Gt );
63829  assert( pExpr->op!=TK_GT || op==OP_Le );
63830  assert( pExpr->op!=TK_GE || op==OP_Lt );
63831
63832  switch( pExpr->op ){
63833    case TK_AND: {
63834      testcase( jumpIfNull==0 );
63835      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
63836      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
63837      break;
63838    }
63839    case TK_OR: {
63840      int d2 = sqlite3VdbeMakeLabel(v);
63841      testcase( jumpIfNull==0 );
63842      sqlite3ExprCachePush(pParse);
63843      sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
63844      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
63845      sqlite3VdbeResolveLabel(v, d2);
63846      sqlite3ExprCachePop(pParse, 1);
63847      break;
63848    }
63849    case TK_NOT: {
63850      testcase( jumpIfNull==0 );
63851      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
63852      break;
63853    }
63854    case TK_LT:
63855    case TK_LE:
63856    case TK_GT:
63857    case TK_GE:
63858    case TK_NE:
63859    case TK_EQ: {
63860      testcase( op==TK_LT );
63861      testcase( op==TK_LE );
63862      testcase( op==TK_GT );
63863      testcase( op==TK_GE );
63864      testcase( op==TK_EQ );
63865      testcase( op==TK_NE );
63866      testcase( jumpIfNull==0 );
63867      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63868      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63869      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63870                  r1, r2, dest, jumpIfNull);
63871      testcase( regFree1==0 );
63872      testcase( regFree2==0 );
63873      break;
63874    }
63875    case TK_IS:
63876    case TK_ISNOT: {
63877      testcase( pExpr->op==TK_IS );
63878      testcase( pExpr->op==TK_ISNOT );
63879      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63880      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63881      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
63882      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63883                  r1, r2, dest, SQLITE_NULLEQ);
63884      testcase( regFree1==0 );
63885      testcase( regFree2==0 );
63886      break;
63887    }
63888    case TK_ISNULL:
63889    case TK_NOTNULL: {
63890      testcase( op==TK_ISNULL );
63891      testcase( op==TK_NOTNULL );
63892      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63893      sqlite3VdbeAddOp2(v, op, r1, dest);
63894      testcase( regFree1==0 );
63895      break;
63896    }
63897    case TK_BETWEEN: {
63898      testcase( jumpIfNull==0 );
63899      exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
63900      break;
63901    }
63902    case TK_IN: {
63903      if( jumpIfNull ){
63904        sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
63905      }else{
63906        int destIfNull = sqlite3VdbeMakeLabel(v);
63907        sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
63908        sqlite3VdbeResolveLabel(v, destIfNull);
63909      }
63910      break;
63911    }
63912    default: {
63913      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
63914      sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
63915      testcase( regFree1==0 );
63916      testcase( jumpIfNull==0 );
63917      break;
63918    }
63919  }
63920  sqlite3ReleaseTempReg(pParse, regFree1);
63921  sqlite3ReleaseTempReg(pParse, regFree2);
63922}
63923
63924/*
63925** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
63926** if they are identical and return FALSE if they differ in any way.
63927**
63928** Sometimes this routine will return FALSE even if the two expressions
63929** really are equivalent.  If we cannot prove that the expressions are
63930** identical, we return FALSE just to be safe.  So if this routine
63931** returns false, then you do not really know for certain if the two
63932** expressions are the same.  But if you get a TRUE return, then you
63933** can be sure the expressions are the same.  In the places where
63934** this routine is used, it does not hurt to get an extra FALSE - that
63935** just might result in some slightly slower code.  But returning
63936** an incorrect TRUE could lead to a malfunction.
63937*/
63938SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
63939  int i;
63940  if( pA==0||pB==0 ){
63941    return pB==pA;
63942  }
63943  assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
63944  assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
63945  if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
63946    return 0;
63947  }
63948  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
63949  if( pA->op!=pB->op ) return 0;
63950  if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
63951  if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
63952
63953  if( pA->x.pList && pB->x.pList ){
63954    if( pA->x.pList->nExpr!=pB->x.pList->nExpr ) return 0;
63955    for(i=0; i<pA->x.pList->nExpr; i++){
63956      Expr *pExprA = pA->x.pList->a[i].pExpr;
63957      Expr *pExprB = pB->x.pList->a[i].pExpr;
63958      if( !sqlite3ExprCompare(pExprA, pExprB) ) return 0;
63959    }
63960  }else if( pA->x.pList || pB->x.pList ){
63961    return 0;
63962  }
63963
63964  if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
63965  if( ExprHasProperty(pA, EP_IntValue) ){
63966    if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
63967      return 0;
63968    }
63969  }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
63970    if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 0;
63971    if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
63972      return 0;
63973    }
63974  }
63975  return 1;
63976}
63977
63978
63979/*
63980** Add a new element to the pAggInfo->aCol[] array.  Return the index of
63981** the new element.  Return a negative number if malloc fails.
63982*/
63983static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
63984  int i;
63985  pInfo->aCol = sqlite3ArrayAllocate(
63986       db,
63987       pInfo->aCol,
63988       sizeof(pInfo->aCol[0]),
63989       3,
63990       &pInfo->nColumn,
63991       &pInfo->nColumnAlloc,
63992       &i
63993  );
63994  return i;
63995}
63996
63997/*
63998** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
63999** the new element.  Return a negative number if malloc fails.
64000*/
64001static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
64002  int i;
64003  pInfo->aFunc = sqlite3ArrayAllocate(
64004       db,
64005       pInfo->aFunc,
64006       sizeof(pInfo->aFunc[0]),
64007       3,
64008       &pInfo->nFunc,
64009       &pInfo->nFuncAlloc,
64010       &i
64011  );
64012  return i;
64013}
64014
64015/*
64016** This is the xExprCallback for a tree walker.  It is used to
64017** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
64018** for additional information.
64019*/
64020static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
64021  int i;
64022  NameContext *pNC = pWalker->u.pNC;
64023  Parse *pParse = pNC->pParse;
64024  SrcList *pSrcList = pNC->pSrcList;
64025  AggInfo *pAggInfo = pNC->pAggInfo;
64026
64027  switch( pExpr->op ){
64028    case TK_AGG_COLUMN:
64029    case TK_COLUMN: {
64030      testcase( pExpr->op==TK_AGG_COLUMN );
64031      testcase( pExpr->op==TK_COLUMN );
64032      /* Check to see if the column is in one of the tables in the FROM
64033      ** clause of the aggregate query */
64034      if( ALWAYS(pSrcList!=0) ){
64035        struct SrcList_item *pItem = pSrcList->a;
64036        for(i=0; i<pSrcList->nSrc; i++, pItem++){
64037          struct AggInfo_col *pCol;
64038          assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
64039          if( pExpr->iTable==pItem->iCursor ){
64040            /* If we reach this point, it means that pExpr refers to a table
64041            ** that is in the FROM clause of the aggregate query.
64042            **
64043            ** Make an entry for the column in pAggInfo->aCol[] if there
64044            ** is not an entry there already.
64045            */
64046            int k;
64047            pCol = pAggInfo->aCol;
64048            for(k=0; k<pAggInfo->nColumn; k++, pCol++){
64049              if( pCol->iTable==pExpr->iTable &&
64050                  pCol->iColumn==pExpr->iColumn ){
64051                break;
64052              }
64053            }
64054            if( (k>=pAggInfo->nColumn)
64055             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
64056            ){
64057              pCol = &pAggInfo->aCol[k];
64058              pCol->pTab = pExpr->pTab;
64059              pCol->iTable = pExpr->iTable;
64060              pCol->iColumn = pExpr->iColumn;
64061              pCol->iMem = ++pParse->nMem;
64062              pCol->iSorterColumn = -1;
64063              pCol->pExpr = pExpr;
64064              if( pAggInfo->pGroupBy ){
64065                int j, n;
64066                ExprList *pGB = pAggInfo->pGroupBy;
64067                struct ExprList_item *pTerm = pGB->a;
64068                n = pGB->nExpr;
64069                for(j=0; j<n; j++, pTerm++){
64070                  Expr *pE = pTerm->pExpr;
64071                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
64072                      pE->iColumn==pExpr->iColumn ){
64073                    pCol->iSorterColumn = j;
64074                    break;
64075                  }
64076                }
64077              }
64078              if( pCol->iSorterColumn<0 ){
64079                pCol->iSorterColumn = pAggInfo->nSortingColumn++;
64080              }
64081            }
64082            /* There is now an entry for pExpr in pAggInfo->aCol[] (either
64083            ** because it was there before or because we just created it).
64084            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
64085            ** pAggInfo->aCol[] entry.
64086            */
64087            ExprSetIrreducible(pExpr);
64088            pExpr->pAggInfo = pAggInfo;
64089            pExpr->op = TK_AGG_COLUMN;
64090            pExpr->iAgg = (i16)k;
64091            break;
64092          } /* endif pExpr->iTable==pItem->iCursor */
64093        } /* end loop over pSrcList */
64094      }
64095      return WRC_Prune;
64096    }
64097    case TK_AGG_FUNCTION: {
64098      /* The pNC->nDepth==0 test causes aggregate functions in subqueries
64099      ** to be ignored */
64100      if( pNC->nDepth==0 ){
64101        /* Check to see if pExpr is a duplicate of another aggregate
64102        ** function that is already in the pAggInfo structure
64103        */
64104        struct AggInfo_func *pItem = pAggInfo->aFunc;
64105        for(i=0; i<pAggInfo->nFunc; i++, pItem++){
64106          if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
64107            break;
64108          }
64109        }
64110        if( i>=pAggInfo->nFunc ){
64111          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
64112          */
64113          u8 enc = ENC(pParse->db);
64114          i = addAggInfoFunc(pParse->db, pAggInfo);
64115          if( i>=0 ){
64116            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
64117            pItem = &pAggInfo->aFunc[i];
64118            pItem->pExpr = pExpr;
64119            pItem->iMem = ++pParse->nMem;
64120            assert( !ExprHasProperty(pExpr, EP_IntValue) );
64121            pItem->pFunc = sqlite3FindFunction(pParse->db,
64122                   pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
64123                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
64124            if( pExpr->flags & EP_Distinct ){
64125              pItem->iDistinct = pParse->nTab++;
64126            }else{
64127              pItem->iDistinct = -1;
64128            }
64129          }
64130        }
64131        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
64132        */
64133        assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
64134        ExprSetIrreducible(pExpr);
64135        pExpr->iAgg = (i16)i;
64136        pExpr->pAggInfo = pAggInfo;
64137        return WRC_Prune;
64138      }
64139    }
64140  }
64141  return WRC_Continue;
64142}
64143static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
64144  NameContext *pNC = pWalker->u.pNC;
64145  if( pNC->nDepth==0 ){
64146    pNC->nDepth++;
64147    sqlite3WalkSelect(pWalker, pSelect);
64148    pNC->nDepth--;
64149    return WRC_Prune;
64150  }else{
64151    return WRC_Continue;
64152  }
64153}
64154
64155/*
64156** Analyze the given expression looking for aggregate functions and
64157** for variables that need to be added to the pParse->aAgg[] array.
64158** Make additional entries to the pParse->aAgg[] array as necessary.
64159**
64160** This routine should only be called after the expression has been
64161** analyzed by sqlite3ResolveExprNames().
64162*/
64163SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
64164  Walker w;
64165  w.xExprCallback = analyzeAggregate;
64166  w.xSelectCallback = analyzeAggregatesInSelect;
64167  w.u.pNC = pNC;
64168  assert( pNC->pSrcList!=0 );
64169  sqlite3WalkExpr(&w, pExpr);
64170}
64171
64172/*
64173** Call sqlite3ExprAnalyzeAggregates() for every expression in an
64174** expression list.  Return the number of errors.
64175**
64176** If an error is found, the analysis is cut short.
64177*/
64178SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
64179  struct ExprList_item *pItem;
64180  int i;
64181  if( pList ){
64182    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
64183      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
64184    }
64185  }
64186}
64187
64188/*
64189** Allocate a single new register for use to hold some intermediate result.
64190*/
64191SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
64192  if( pParse->nTempReg==0 ){
64193    return ++pParse->nMem;
64194  }
64195  return pParse->aTempReg[--pParse->nTempReg];
64196}
64197
64198/*
64199** Deallocate a register, making available for reuse for some other
64200** purpose.
64201**
64202** If a register is currently being used by the column cache, then
64203** the dallocation is deferred until the column cache line that uses
64204** the register becomes stale.
64205*/
64206SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
64207  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
64208    int i;
64209    struct yColCache *p;
64210    for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
64211      if( p->iReg==iReg ){
64212        p->tempReg = 1;
64213        return;
64214      }
64215    }
64216    pParse->aTempReg[pParse->nTempReg++] = iReg;
64217  }
64218}
64219
64220/*
64221** Allocate or deallocate a block of nReg consecutive registers
64222*/
64223SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
64224  int i, n;
64225  i = pParse->iRangeReg;
64226  n = pParse->nRangeReg;
64227  if( nReg<=n ){
64228    assert( !usedAsColumnCache(pParse, i, i+n-1) );
64229    pParse->iRangeReg += nReg;
64230    pParse->nRangeReg -= nReg;
64231  }else{
64232    i = pParse->nMem+1;
64233    pParse->nMem += nReg;
64234  }
64235  return i;
64236}
64237SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
64238  sqlite3ExprCacheRemove(pParse, iReg, nReg);
64239  if( nReg>pParse->nRangeReg ){
64240    pParse->nRangeReg = nReg;
64241    pParse->iRangeReg = iReg;
64242  }
64243}
64244
64245/************** End of expr.c ************************************************/
64246/************** Begin file alter.c *******************************************/
64247/*
64248** 2005 February 15
64249**
64250** The author disclaims copyright to this source code.  In place of
64251** a legal notice, here is a blessing:
64252**
64253**    May you do good and not evil.
64254**    May you find forgiveness for yourself and forgive others.
64255**    May you share freely, never taking more than you give.
64256**
64257*************************************************************************
64258** This file contains C code routines that used to generate VDBE code
64259** that implements the ALTER TABLE command.
64260*/
64261
64262/*
64263** The code in this file only exists if we are not omitting the
64264** ALTER TABLE logic from the build.
64265*/
64266#ifndef SQLITE_OMIT_ALTERTABLE
64267
64268
64269/*
64270** This function is used by SQL generated to implement the
64271** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
64272** CREATE INDEX command. The second is a table name. The table name in
64273** the CREATE TABLE or CREATE INDEX statement is replaced with the third
64274** argument and the result returned. Examples:
64275**
64276** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
64277**     -> 'CREATE TABLE def(a, b, c)'
64278**
64279** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
64280**     -> 'CREATE INDEX i ON def(a, b, c)'
64281*/
64282static void renameTableFunc(
64283  sqlite3_context *context,
64284  int NotUsed,
64285  sqlite3_value **argv
64286){
64287  unsigned char const *zSql = sqlite3_value_text(argv[0]);
64288  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
64289
64290  int token;
64291  Token tname;
64292  unsigned char const *zCsr = zSql;
64293  int len = 0;
64294  char *zRet;
64295
64296  sqlite3 *db = sqlite3_context_db_handle(context);
64297
64298  UNUSED_PARAMETER(NotUsed);
64299
64300  /* The principle used to locate the table name in the CREATE TABLE
64301  ** statement is that the table name is the first non-space token that
64302  ** is immediately followed by a TK_LP or TK_USING token.
64303  */
64304  if( zSql ){
64305    do {
64306      if( !*zCsr ){
64307        /* Ran out of input before finding an opening bracket. Return NULL. */
64308        return;
64309      }
64310
64311      /* Store the token that zCsr points to in tname. */
64312      tname.z = (char*)zCsr;
64313      tname.n = len;
64314
64315      /* Advance zCsr to the next token. Store that token type in 'token',
64316      ** and its length in 'len' (to be used next iteration of this loop).
64317      */
64318      do {
64319        zCsr += len;
64320        len = sqlite3GetToken(zCsr, &token);
64321      } while( token==TK_SPACE );
64322      assert( len>0 );
64323    } while( token!=TK_LP && token!=TK_USING );
64324
64325    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
64326       zTableName, tname.z+tname.n);
64327    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
64328  }
64329}
64330
64331/*
64332** This C function implements an SQL user function that is used by SQL code
64333** generated by the ALTER TABLE ... RENAME command to modify the definition
64334** of any foreign key constraints that use the table being renamed as the
64335** parent table. It is passed three arguments:
64336**
64337**   1) The complete text of the CREATE TABLE statement being modified,
64338**   2) The old name of the table being renamed, and
64339**   3) The new name of the table being renamed.
64340**
64341** It returns the new CREATE TABLE statement. For example:
64342**
64343**   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
64344**       -> 'CREATE TABLE t1(a REFERENCES t3)'
64345*/
64346#ifndef SQLITE_OMIT_FOREIGN_KEY
64347static void renameParentFunc(
64348  sqlite3_context *context,
64349  int NotUsed,
64350  sqlite3_value **argv
64351){
64352  sqlite3 *db = sqlite3_context_db_handle(context);
64353  char *zOutput = 0;
64354  char *zResult;
64355  unsigned char const *zInput = sqlite3_value_text(argv[0]);
64356  unsigned char const *zOld = sqlite3_value_text(argv[1]);
64357  unsigned char const *zNew = sqlite3_value_text(argv[2]);
64358
64359  unsigned const char *z;         /* Pointer to token */
64360  int n;                          /* Length of token z */
64361  int token;                      /* Type of token */
64362
64363  UNUSED_PARAMETER(NotUsed);
64364  for(z=zInput; *z; z=z+n){
64365    n = sqlite3GetToken(z, &token);
64366    if( token==TK_REFERENCES ){
64367      char *zParent;
64368      do {
64369        z += n;
64370        n = sqlite3GetToken(z, &token);
64371      }while( token==TK_SPACE );
64372
64373      zParent = sqlite3DbStrNDup(db, (const char *)z, n);
64374      if( zParent==0 ) break;
64375      sqlite3Dequote(zParent);
64376      if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
64377        char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
64378            (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
64379        );
64380        sqlite3DbFree(db, zOutput);
64381        zOutput = zOut;
64382        zInput = &z[n];
64383      }
64384      sqlite3DbFree(db, zParent);
64385    }
64386  }
64387
64388  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
64389  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
64390  sqlite3DbFree(db, zOutput);
64391}
64392#endif
64393
64394#ifndef SQLITE_OMIT_TRIGGER
64395/* This function is used by SQL generated to implement the
64396** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
64397** statement. The second is a table name. The table name in the CREATE
64398** TRIGGER statement is replaced with the third argument and the result
64399** returned. This is analagous to renameTableFunc() above, except for CREATE
64400** TRIGGER, not CREATE INDEX and CREATE TABLE.
64401*/
64402static void renameTriggerFunc(
64403  sqlite3_context *context,
64404  int NotUsed,
64405  sqlite3_value **argv
64406){
64407  unsigned char const *zSql = sqlite3_value_text(argv[0]);
64408  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
64409
64410  int token;
64411  Token tname;
64412  int dist = 3;
64413  unsigned char const *zCsr = zSql;
64414  int len = 0;
64415  char *zRet;
64416  sqlite3 *db = sqlite3_context_db_handle(context);
64417
64418  UNUSED_PARAMETER(NotUsed);
64419
64420  /* The principle used to locate the table name in the CREATE TRIGGER
64421  ** statement is that the table name is the first token that is immediatedly
64422  ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
64423  ** of TK_WHEN, TK_BEGIN or TK_FOR.
64424  */
64425  if( zSql ){
64426    do {
64427
64428      if( !*zCsr ){
64429        /* Ran out of input before finding the table name. Return NULL. */
64430        return;
64431      }
64432
64433      /* Store the token that zCsr points to in tname. */
64434      tname.z = (char*)zCsr;
64435      tname.n = len;
64436
64437      /* Advance zCsr to the next token. Store that token type in 'token',
64438      ** and its length in 'len' (to be used next iteration of this loop).
64439      */
64440      do {
64441        zCsr += len;
64442        len = sqlite3GetToken(zCsr, &token);
64443      }while( token==TK_SPACE );
64444      assert( len>0 );
64445
64446      /* Variable 'dist' stores the number of tokens read since the most
64447      ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
64448      ** token is read and 'dist' equals 2, the condition stated above
64449      ** to be met.
64450      **
64451      ** Note that ON cannot be a database, table or column name, so
64452      ** there is no need to worry about syntax like
64453      ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
64454      */
64455      dist++;
64456      if( token==TK_DOT || token==TK_ON ){
64457        dist = 0;
64458      }
64459    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
64460
64461    /* Variable tname now contains the token that is the old table-name
64462    ** in the CREATE TRIGGER statement.
64463    */
64464    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
64465       zTableName, tname.z+tname.n);
64466    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
64467  }
64468}
64469#endif   /* !SQLITE_OMIT_TRIGGER */
64470
64471/*
64472** Register built-in functions used to help implement ALTER TABLE
64473*/
64474SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3 *db){
64475  sqlite3CreateFunc(db, "sqlite_rename_table", 2, SQLITE_UTF8, 0,
64476                         renameTableFunc, 0, 0);
64477#ifndef SQLITE_OMIT_TRIGGER
64478  sqlite3CreateFunc(db, "sqlite_rename_trigger", 2, SQLITE_UTF8, 0,
64479                         renameTriggerFunc, 0, 0);
64480#endif
64481#ifndef SQLITE_OMIT_FOREIGN_KEY
64482  sqlite3CreateFunc(db, "sqlite_rename_parent", 3, SQLITE_UTF8, 0,
64483                         renameParentFunc, 0, 0);
64484#endif
64485}
64486
64487/*
64488** This function is used to create the text of expressions of the form:
64489**
64490**   name=<constant1> OR name=<constant2> OR ...
64491**
64492** If argument zWhere is NULL, then a pointer string containing the text
64493** "name=<constant>" is returned, where <constant> is the quoted version
64494** of the string passed as argument zConstant. The returned buffer is
64495** allocated using sqlite3DbMalloc(). It is the responsibility of the
64496** caller to ensure that it is eventually freed.
64497**
64498** If argument zWhere is not NULL, then the string returned is
64499** "<where> OR name=<constant>", where <where> is the contents of zWhere.
64500** In this case zWhere is passed to sqlite3DbFree() before returning.
64501**
64502*/
64503static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
64504  char *zNew;
64505  if( !zWhere ){
64506    zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
64507  }else{
64508    zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
64509    sqlite3DbFree(db, zWhere);
64510  }
64511  return zNew;
64512}
64513
64514#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
64515/*
64516** Generate the text of a WHERE expression which can be used to select all
64517** tables that have foreign key constraints that refer to table pTab (i.e.
64518** constraints for which pTab is the parent table) from the sqlite_master
64519** table.
64520*/
64521static char *whereForeignKeys(Parse *pParse, Table *pTab){
64522  FKey *p;
64523  char *zWhere = 0;
64524  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
64525    zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
64526  }
64527  return zWhere;
64528}
64529#endif
64530
64531/*
64532** Generate the text of a WHERE expression which can be used to select all
64533** temporary triggers on table pTab from the sqlite_temp_master table. If
64534** table pTab has no temporary triggers, or is itself stored in the
64535** temporary database, NULL is returned.
64536*/
64537static char *whereTempTriggers(Parse *pParse, Table *pTab){
64538  Trigger *pTrig;
64539  char *zWhere = 0;
64540  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
64541
64542  /* If the table is not located in the temp-db (in which case NULL is
64543  ** returned, loop through the tables list of triggers. For each trigger
64544  ** that is not part of the temp-db schema, add a clause to the WHERE
64545  ** expression being built up in zWhere.
64546  */
64547  if( pTab->pSchema!=pTempSchema ){
64548    sqlite3 *db = pParse->db;
64549    for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
64550      if( pTrig->pSchema==pTempSchema ){
64551        zWhere = whereOrName(db, zWhere, pTrig->zName);
64552      }
64553    }
64554  }
64555  return zWhere;
64556}
64557
64558/*
64559** Generate code to drop and reload the internal representation of table
64560** pTab from the database, including triggers and temporary triggers.
64561** Argument zName is the name of the table in the database schema at
64562** the time the generated code is executed. This can be different from
64563** pTab->zName if this function is being called to code part of an
64564** "ALTER TABLE RENAME TO" statement.
64565*/
64566static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
64567  Vdbe *v;
64568  char *zWhere;
64569  int iDb;                   /* Index of database containing pTab */
64570#ifndef SQLITE_OMIT_TRIGGER
64571  Trigger *pTrig;
64572#endif
64573
64574  v = sqlite3GetVdbe(pParse);
64575  if( NEVER(v==0) ) return;
64576  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
64577  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
64578  assert( iDb>=0 );
64579
64580#ifndef SQLITE_OMIT_TRIGGER
64581  /* Drop any table triggers from the internal schema. */
64582  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
64583    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
64584    assert( iTrigDb==iDb || iTrigDb==1 );
64585    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
64586  }
64587#endif
64588
64589  /* Drop the table and index from the internal schema.  */
64590  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
64591
64592  /* Reload the table, index and permanent trigger schemas. */
64593  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
64594  if( !zWhere ) return;
64595  sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
64596
64597#ifndef SQLITE_OMIT_TRIGGER
64598  /* Now, if the table is not stored in the temp database, reload any temp
64599  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
64600  */
64601  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
64602    sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
64603  }
64604#endif
64605}
64606
64607/*
64608** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
64609** command.
64610*/
64611SQLITE_PRIVATE void sqlite3AlterRenameTable(
64612  Parse *pParse,            /* Parser context. */
64613  SrcList *pSrc,            /* The table to rename. */
64614  Token *pName              /* The new table name. */
64615){
64616  int iDb;                  /* Database that contains the table */
64617  char *zDb;                /* Name of database iDb */
64618  Table *pTab;              /* Table being renamed */
64619  char *zName = 0;          /* NULL-terminated version of pName */
64620  sqlite3 *db = pParse->db; /* Database connection */
64621  int nTabName;             /* Number of UTF-8 characters in zTabName */
64622  const char *zTabName;     /* Original name of the table */
64623  Vdbe *v;
64624#ifndef SQLITE_OMIT_TRIGGER
64625  char *zWhere = 0;         /* Where clause to locate temp triggers */
64626#endif
64627  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
64628
64629  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
64630  assert( pSrc->nSrc==1 );
64631  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
64632
64633  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
64634  if( !pTab ) goto exit_rename_table;
64635  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
64636  zDb = db->aDb[iDb].zName;
64637
64638  /* Get a NULL terminated version of the new table name. */
64639  zName = sqlite3NameFromToken(db, pName);
64640  if( !zName ) goto exit_rename_table;
64641
64642  /* Check that a table or index named 'zName' does not already exist
64643  ** in database iDb. If so, this is an error.
64644  */
64645  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
64646    sqlite3ErrorMsg(pParse,
64647        "there is already another table or index with this name: %s", zName);
64648    goto exit_rename_table;
64649  }
64650
64651  /* Make sure it is not a system table being altered, or a reserved name
64652  ** that the table is being renamed to.
64653  */
64654  if( sqlite3Strlen30(pTab->zName)>6
64655   && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
64656  ){
64657    sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
64658    goto exit_rename_table;
64659  }
64660  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
64661    goto exit_rename_table;
64662  }
64663
64664#ifndef SQLITE_OMIT_VIEW
64665  if( pTab->pSelect ){
64666    sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
64667    goto exit_rename_table;
64668  }
64669#endif
64670
64671#ifndef SQLITE_OMIT_AUTHORIZATION
64672  /* Invoke the authorization callback. */
64673  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
64674    goto exit_rename_table;
64675  }
64676#endif
64677
64678#ifndef SQLITE_OMIT_VIRTUALTABLE
64679  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
64680    goto exit_rename_table;
64681  }
64682  if( IsVirtual(pTab) ){
64683    pVTab = sqlite3GetVTable(db, pTab);
64684    if( pVTab->pVtab->pModule->xRename==0 ){
64685      pVTab = 0;
64686    }
64687  }
64688#endif
64689
64690  /* Begin a transaction and code the VerifyCookie for database iDb.
64691  ** Then modify the schema cookie (since the ALTER TABLE modifies the
64692  ** schema). Open a statement transaction if the table is a virtual
64693  ** table.
64694  */
64695  v = sqlite3GetVdbe(pParse);
64696  if( v==0 ){
64697    goto exit_rename_table;
64698  }
64699  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
64700  sqlite3ChangeCookie(pParse, iDb);
64701
64702  /* If this is a virtual table, invoke the xRename() function if
64703  ** one is defined. The xRename() callback will modify the names
64704  ** of any resources used by the v-table implementation (including other
64705  ** SQLite tables) that are identified by the name of the virtual table.
64706  */
64707#ifndef SQLITE_OMIT_VIRTUALTABLE
64708  if( pVTab ){
64709    int i = ++pParse->nMem;
64710    sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
64711    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
64712    sqlite3MayAbort(pParse);
64713  }
64714#endif
64715
64716  /* figure out how many UTF-8 characters are in zName */
64717  zTabName = pTab->zName;
64718  nTabName = sqlite3Utf8CharLen(zTabName, -1);
64719
64720#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
64721  if( db->flags&SQLITE_ForeignKeys ){
64722    /* If foreign-key support is enabled, rewrite the CREATE TABLE
64723    ** statements corresponding to all child tables of foreign key constraints
64724    ** for which the renamed table is the parent table.  */
64725    if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
64726      sqlite3NestedParse(pParse,
64727          "UPDATE sqlite_master SET "
64728              "sql = sqlite_rename_parent(sql, %Q, %Q) "
64729              "WHERE %s;", zTabName, zName, zWhere);
64730      sqlite3DbFree(db, zWhere);
64731    }
64732  }
64733#endif
64734
64735  /* Modify the sqlite_master table to use the new table name. */
64736  sqlite3NestedParse(pParse,
64737      "UPDATE %Q.%s SET "
64738#ifdef SQLITE_OMIT_TRIGGER
64739          "sql = sqlite_rename_table(sql, %Q), "
64740#else
64741          "sql = CASE "
64742            "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
64743            "ELSE sqlite_rename_table(sql, %Q) END, "
64744#endif
64745          "tbl_name = %Q, "
64746          "name = CASE "
64747            "WHEN type='table' THEN %Q "
64748            "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
64749             "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
64750            "ELSE name END "
64751      "WHERE tbl_name=%Q AND "
64752          "(type='table' OR type='index' OR type='trigger');",
64753      zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
64754#ifndef SQLITE_OMIT_TRIGGER
64755      zName,
64756#endif
64757      zName, nTabName, zTabName
64758  );
64759
64760#ifndef SQLITE_OMIT_AUTOINCREMENT
64761  /* If the sqlite_sequence table exists in this database, then update
64762  ** it with the new table name.
64763  */
64764  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
64765    sqlite3NestedParse(pParse,
64766        "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
64767        zDb, zName, pTab->zName);
64768  }
64769#endif
64770
64771#ifndef SQLITE_OMIT_TRIGGER
64772  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
64773  ** table. Don't do this if the table being ALTERed is itself located in
64774  ** the temp database.
64775  */
64776  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
64777    sqlite3NestedParse(pParse,
64778        "UPDATE sqlite_temp_master SET "
64779            "sql = sqlite_rename_trigger(sql, %Q), "
64780            "tbl_name = %Q "
64781            "WHERE %s;", zName, zName, zWhere);
64782    sqlite3DbFree(db, zWhere);
64783  }
64784#endif
64785
64786#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
64787  if( db->flags&SQLITE_ForeignKeys ){
64788    FKey *p;
64789    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
64790      Table *pFrom = p->pFrom;
64791      if( pFrom!=pTab ){
64792        reloadTableSchema(pParse, p->pFrom, pFrom->zName);
64793      }
64794    }
64795  }
64796#endif
64797
64798  /* Drop and reload the internal table schema. */
64799  reloadTableSchema(pParse, pTab, zName);
64800
64801exit_rename_table:
64802  sqlite3SrcListDelete(db, pSrc);
64803  sqlite3DbFree(db, zName);
64804}
64805
64806
64807/*
64808** Generate code to make sure the file format number is at least minFormat.
64809** The generated code will increase the file format number if necessary.
64810*/
64811SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
64812  Vdbe *v;
64813  v = sqlite3GetVdbe(pParse);
64814  /* The VDBE should have been allocated before this routine is called.
64815  ** If that allocation failed, we would have quit before reaching this
64816  ** point */
64817  if( ALWAYS(v) ){
64818    int r1 = sqlite3GetTempReg(pParse);
64819    int r2 = sqlite3GetTempReg(pParse);
64820    int j1;
64821    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
64822    sqlite3VdbeUsesBtree(v, iDb);
64823    sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
64824    j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
64825    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
64826    sqlite3VdbeJumpHere(v, j1);
64827    sqlite3ReleaseTempReg(pParse, r1);
64828    sqlite3ReleaseTempReg(pParse, r2);
64829  }
64830}
64831
64832/*
64833** This function is called after an "ALTER TABLE ... ADD" statement
64834** has been parsed. Argument pColDef contains the text of the new
64835** column definition.
64836**
64837** The Table structure pParse->pNewTable was extended to include
64838** the new column during parsing.
64839*/
64840SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
64841  Table *pNew;              /* Copy of pParse->pNewTable */
64842  Table *pTab;              /* Table being altered */
64843  int iDb;                  /* Database number */
64844  const char *zDb;          /* Database name */
64845  const char *zTab;         /* Table name */
64846  char *zCol;               /* Null-terminated column definition */
64847  Column *pCol;             /* The new column */
64848  Expr *pDflt;              /* Default value for the new column */
64849  sqlite3 *db;              /* The database connection; */
64850
64851  db = pParse->db;
64852  if( pParse->nErr || db->mallocFailed ) return;
64853  pNew = pParse->pNewTable;
64854  assert( pNew );
64855
64856  assert( sqlite3BtreeHoldsAllMutexes(db) );
64857  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
64858  zDb = db->aDb[iDb].zName;
64859  zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
64860  pCol = &pNew->aCol[pNew->nCol-1];
64861  pDflt = pCol->pDflt;
64862  pTab = sqlite3FindTable(db, zTab, zDb);
64863  assert( pTab );
64864
64865#ifndef SQLITE_OMIT_AUTHORIZATION
64866  /* Invoke the authorization callback. */
64867  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
64868    return;
64869  }
64870#endif
64871
64872  /* If the default value for the new column was specified with a
64873  ** literal NULL, then set pDflt to 0. This simplifies checking
64874  ** for an SQL NULL default below.
64875  */
64876  if( pDflt && pDflt->op==TK_NULL ){
64877    pDflt = 0;
64878  }
64879
64880  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
64881  ** If there is a NOT NULL constraint, then the default value for the
64882  ** column must not be NULL.
64883  */
64884  if( pCol->isPrimKey ){
64885    sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
64886    return;
64887  }
64888  if( pNew->pIndex ){
64889    sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
64890    return;
64891  }
64892  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
64893    sqlite3ErrorMsg(pParse,
64894        "Cannot add a REFERENCES column with non-NULL default value");
64895    return;
64896  }
64897  if( pCol->notNull && !pDflt ){
64898    sqlite3ErrorMsg(pParse,
64899        "Cannot add a NOT NULL column with default value NULL");
64900    return;
64901  }
64902
64903  /* Ensure the default expression is something that sqlite3ValueFromExpr()
64904  ** can handle (i.e. not CURRENT_TIME etc.)
64905  */
64906  if( pDflt ){
64907    sqlite3_value *pVal;
64908    if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
64909      db->mallocFailed = 1;
64910      return;
64911    }
64912    if( !pVal ){
64913      sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
64914      return;
64915    }
64916    sqlite3ValueFree(pVal);
64917  }
64918
64919  /* Modify the CREATE TABLE statement. */
64920  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
64921  if( zCol ){
64922    char *zEnd = &zCol[pColDef->n-1];
64923    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
64924      *zEnd-- = '\0';
64925    }
64926    sqlite3NestedParse(pParse,
64927        "UPDATE \"%w\".%s SET "
64928          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
64929        "WHERE type = 'table' AND name = %Q",
64930      zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
64931      zTab
64932    );
64933    sqlite3DbFree(db, zCol);
64934  }
64935
64936  /* If the default value of the new column is NULL, then set the file
64937  ** format to 2. If the default value of the new column is not NULL,
64938  ** the file format becomes 3.
64939  */
64940  sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
64941
64942  /* Reload the schema of the modified table. */
64943  reloadTableSchema(pParse, pTab, pTab->zName);
64944}
64945
64946/*
64947** This function is called by the parser after the table-name in
64948** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
64949** pSrc is the full-name of the table being altered.
64950**
64951** This routine makes a (partial) copy of the Table structure
64952** for the table being altered and sets Parse.pNewTable to point
64953** to it. Routines called by the parser as the column definition
64954** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
64955** the copy. The copy of the Table structure is deleted by tokenize.c
64956** after parsing is finished.
64957**
64958** Routine sqlite3AlterFinishAddColumn() will be called to complete
64959** coding the "ALTER TABLE ... ADD" statement.
64960*/
64961SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
64962  Table *pNew;
64963  Table *pTab;
64964  Vdbe *v;
64965  int iDb;
64966  int i;
64967  int nAlloc;
64968  sqlite3 *db = pParse->db;
64969
64970  /* Look up the table being altered. */
64971  assert( pParse->pNewTable==0 );
64972  assert( sqlite3BtreeHoldsAllMutexes(db) );
64973  if( db->mallocFailed ) goto exit_begin_add_column;
64974  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
64975  if( !pTab ) goto exit_begin_add_column;
64976
64977#ifndef SQLITE_OMIT_VIRTUALTABLE
64978  if( IsVirtual(pTab) ){
64979    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
64980    goto exit_begin_add_column;
64981  }
64982#endif
64983
64984  /* Make sure this is not an attempt to ALTER a view. */
64985  if( pTab->pSelect ){
64986    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
64987    goto exit_begin_add_column;
64988  }
64989
64990  assert( pTab->addColOffset>0 );
64991  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
64992
64993  /* Put a copy of the Table struct in Parse.pNewTable for the
64994  ** sqlite3AddColumn() function and friends to modify.  But modify
64995  ** the name by adding an "sqlite_altertab_" prefix.  By adding this
64996  ** prefix, we insure that the name will not collide with an existing
64997  ** table because user table are not allowed to have the "sqlite_"
64998  ** prefix on their name.
64999  */
65000  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
65001  if( !pNew ) goto exit_begin_add_column;
65002  pParse->pNewTable = pNew;
65003  pNew->nRef = 1;
65004  pNew->dbMem = pTab->dbMem;
65005  pNew->nCol = pTab->nCol;
65006  assert( pNew->nCol>0 );
65007  nAlloc = (((pNew->nCol-1)/8)*8)+8;
65008  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
65009  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
65010  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
65011  if( !pNew->aCol || !pNew->zName ){
65012    db->mallocFailed = 1;
65013    goto exit_begin_add_column;
65014  }
65015  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
65016  for(i=0; i<pNew->nCol; i++){
65017    Column *pCol = &pNew->aCol[i];
65018    pCol->zName = sqlite3DbStrDup(db, pCol->zName);
65019    pCol->zColl = 0;
65020    pCol->zType = 0;
65021    pCol->pDflt = 0;
65022    pCol->zDflt = 0;
65023  }
65024  pNew->pSchema = db->aDb[iDb].pSchema;
65025  pNew->addColOffset = pTab->addColOffset;
65026  pNew->nRef = 1;
65027
65028  /* Begin a transaction and increment the schema cookie.  */
65029  sqlite3BeginWriteOperation(pParse, 0, iDb);
65030  v = sqlite3GetVdbe(pParse);
65031  if( !v ) goto exit_begin_add_column;
65032  sqlite3ChangeCookie(pParse, iDb);
65033
65034exit_begin_add_column:
65035  sqlite3SrcListDelete(db, pSrc);
65036  return;
65037}
65038#endif  /* SQLITE_ALTER_TABLE */
65039
65040/************** End of alter.c ***********************************************/
65041/************** Begin file analyze.c *****************************************/
65042/*
65043** 2005 July 8
65044**
65045** The author disclaims copyright to this source code.  In place of
65046** a legal notice, here is a blessing:
65047**
65048**    May you do good and not evil.
65049**    May you find forgiveness for yourself and forgive others.
65050**    May you share freely, never taking more than you give.
65051**
65052*************************************************************************
65053** This file contains code associated with the ANALYZE command.
65054*/
65055#ifndef SQLITE_OMIT_ANALYZE
65056
65057/*
65058** This routine generates code that opens the sqlite_stat1 table for
65059** writing with cursor iStatCur. If the library was built with the
65060** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
65061** opened for writing using cursor (iStatCur+1)
65062**
65063** If the sqlite_stat1 tables does not previously exist, it is created.
65064** Similarly, if the sqlite_stat2 table does not exist and the library
65065** is compiled with SQLITE_ENABLE_STAT2 defined, it is created.
65066**
65067** Argument zWhere may be a pointer to a buffer containing a table name,
65068** or it may be a NULL pointer. If it is not NULL, then all entries in
65069** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
65070** with the named table are deleted. If zWhere==0, then code is generated
65071** to delete all stat table entries.
65072*/
65073static void openStatTable(
65074  Parse *pParse,          /* Parsing context */
65075  int iDb,                /* The database we are looking in */
65076  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
65077  const char *zWhere      /* Delete entries associated with this table */
65078){
65079  static struct {
65080    const char *zName;
65081    const char *zCols;
65082  } aTable[] = {
65083    { "sqlite_stat1", "tbl,idx,stat" },
65084#ifdef SQLITE_ENABLE_STAT2
65085    { "sqlite_stat2", "tbl,idx,sampleno,sample" },
65086#endif
65087  };
65088
65089  int aRoot[] = {0, 0};
65090  u8 aCreateTbl[] = {0, 0};
65091
65092  int i;
65093  sqlite3 *db = pParse->db;
65094  Db *pDb;
65095  Vdbe *v = sqlite3GetVdbe(pParse);
65096  if( v==0 ) return;
65097  assert( sqlite3BtreeHoldsAllMutexes(db) );
65098  assert( sqlite3VdbeDb(v)==db );
65099  pDb = &db->aDb[iDb];
65100
65101  for(i=0; i<ArraySize(aTable); i++){
65102    const char *zTab = aTable[i].zName;
65103    Table *pStat;
65104    if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
65105      /* The sqlite_stat[12] table does not exist. Create it. Note that a
65106      ** side-effect of the CREATE TABLE statement is to leave the rootpage
65107      ** of the new table in register pParse->regRoot. This is important
65108      ** because the OpenWrite opcode below will be needing it. */
65109      sqlite3NestedParse(pParse,
65110          "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
65111      );
65112      aRoot[i] = pParse->regRoot;
65113      aCreateTbl[i] = 1;
65114    }else{
65115      /* The table already exists. If zWhere is not NULL, delete all entries
65116      ** associated with the table zWhere. If zWhere is NULL, delete the
65117      ** entire contents of the table. */
65118      aRoot[i] = pStat->tnum;
65119      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
65120      if( zWhere ){
65121        sqlite3NestedParse(pParse,
65122           "DELETE FROM %Q.%s WHERE tbl=%Q", pDb->zName, zTab, zWhere
65123        );
65124      }else{
65125        /* The sqlite_stat[12] table already exists.  Delete all rows. */
65126        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
65127      }
65128    }
65129  }
65130
65131  /* Open the sqlite_stat[12] tables for writing. */
65132  for(i=0; i<ArraySize(aTable); i++){
65133    sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
65134    sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
65135    sqlite3VdbeChangeP5(v, aCreateTbl[i]);
65136  }
65137}
65138
65139/*
65140** Generate code to do an analysis of all indices associated with
65141** a single table.
65142*/
65143static void analyzeOneTable(
65144  Parse *pParse,   /* Parser context */
65145  Table *pTab,     /* Table whose indices are to be analyzed */
65146  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
65147  int iMem         /* Available memory locations begin here */
65148){
65149  sqlite3 *db = pParse->db;    /* Database handle */
65150  Index *pIdx;                 /* An index to being analyzed */
65151  int iIdxCur;                 /* Cursor open on index being analyzed */
65152  Vdbe *v;                     /* The virtual machine being built up */
65153  int i;                       /* Loop counter */
65154  int topOfLoop;               /* The top of the loop */
65155  int endOfLoop;               /* The end of the loop */
65156  int addr;                    /* The address of an instruction */
65157  int iDb;                     /* Index of database containing pTab */
65158  int regTabname = iMem++;     /* Register containing table name */
65159  int regIdxname = iMem++;     /* Register containing index name */
65160  int regSampleno = iMem++;    /* Register containing next sample number */
65161  int regCol = iMem++;         /* Content of a column analyzed table */
65162  int regRec = iMem++;         /* Register holding completed record */
65163  int regTemp = iMem++;        /* Temporary use register */
65164  int regRowid = iMem++;       /* Rowid for the inserted record */
65165
65166#ifdef SQLITE_ENABLE_STAT2
65167  int regTemp2 = iMem++;       /* Temporary use register */
65168  int regSamplerecno = iMem++; /* Index of next sample to record */
65169  int regRecno = iMem++;       /* Current sample index */
65170  int regLast = iMem++;        /* Index of last sample to record */
65171  int regFirst = iMem++;       /* Index of first sample to record */
65172#endif
65173
65174  v = sqlite3GetVdbe(pParse);
65175  if( v==0 || NEVER(pTab==0) || pTab->pIndex==0 ){
65176    /* Do no analysis for tables that have no indices */
65177    return;
65178  }
65179  assert( sqlite3BtreeHoldsAllMutexes(db) );
65180  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
65181  assert( iDb>=0 );
65182#ifndef SQLITE_OMIT_AUTHORIZATION
65183  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
65184      db->aDb[iDb].zName ) ){
65185    return;
65186  }
65187#endif
65188
65189  /* Establish a read-lock on the table at the shared-cache level. */
65190  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
65191
65192  iIdxCur = pParse->nTab++;
65193  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
65194    int nCol = pIdx->nColumn;
65195    KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
65196
65197    if( iMem+1+(nCol*2)>pParse->nMem ){
65198      pParse->nMem = iMem+1+(nCol*2);
65199    }
65200
65201    /* Open a cursor to the index to be analyzed. */
65202    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
65203    sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
65204        (char *)pKey, P4_KEYINFO_HANDOFF);
65205    VdbeComment((v, "%s", pIdx->zName));
65206
65207    /* Populate the registers containing the table and index names. */
65208    if( pTab->pIndex==pIdx ){
65209      sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
65210    }
65211    sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
65212
65213#ifdef SQLITE_ENABLE_STAT2
65214
65215    /* If this iteration of the loop is generating code to analyze the
65216    ** first index in the pTab->pIndex list, then register regLast has
65217    ** not been populated. In this case populate it now.  */
65218    if( pTab->pIndex==pIdx ){
65219      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
65220      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
65221      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
65222
65223      sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
65224      sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
65225      addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
65226      sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
65227      sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
65228      sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
65229      sqlite3VdbeAddOp3(v, OP_Divide,  regTemp2, regLast, regLast);
65230      sqlite3VdbeJumpHere(v, addr);
65231    }
65232
65233    /* Zero the regSampleno and regRecno registers. */
65234    sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
65235    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
65236    sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
65237#endif
65238
65239    /* The block of memory cells initialized here is used as follows.
65240    **
65241    **    iMem:
65242    **        The total number of rows in the table.
65243    **
65244    **    iMem+1 .. iMem+nCol:
65245    **        Number of distinct entries in index considering the
65246    **        left-most N columns only, where N is between 1 and nCol,
65247    **        inclusive.
65248    **
65249    **    iMem+nCol+1 .. Mem+2*nCol:
65250    **        Previous value of indexed columns, from left to right.
65251    **
65252    ** Cells iMem through iMem+nCol are initialized to 0. The others are
65253    ** initialized to contain an SQL NULL.
65254    */
65255    for(i=0; i<=nCol; i++){
65256      sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
65257    }
65258    for(i=0; i<nCol; i++){
65259      sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
65260    }
65261
65262    /* Start the analysis loop. This loop runs through all the entries in
65263    ** the index b-tree.  */
65264    endOfLoop = sqlite3VdbeMakeLabel(v);
65265    sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
65266    topOfLoop = sqlite3VdbeCurrentAddr(v);
65267    sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
65268
65269    for(i=0; i<nCol; i++){
65270      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
65271#ifdef SQLITE_ENABLE_STAT2
65272      if( i==0 ){
65273        /* Check if the record that cursor iIdxCur points to contains a
65274        ** value that should be stored in the sqlite_stat2 table. If so,
65275        ** store it.  */
65276        int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
65277        assert( regTabname+1==regIdxname
65278             && regTabname+2==regSampleno
65279             && regTabname+3==regCol
65280        );
65281        sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
65282        sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
65283        sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
65284        sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
65285
65286        /* Calculate new values for regSamplerecno and regSampleno.
65287        **
65288        **   sampleno = sampleno + 1
65289        **   samplerecno = samplerecno+(remaining records)/(remaining samples)
65290        */
65291        sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
65292        sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
65293        sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
65294        sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
65295        sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
65296        sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
65297        sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
65298
65299        sqlite3VdbeJumpHere(v, ne);
65300        sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
65301      }
65302#endif
65303
65304      sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
65305      /**** TODO:  add collating sequence *****/
65306      sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
65307    }
65308    if( db->mallocFailed ){
65309      /* If a malloc failure has occurred, then the result of the expression
65310      ** passed as the second argument to the call to sqlite3VdbeJumpHere()
65311      ** below may be negative. Which causes an assert() to fail (or an
65312      ** out-of-bounds write if SQLITE_DEBUG is not defined).  */
65313      return;
65314    }
65315    sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
65316    for(i=0; i<nCol; i++){
65317      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-(nCol*2));
65318      sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
65319      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
65320    }
65321
65322    /* End of the analysis loop. */
65323    sqlite3VdbeResolveLabel(v, endOfLoop);
65324    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
65325    sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
65326
65327    /* Store the results in sqlite_stat1.
65328    **
65329    ** The result is a single row of the sqlite_stat1 table.  The first
65330    ** two columns are the names of the table and index.  The third column
65331    ** is a string composed of a list of integer statistics about the
65332    ** index.  The first integer in the list is the total number of entries
65333    ** in the index.  There is one additional integer in the list for each
65334    ** column of the table.  This additional integer is a guess of how many
65335    ** rows of the table the index will select.  If D is the count of distinct
65336    ** values and K is the total number of rows, then the integer is computed
65337    ** as:
65338    **
65339    **        I = (K+D-1)/D
65340    **
65341    ** If K==0 then no entry is made into the sqlite_stat1 table.
65342    ** If K>0 then it is always the case the D>0 so division by zero
65343    ** is never possible.
65344    */
65345    addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
65346    sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
65347    for(i=0; i<nCol; i++){
65348      sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
65349      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
65350      sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
65351      sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
65352      sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
65353      sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
65354      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
65355    }
65356    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
65357    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
65358    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
65359    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
65360    sqlite3VdbeJumpHere(v, addr);
65361  }
65362}
65363
65364/*
65365** Generate code that will cause the most recent index analysis to
65366** be laoded into internal hash tables where is can be used.
65367*/
65368static void loadAnalysis(Parse *pParse, int iDb){
65369  Vdbe *v = sqlite3GetVdbe(pParse);
65370  if( v ){
65371    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
65372  }
65373}
65374
65375/*
65376** Generate code that will do an analysis of an entire database
65377*/
65378static void analyzeDatabase(Parse *pParse, int iDb){
65379  sqlite3 *db = pParse->db;
65380  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
65381  HashElem *k;
65382  int iStatCur;
65383  int iMem;
65384
65385  sqlite3BeginWriteOperation(pParse, 0, iDb);
65386  iStatCur = pParse->nTab;
65387  pParse->nTab += 2;
65388  openStatTable(pParse, iDb, iStatCur, 0);
65389  iMem = pParse->nMem+1;
65390  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
65391    Table *pTab = (Table*)sqliteHashData(k);
65392    analyzeOneTable(pParse, pTab, iStatCur, iMem);
65393  }
65394  loadAnalysis(pParse, iDb);
65395}
65396
65397/*
65398** Generate code that will do an analysis of a single table in
65399** a database.
65400*/
65401static void analyzeTable(Parse *pParse, Table *pTab){
65402  int iDb;
65403  int iStatCur;
65404
65405  assert( pTab!=0 );
65406  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
65407  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
65408  sqlite3BeginWriteOperation(pParse, 0, iDb);
65409  iStatCur = pParse->nTab;
65410  pParse->nTab += 2;
65411  openStatTable(pParse, iDb, iStatCur, pTab->zName);
65412  analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
65413  loadAnalysis(pParse, iDb);
65414}
65415
65416/*
65417** Generate code for the ANALYZE command.  The parser calls this routine
65418** when it recognizes an ANALYZE command.
65419**
65420**        ANALYZE                            -- 1
65421**        ANALYZE  <database>                -- 2
65422**        ANALYZE  ?<database>.?<tablename>  -- 3
65423**
65424** Form 1 causes all indices in all attached databases to be analyzed.
65425** Form 2 analyzes all indices the single database named.
65426** Form 3 analyzes all indices associated with the named table.
65427*/
65428SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
65429  sqlite3 *db = pParse->db;
65430  int iDb;
65431  int i;
65432  char *z, *zDb;
65433  Table *pTab;
65434  Token *pTableName;
65435
65436  /* Read the database schema. If an error occurs, leave an error message
65437  ** and code in pParse and return NULL. */
65438  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
65439  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
65440    return;
65441  }
65442
65443  assert( pName2!=0 || pName1==0 );
65444  if( pName1==0 ){
65445    /* Form 1:  Analyze everything */
65446    for(i=0; i<db->nDb; i++){
65447      if( i==1 ) continue;  /* Do not analyze the TEMP database */
65448      analyzeDatabase(pParse, i);
65449    }
65450  }else if( pName2->n==0 ){
65451    /* Form 2:  Analyze the database or table named */
65452    iDb = sqlite3FindDb(db, pName1);
65453    if( iDb>=0 ){
65454      analyzeDatabase(pParse, iDb);
65455    }else{
65456      z = sqlite3NameFromToken(db, pName1);
65457      if( z ){
65458        pTab = sqlite3LocateTable(pParse, 0, z, 0);
65459        sqlite3DbFree(db, z);
65460        if( pTab ){
65461          analyzeTable(pParse, pTab);
65462        }
65463      }
65464    }
65465  }else{
65466    /* Form 3: Analyze the fully qualified table name */
65467    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
65468    if( iDb>=0 ){
65469      zDb = db->aDb[iDb].zName;
65470      z = sqlite3NameFromToken(db, pTableName);
65471      if( z ){
65472        pTab = sqlite3LocateTable(pParse, 0, z, zDb);
65473        sqlite3DbFree(db, z);
65474        if( pTab ){
65475          analyzeTable(pParse, pTab);
65476        }
65477      }
65478    }
65479  }
65480}
65481
65482/*
65483** Used to pass information from the analyzer reader through to the
65484** callback routine.
65485*/
65486typedef struct analysisInfo analysisInfo;
65487struct analysisInfo {
65488  sqlite3 *db;
65489  const char *zDatabase;
65490};
65491
65492/*
65493** This callback is invoked once for each index when reading the
65494** sqlite_stat1 table.
65495**
65496**     argv[0] = name of the index
65497**     argv[1] = results of analysis - on integer for each column
65498*/
65499static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
65500  analysisInfo *pInfo = (analysisInfo*)pData;
65501  Index *pIndex;
65502  int i, c;
65503  unsigned int v;
65504  const char *z;
65505
65506  assert( argc==2 );
65507  UNUSED_PARAMETER2(NotUsed, argc);
65508
65509  if( argv==0 || argv[0]==0 || argv[1]==0 ){
65510    return 0;
65511  }
65512  pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
65513  if( pIndex==0 ){
65514    return 0;
65515  }
65516  z = argv[1];
65517  for(i=0; *z && i<=pIndex->nColumn; i++){
65518    v = 0;
65519    while( (c=z[0])>='0' && c<='9' ){
65520      v = v*10 + c - '0';
65521      z++;
65522    }
65523    pIndex->aiRowEst[i] = v;
65524    if( *z==' ' ) z++;
65525  }
65526  return 0;
65527}
65528
65529/*
65530** If the Index.aSample variable is not NULL, delete the aSample[] array
65531** and its contents.
65532*/
65533SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index *pIdx){
65534#ifdef SQLITE_ENABLE_STAT2
65535  if( pIdx->aSample ){
65536    int j;
65537    sqlite3 *dbMem = pIdx->pTable->dbMem;
65538    for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
65539      IndexSample *p = &pIdx->aSample[j];
65540      if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
65541        sqlite3DbFree(pIdx->pTable->dbMem, p->u.z);
65542      }
65543    }
65544    sqlite3DbFree(dbMem, pIdx->aSample);
65545    pIdx->aSample = 0;
65546  }
65547#else
65548  UNUSED_PARAMETER(pIdx);
65549#endif
65550}
65551
65552/*
65553** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
65554** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
65555** arrays. The contents of sqlite_stat2 are used to populate the
65556** Index.aSample[] arrays.
65557**
65558** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
65559** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined
65560** during compilation and the sqlite_stat2 table is present, no data is
65561** read from it.
65562**
65563** If SQLITE_ENABLE_STAT2 was defined during compilation and the
65564** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
65565** returned. However, in this case, data is read from the sqlite_stat1
65566** table (if it is present) before returning.
65567**
65568** If an OOM error occurs, this function always sets db->mallocFailed.
65569** This means if the caller does not care about other errors, the return
65570** code may be ignored.
65571*/
65572SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
65573  analysisInfo sInfo;
65574  HashElem *i;
65575  char *zSql;
65576  int rc;
65577
65578  assert( iDb>=0 && iDb<db->nDb );
65579  assert( db->aDb[iDb].pBt!=0 );
65580  assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
65581
65582  /* Clear any prior statistics */
65583  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
65584    Index *pIdx = sqliteHashData(i);
65585    sqlite3DefaultRowEst(pIdx);
65586    sqlite3DeleteIndexSamples(pIdx);
65587  }
65588
65589  /* Check to make sure the sqlite_stat1 table exists */
65590  sInfo.db = db;
65591  sInfo.zDatabase = db->aDb[iDb].zName;
65592  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
65593    return SQLITE_ERROR;
65594  }
65595
65596  /* Load new statistics out of the sqlite_stat1 table */
65597  zSql = sqlite3MPrintf(db,
65598      "SELECT idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
65599  if( zSql==0 ){
65600    rc = SQLITE_NOMEM;
65601  }else{
65602    rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
65603    sqlite3DbFree(db, zSql);
65604  }
65605
65606
65607  /* Load the statistics from the sqlite_stat2 table. */
65608#ifdef SQLITE_ENABLE_STAT2
65609  if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
65610    rc = SQLITE_ERROR;
65611  }
65612  if( rc==SQLITE_OK ){
65613    sqlite3_stmt *pStmt = 0;
65614
65615    zSql = sqlite3MPrintf(db,
65616        "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
65617    if( !zSql ){
65618      rc = SQLITE_NOMEM;
65619    }else{
65620      rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
65621      sqlite3DbFree(db, zSql);
65622    }
65623
65624    if( rc==SQLITE_OK ){
65625      while( sqlite3_step(pStmt)==SQLITE_ROW ){
65626        char *zIndex = (char *)sqlite3_column_text(pStmt, 0);
65627        Index *pIdx = sqlite3FindIndex(db, zIndex, sInfo.zDatabase);
65628        if( pIdx ){
65629          int iSample = sqlite3_column_int(pStmt, 1);
65630          sqlite3 *dbMem = pIdx->pTable->dbMem;
65631          assert( dbMem==db || dbMem==0 );
65632          if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
65633            int eType = sqlite3_column_type(pStmt, 2);
65634
65635            if( pIdx->aSample==0 ){
65636              static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
65637              pIdx->aSample = (IndexSample *)sqlite3DbMallocZero(dbMem, sz);
65638              if( pIdx->aSample==0 ){
65639                db->mallocFailed = 1;
65640                break;
65641              }
65642            }
65643
65644            assert( pIdx->aSample );
65645            {
65646              IndexSample *pSample = &pIdx->aSample[iSample];
65647              pSample->eType = (u8)eType;
65648              if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
65649                pSample->u.r = sqlite3_column_double(pStmt, 2);
65650              }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
65651                const char *z = (const char *)(
65652                    (eType==SQLITE_BLOB) ?
65653                    sqlite3_column_blob(pStmt, 2):
65654                    sqlite3_column_text(pStmt, 2)
65655                );
65656                int n = sqlite3_column_bytes(pStmt, 2);
65657                if( n>24 ){
65658                  n = 24;
65659                }
65660                pSample->nByte = (u8)n;
65661                pSample->u.z = sqlite3DbMallocRaw(dbMem, n);
65662                if( pSample->u.z ){
65663                  memcpy(pSample->u.z, z, n);
65664                }else{
65665                  db->mallocFailed = 1;
65666                  break;
65667                }
65668              }
65669            }
65670          }
65671        }
65672      }
65673      rc = sqlite3_finalize(pStmt);
65674    }
65675  }
65676#endif
65677
65678  if( rc==SQLITE_NOMEM ){
65679    db->mallocFailed = 1;
65680  }
65681  return rc;
65682}
65683
65684
65685#endif /* SQLITE_OMIT_ANALYZE */
65686
65687/************** End of analyze.c *********************************************/
65688/************** Begin file attach.c ******************************************/
65689/*
65690** 2003 April 6
65691**
65692** The author disclaims copyright to this source code.  In place of
65693** a legal notice, here is a blessing:
65694**
65695**    May you do good and not evil.
65696**    May you find forgiveness for yourself and forgive others.
65697**    May you share freely, never taking more than you give.
65698**
65699*************************************************************************
65700** This file contains code used to implement the ATTACH and DETACH commands.
65701*/
65702
65703#ifndef SQLITE_OMIT_ATTACH
65704/*
65705** Resolve an expression that was part of an ATTACH or DETACH statement. This
65706** is slightly different from resolving a normal SQL expression, because simple
65707** identifiers are treated as strings, not possible column names or aliases.
65708**
65709** i.e. if the parser sees:
65710**
65711**     ATTACH DATABASE abc AS def
65712**
65713** it treats the two expressions as literal strings 'abc' and 'def' instead of
65714** looking for columns of the same name.
65715**
65716** This only applies to the root node of pExpr, so the statement:
65717**
65718**     ATTACH DATABASE abc||def AS 'db2'
65719**
65720** will fail because neither abc or def can be resolved.
65721*/
65722static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
65723{
65724  int rc = SQLITE_OK;
65725  if( pExpr ){
65726    if( pExpr->op!=TK_ID ){
65727      rc = sqlite3ResolveExprNames(pName, pExpr);
65728      if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
65729        sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
65730        return SQLITE_ERROR;
65731      }
65732    }else{
65733      pExpr->op = TK_STRING;
65734    }
65735  }
65736  return rc;
65737}
65738
65739/*
65740** An SQL user-function registered to do the work of an ATTACH statement. The
65741** three arguments to the function come directly from an attach statement:
65742**
65743**     ATTACH DATABASE x AS y KEY z
65744**
65745**     SELECT sqlite_attach(x, y, z)
65746**
65747** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
65748** third argument.
65749*/
65750static void attachFunc(
65751  sqlite3_context *context,
65752  int NotUsed,
65753  sqlite3_value **argv
65754){
65755  int i;
65756  int rc = 0;
65757  sqlite3 *db = sqlite3_context_db_handle(context);
65758  const char *zName;
65759  const char *zFile;
65760  Db *aNew;
65761  char *zErrDyn = 0;
65762
65763  UNUSED_PARAMETER(NotUsed);
65764
65765  zFile = (const char *)sqlite3_value_text(argv[0]);
65766  zName = (const char *)sqlite3_value_text(argv[1]);
65767  if( zFile==0 ) zFile = "";
65768  if( zName==0 ) zName = "";
65769
65770  /* Check for the following errors:
65771  **
65772  **     * Too many attached databases,
65773  **     * Transaction currently open
65774  **     * Specified database name already being used.
65775  */
65776  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
65777    zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
65778      db->aLimit[SQLITE_LIMIT_ATTACHED]
65779    );
65780    goto attach_error;
65781  }
65782  if( !db->autoCommit ){
65783    zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
65784    goto attach_error;
65785  }
65786  for(i=0; i<db->nDb; i++){
65787    char *z = db->aDb[i].zName;
65788    assert( z && zName );
65789    if( sqlite3StrICmp(z, zName)==0 ){
65790      zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
65791      goto attach_error;
65792    }
65793  }
65794
65795  /* Allocate the new entry in the db->aDb[] array and initialise the schema
65796  ** hash tables.
65797  */
65798  if( db->aDb==db->aDbStatic ){
65799    aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
65800    if( aNew==0 ) return;
65801    memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
65802  }else{
65803    aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
65804    if( aNew==0 ) return;
65805  }
65806  db->aDb = aNew;
65807  aNew = &db->aDb[db->nDb];
65808  memset(aNew, 0, sizeof(*aNew));
65809
65810  /* Open the database file. If the btree is successfully opened, use
65811  ** it to obtain the database schema. At this point the schema may
65812  ** or may not be initialised.
65813  */
65814  rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
65815                           db->openFlags | SQLITE_OPEN_MAIN_DB | SQLITE_OPEN_CREATE /* Android Change */,
65816                           &aNew->pBt);
65817  db->nDb++;
65818  if( rc==SQLITE_CONSTRAINT ){
65819    rc = SQLITE_ERROR;
65820    zErrDyn = sqlite3MPrintf(db, "database is already attached");
65821  }else if( rc==SQLITE_OK ){
65822    Pager *pPager;
65823    aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
65824    if( !aNew->pSchema ){
65825      rc = SQLITE_NOMEM;
65826    }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
65827      zErrDyn = sqlite3MPrintf(db,
65828        "attached databases must use the same text encoding as main database");
65829      rc = SQLITE_ERROR;
65830    }
65831    pPager = sqlite3BtreePager(aNew->pBt);
65832    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
65833    sqlite3PagerJournalMode(pPager, db->dfltJournalMode);
65834  }
65835  aNew->safety_level = 3;
65836  aNew->zName = sqlite3DbStrDup(db, zName);
65837  if( rc==SQLITE_OK && aNew->zName==0 ){
65838    rc = SQLITE_NOMEM;
65839  }
65840
65841
65842#if SQLITE_HAS_CODEC
65843  if( rc==SQLITE_OK ){
65844    extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
65845    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
65846    int nKey;
65847    char *zKey;
65848    int t = sqlite3_value_type(argv[2]);
65849    switch( t ){
65850      case SQLITE_INTEGER:
65851      case SQLITE_FLOAT:
65852        zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
65853        rc = SQLITE_ERROR;
65854        break;
65855
65856      case SQLITE_TEXT:
65857      case SQLITE_BLOB:
65858        nKey = sqlite3_value_bytes(argv[2]);
65859        zKey = (char *)sqlite3_value_blob(argv[2]);
65860        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
65861        break;
65862
65863      case SQLITE_NULL:
65864        /* No key specified.  Use the key from the main database */
65865        sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
65866        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
65867        break;
65868    }
65869  }
65870#endif
65871
65872  /* If the file was opened successfully, read the schema for the new database.
65873  ** If this fails, or if opening the file failed, then close the file and
65874  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
65875  ** we found it.
65876  */
65877  if( rc==SQLITE_OK ){
65878    sqlite3BtreeEnterAll(db);
65879    rc = sqlite3Init(db, &zErrDyn);
65880    sqlite3BtreeLeaveAll(db);
65881  }
65882  if( rc ){
65883    int iDb = db->nDb - 1;
65884    assert( iDb>=2 );
65885    if( db->aDb[iDb].pBt ){
65886      sqlite3BtreeClose(db->aDb[iDb].pBt);
65887      db->aDb[iDb].pBt = 0;
65888      db->aDb[iDb].pSchema = 0;
65889    }
65890    sqlite3ResetInternalSchema(db, 0);
65891    db->nDb = iDb;
65892    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
65893      db->mallocFailed = 1;
65894      sqlite3DbFree(db, zErrDyn);
65895      zErrDyn = sqlite3MPrintf(db, "out of memory");
65896    }else if( zErrDyn==0 ){
65897      zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
65898    }
65899    goto attach_error;
65900  }
65901
65902  return;
65903
65904attach_error:
65905  /* Return an error if we get here */
65906  if( zErrDyn ){
65907    sqlite3_result_error(context, zErrDyn, -1);
65908    sqlite3DbFree(db, zErrDyn);
65909  }
65910  if( rc ) sqlite3_result_error_code(context, rc);
65911}
65912
65913/*
65914** An SQL user-function registered to do the work of an DETACH statement. The
65915** three arguments to the function come directly from a detach statement:
65916**
65917**     DETACH DATABASE x
65918**
65919**     SELECT sqlite_detach(x)
65920*/
65921static void detachFunc(
65922  sqlite3_context *context,
65923  int NotUsed,
65924  sqlite3_value **argv
65925){
65926  const char *zName = (const char *)sqlite3_value_text(argv[0]);
65927  sqlite3 *db = sqlite3_context_db_handle(context);
65928  int i;
65929  Db *pDb = 0;
65930  char zErr[128];
65931
65932  UNUSED_PARAMETER(NotUsed);
65933
65934  if( zName==0 ) zName = "";
65935  for(i=0; i<db->nDb; i++){
65936    pDb = &db->aDb[i];
65937    if( pDb->pBt==0 ) continue;
65938    if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
65939  }
65940
65941  if( i>=db->nDb ){
65942    sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
65943    goto detach_error;
65944  }
65945  if( i<2 ){
65946    sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
65947    goto detach_error;
65948  }
65949  if( !db->autoCommit ){
65950    sqlite3_snprintf(sizeof(zErr), zErr,
65951                     "cannot DETACH database within transaction");
65952    goto detach_error;
65953  }
65954  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
65955    sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
65956    goto detach_error;
65957  }
65958
65959  sqlite3BtreeClose(pDb->pBt);
65960  pDb->pBt = 0;
65961  pDb->pSchema = 0;
65962  sqlite3ResetInternalSchema(db, 0);
65963  return;
65964
65965detach_error:
65966  sqlite3_result_error(context, zErr, -1);
65967}
65968
65969/*
65970** This procedure generates VDBE code for a single invocation of either the
65971** sqlite_detach() or sqlite_attach() SQL user functions.
65972*/
65973static void codeAttach(
65974  Parse *pParse,       /* The parser context */
65975  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
65976  FuncDef *pFunc,      /* FuncDef wrapper for detachFunc() or attachFunc() */
65977  Expr *pAuthArg,      /* Expression to pass to authorization callback */
65978  Expr *pFilename,     /* Name of database file */
65979  Expr *pDbname,       /* Name of the database to use internally */
65980  Expr *pKey           /* Database key for encryption extension */
65981){
65982  int rc;
65983  NameContext sName;
65984  Vdbe *v;
65985  sqlite3* db = pParse->db;
65986  int regArgs;
65987
65988  memset(&sName, 0, sizeof(NameContext));
65989  sName.pParse = pParse;
65990
65991  if(
65992      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
65993      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
65994      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
65995  ){
65996    pParse->nErr++;
65997    goto attach_end;
65998  }
65999
66000#ifndef SQLITE_OMIT_AUTHORIZATION
66001  if( pAuthArg ){
66002    char *zAuthArg = pAuthArg->u.zToken;
66003    if( NEVER(zAuthArg==0) ){
66004      goto attach_end;
66005    }
66006    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
66007    if(rc!=SQLITE_OK ){
66008      goto attach_end;
66009    }
66010  }
66011#endif /* SQLITE_OMIT_AUTHORIZATION */
66012
66013
66014  v = sqlite3GetVdbe(pParse);
66015  regArgs = sqlite3GetTempRange(pParse, 4);
66016  sqlite3ExprCode(pParse, pFilename, regArgs);
66017  sqlite3ExprCode(pParse, pDbname, regArgs+1);
66018  sqlite3ExprCode(pParse, pKey, regArgs+2);
66019
66020  assert( v || db->mallocFailed );
66021  if( v ){
66022    sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
66023    assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
66024    sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
66025    sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
66026
66027    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
66028    ** statement only). For DETACH, set it to false (expire all existing
66029    ** statements).
66030    */
66031    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
66032  }
66033
66034attach_end:
66035  sqlite3ExprDelete(db, pFilename);
66036  sqlite3ExprDelete(db, pDbname);
66037  sqlite3ExprDelete(db, pKey);
66038}
66039
66040/*
66041** Called by the parser to compile a DETACH statement.
66042**
66043**     DETACH pDbname
66044*/
66045SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
66046  static FuncDef detach_func = {
66047    1,                /* nArg */
66048    SQLITE_UTF8,      /* iPrefEnc */
66049    0,                /* flags */
66050    0,                /* pUserData */
66051    0,                /* pNext */
66052    detachFunc,       /* xFunc */
66053    0,                /* xStep */
66054    0,                /* xFinalize */
66055    "sqlite_detach",  /* zName */
66056    0                 /* pHash */
66057  };
66058  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
66059}
66060
66061/*
66062** Called by the parser to compile an ATTACH statement.
66063**
66064**     ATTACH p AS pDbname KEY pKey
66065*/
66066SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
66067  static FuncDef attach_func = {
66068    3,                /* nArg */
66069    SQLITE_UTF8,      /* iPrefEnc */
66070    0,                /* flags */
66071    0,                /* pUserData */
66072    0,                /* pNext */
66073    attachFunc,       /* xFunc */
66074    0,                /* xStep */
66075    0,                /* xFinalize */
66076    "sqlite_attach",  /* zName */
66077    0                 /* pHash */
66078  };
66079  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
66080}
66081#endif /* SQLITE_OMIT_ATTACH */
66082
66083/*
66084** Initialize a DbFixer structure.  This routine must be called prior
66085** to passing the structure to one of the sqliteFixAAAA() routines below.
66086**
66087** The return value indicates whether or not fixation is required.  TRUE
66088** means we do need to fix the database references, FALSE means we do not.
66089*/
66090SQLITE_PRIVATE int sqlite3FixInit(
66091  DbFixer *pFix,      /* The fixer to be initialized */
66092  Parse *pParse,      /* Error messages will be written here */
66093  int iDb,            /* This is the database that must be used */
66094  const char *zType,  /* "view", "trigger", or "index" */
66095  const Token *pName  /* Name of the view, trigger, or index */
66096){
66097  sqlite3 *db;
66098
66099  if( NEVER(iDb<0) || iDb==1 ) return 0;
66100  db = pParse->db;
66101  assert( db->nDb>iDb );
66102  pFix->pParse = pParse;
66103  pFix->zDb = db->aDb[iDb].zName;
66104  pFix->zType = zType;
66105  pFix->pName = pName;
66106  return 1;
66107}
66108
66109/*
66110** The following set of routines walk through the parse tree and assign
66111** a specific database to all table references where the database name
66112** was left unspecified in the original SQL statement.  The pFix structure
66113** must have been initialized by a prior call to sqlite3FixInit().
66114**
66115** These routines are used to make sure that an index, trigger, or
66116** view in one database does not refer to objects in a different database.
66117** (Exception: indices, triggers, and views in the TEMP database are
66118** allowed to refer to anything.)  If a reference is explicitly made
66119** to an object in a different database, an error message is added to
66120** pParse->zErrMsg and these routines return non-zero.  If everything
66121** checks out, these routines return 0.
66122*/
66123SQLITE_PRIVATE int sqlite3FixSrcList(
66124  DbFixer *pFix,       /* Context of the fixation */
66125  SrcList *pList       /* The Source list to check and modify */
66126){
66127  int i;
66128  const char *zDb;
66129  struct SrcList_item *pItem;
66130
66131  if( NEVER(pList==0) ) return 0;
66132  zDb = pFix->zDb;
66133  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
66134    if( pItem->zDatabase==0 ){
66135      pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
66136    }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
66137      sqlite3ErrorMsg(pFix->pParse,
66138         "%s %T cannot reference objects in database %s",
66139         pFix->zType, pFix->pName, pItem->zDatabase);
66140      return 1;
66141    }
66142#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
66143    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
66144    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
66145#endif
66146  }
66147  return 0;
66148}
66149#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
66150SQLITE_PRIVATE int sqlite3FixSelect(
66151  DbFixer *pFix,       /* Context of the fixation */
66152  Select *pSelect      /* The SELECT statement to be fixed to one database */
66153){
66154  while( pSelect ){
66155    if( sqlite3FixExprList(pFix, pSelect->pEList) ){
66156      return 1;
66157    }
66158    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
66159      return 1;
66160    }
66161    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
66162      return 1;
66163    }
66164    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
66165      return 1;
66166    }
66167    pSelect = pSelect->pPrior;
66168  }
66169  return 0;
66170}
66171SQLITE_PRIVATE int sqlite3FixExpr(
66172  DbFixer *pFix,     /* Context of the fixation */
66173  Expr *pExpr        /* The expression to be fixed to one database */
66174){
66175  while( pExpr ){
66176    if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
66177    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
66178      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
66179    }else{
66180      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
66181    }
66182    if( sqlite3FixExpr(pFix, pExpr->pRight) ){
66183      return 1;
66184    }
66185    pExpr = pExpr->pLeft;
66186  }
66187  return 0;
66188}
66189SQLITE_PRIVATE int sqlite3FixExprList(
66190  DbFixer *pFix,     /* Context of the fixation */
66191  ExprList *pList    /* The expression to be fixed to one database */
66192){
66193  int i;
66194  struct ExprList_item *pItem;
66195  if( pList==0 ) return 0;
66196  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
66197    if( sqlite3FixExpr(pFix, pItem->pExpr) ){
66198      return 1;
66199    }
66200  }
66201  return 0;
66202}
66203#endif
66204
66205#ifndef SQLITE_OMIT_TRIGGER
66206SQLITE_PRIVATE int sqlite3FixTriggerStep(
66207  DbFixer *pFix,     /* Context of the fixation */
66208  TriggerStep *pStep /* The trigger step be fixed to one database */
66209){
66210  while( pStep ){
66211    if( sqlite3FixSelect(pFix, pStep->pSelect) ){
66212      return 1;
66213    }
66214    if( sqlite3FixExpr(pFix, pStep->pWhere) ){
66215      return 1;
66216    }
66217    if( sqlite3FixExprList(pFix, pStep->pExprList) ){
66218      return 1;
66219    }
66220    pStep = pStep->pNext;
66221  }
66222  return 0;
66223}
66224#endif
66225
66226/************** End of attach.c **********************************************/
66227/************** Begin file auth.c ********************************************/
66228/*
66229** 2003 January 11
66230**
66231** The author disclaims copyright to this source code.  In place of
66232** a legal notice, here is a blessing:
66233**
66234**    May you do good and not evil.
66235**    May you find forgiveness for yourself and forgive others.
66236**    May you share freely, never taking more than you give.
66237**
66238*************************************************************************
66239** This file contains code used to implement the sqlite3_set_authorizer()
66240** API.  This facility is an optional feature of the library.  Embedded
66241** systems that do not need this facility may omit it by recompiling
66242** the library with -DSQLITE_OMIT_AUTHORIZATION=1
66243*/
66244
66245/*
66246** All of the code in this file may be omitted by defining a single
66247** macro.
66248*/
66249#ifndef SQLITE_OMIT_AUTHORIZATION
66250
66251/*
66252** Set or clear the access authorization function.
66253**
66254** The access authorization function is be called during the compilation
66255** phase to verify that the user has read and/or write access permission on
66256** various fields of the database.  The first argument to the auth function
66257** is a copy of the 3rd argument to this routine.  The second argument
66258** to the auth function is one of these constants:
66259**
66260**       SQLITE_CREATE_INDEX
66261**       SQLITE_CREATE_TABLE
66262**       SQLITE_CREATE_TEMP_INDEX
66263**       SQLITE_CREATE_TEMP_TABLE
66264**       SQLITE_CREATE_TEMP_TRIGGER
66265**       SQLITE_CREATE_TEMP_VIEW
66266**       SQLITE_CREATE_TRIGGER
66267**       SQLITE_CREATE_VIEW
66268**       SQLITE_DELETE
66269**       SQLITE_DROP_INDEX
66270**       SQLITE_DROP_TABLE
66271**       SQLITE_DROP_TEMP_INDEX
66272**       SQLITE_DROP_TEMP_TABLE
66273**       SQLITE_DROP_TEMP_TRIGGER
66274**       SQLITE_DROP_TEMP_VIEW
66275**       SQLITE_DROP_TRIGGER
66276**       SQLITE_DROP_VIEW
66277**       SQLITE_INSERT
66278**       SQLITE_PRAGMA
66279**       SQLITE_READ
66280**       SQLITE_SELECT
66281**       SQLITE_TRANSACTION
66282**       SQLITE_UPDATE
66283**
66284** The third and fourth arguments to the auth function are the name of
66285** the table and the column that are being accessed.  The auth function
66286** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
66287** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
66288** means that the SQL statement will never-run - the sqlite3_exec() call
66289** will return with an error.  SQLITE_IGNORE means that the SQL statement
66290** should run but attempts to read the specified column will return NULL
66291** and attempts to write the column will be ignored.
66292**
66293** Setting the auth function to NULL disables this hook.  The default
66294** setting of the auth function is NULL.
66295*/
66296SQLITE_API int sqlite3_set_authorizer(
66297  sqlite3 *db,
66298  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
66299  void *pArg
66300){
66301  sqlite3_mutex_enter(db->mutex);
66302  db->xAuth = xAuth;
66303  db->pAuthArg = pArg;
66304  sqlite3ExpirePreparedStatements(db);
66305  sqlite3_mutex_leave(db->mutex);
66306  return SQLITE_OK;
66307}
66308
66309/*
66310** Write an error message into pParse->zErrMsg that explains that the
66311** user-supplied authorization function returned an illegal value.
66312*/
66313static void sqliteAuthBadReturnCode(Parse *pParse){
66314  sqlite3ErrorMsg(pParse, "authorizer malfunction");
66315  pParse->rc = SQLITE_ERROR;
66316}
66317
66318/*
66319** Invoke the authorization callback for permission to read column zCol from
66320** table zTab in database zDb. This function assumes that an authorization
66321** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
66322**
66323** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
66324** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
66325** is treated as SQLITE_DENY. In this case an error is left in pParse.
66326*/
66327SQLITE_PRIVATE int sqlite3AuthReadCol(
66328  Parse *pParse,                  /* The parser context */
66329  const char *zTab,               /* Table name */
66330  const char *zCol,               /* Column name */
66331  int iDb                         /* Index of containing database. */
66332){
66333  sqlite3 *db = pParse->db;       /* Database handle */
66334  char *zDb = db->aDb[iDb].zName; /* Name of attached database */
66335  int rc;                         /* Auth callback return code */
66336
66337  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
66338  if( rc==SQLITE_DENY ){
66339    if( db->nDb>2 || iDb!=0 ){
66340      sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
66341    }else{
66342      sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
66343    }
66344    pParse->rc = SQLITE_AUTH;
66345  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
66346    sqliteAuthBadReturnCode(pParse);
66347  }
66348  return rc;
66349}
66350
66351/*
66352** The pExpr should be a TK_COLUMN expression.  The table referred to
66353** is in pTabList or else it is the NEW or OLD table of a trigger.
66354** Check to see if it is OK to read this particular column.
66355**
66356** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
66357** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
66358** then generate an error.
66359*/
66360SQLITE_PRIVATE void sqlite3AuthRead(
66361  Parse *pParse,        /* The parser context */
66362  Expr *pExpr,          /* The expression to check authorization on */
66363  Schema *pSchema,      /* The schema of the expression */
66364  SrcList *pTabList     /* All table that pExpr might refer to */
66365){
66366  sqlite3 *db = pParse->db;
66367  Table *pTab = 0;      /* The table being read */
66368  const char *zCol;     /* Name of the column of the table */
66369  int iSrc;             /* Index in pTabList->a[] of table being read */
66370  int iDb;              /* The index of the database the expression refers to */
66371  int iCol;             /* Index of column in table */
66372
66373  if( db->xAuth==0 ) return;
66374  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
66375  if( iDb<0 ){
66376    /* An attempt to read a column out of a subquery or other
66377    ** temporary table. */
66378    return;
66379  }
66380
66381  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
66382  if( pExpr->op==TK_TRIGGER ){
66383    pTab = pParse->pTriggerTab;
66384  }else{
66385    assert( pTabList );
66386    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
66387      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
66388        pTab = pTabList->a[iSrc].pTab;
66389        break;
66390      }
66391    }
66392  }
66393  iCol = pExpr->iColumn;
66394  if( NEVER(pTab==0) ) return;
66395
66396  if( iCol>=0 ){
66397    assert( iCol<pTab->nCol );
66398    zCol = pTab->aCol[iCol].zName;
66399  }else if( pTab->iPKey>=0 ){
66400    assert( pTab->iPKey<pTab->nCol );
66401    zCol = pTab->aCol[pTab->iPKey].zName;
66402  }else{
66403    zCol = "ROWID";
66404  }
66405  assert( iDb>=0 && iDb<db->nDb );
66406  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
66407    pExpr->op = TK_NULL;
66408  }
66409}
66410
66411/*
66412** Do an authorization check using the code and arguments given.  Return
66413** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
66414** is returned, then the error count and error message in pParse are
66415** modified appropriately.
66416*/
66417SQLITE_PRIVATE int sqlite3AuthCheck(
66418  Parse *pParse,
66419  int code,
66420  const char *zArg1,
66421  const char *zArg2,
66422  const char *zArg3
66423){
66424  sqlite3 *db = pParse->db;
66425  int rc;
66426
66427  /* Don't do any authorization checks if the database is initialising
66428  ** or if the parser is being invoked from within sqlite3_declare_vtab.
66429  */
66430  if( db->init.busy || IN_DECLARE_VTAB ){
66431    return SQLITE_OK;
66432  }
66433
66434  if( db->xAuth==0 ){
66435    return SQLITE_OK;
66436  }
66437  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
66438  if( rc==SQLITE_DENY ){
66439    sqlite3ErrorMsg(pParse, "not authorized");
66440    pParse->rc = SQLITE_AUTH;
66441  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
66442    rc = SQLITE_DENY;
66443    sqliteAuthBadReturnCode(pParse);
66444  }
66445  return rc;
66446}
66447
66448/*
66449** Push an authorization context.  After this routine is called, the
66450** zArg3 argument to authorization callbacks will be zContext until
66451** popped.  Or if pParse==0, this routine is a no-op.
66452*/
66453SQLITE_PRIVATE void sqlite3AuthContextPush(
66454  Parse *pParse,
66455  AuthContext *pContext,
66456  const char *zContext
66457){
66458  assert( pParse );
66459  pContext->pParse = pParse;
66460  pContext->zAuthContext = pParse->zAuthContext;
66461  pParse->zAuthContext = zContext;
66462}
66463
66464/*
66465** Pop an authorization context that was previously pushed
66466** by sqlite3AuthContextPush
66467*/
66468SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
66469  if( pContext->pParse ){
66470    pContext->pParse->zAuthContext = pContext->zAuthContext;
66471    pContext->pParse = 0;
66472  }
66473}
66474
66475#endif /* SQLITE_OMIT_AUTHORIZATION */
66476
66477/************** End of auth.c ************************************************/
66478/************** Begin file build.c *******************************************/
66479/*
66480** 2001 September 15
66481**
66482** The author disclaims copyright to this source code.  In place of
66483** a legal notice, here is a blessing:
66484**
66485**    May you do good and not evil.
66486**    May you find forgiveness for yourself and forgive others.
66487**    May you share freely, never taking more than you give.
66488**
66489*************************************************************************
66490** This file contains C code routines that are called by the SQLite parser
66491** when syntax rules are reduced.  The routines in this file handle the
66492** following kinds of SQL syntax:
66493**
66494**     CREATE TABLE
66495**     DROP TABLE
66496**     CREATE INDEX
66497**     DROP INDEX
66498**     creating ID lists
66499**     BEGIN TRANSACTION
66500**     COMMIT
66501**     ROLLBACK
66502*/
66503
66504/*
66505** This routine is called when a new SQL statement is beginning to
66506** be parsed.  Initialize the pParse structure as needed.
66507*/
66508SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
66509  pParse->explain = (u8)explainFlag;
66510  pParse->nVar = 0;
66511}
66512
66513#ifndef SQLITE_OMIT_SHARED_CACHE
66514/*
66515** The TableLock structure is only used by the sqlite3TableLock() and
66516** codeTableLocks() functions.
66517*/
66518struct TableLock {
66519  int iDb;             /* The database containing the table to be locked */
66520  int iTab;            /* The root page of the table to be locked */
66521  u8 isWriteLock;      /* True for write lock.  False for a read lock */
66522  const char *zName;   /* Name of the table */
66523};
66524
66525/*
66526** Record the fact that we want to lock a table at run-time.
66527**
66528** The table to be locked has root page iTab and is found in database iDb.
66529** A read or a write lock can be taken depending on isWritelock.
66530**
66531** This routine just records the fact that the lock is desired.  The
66532** code to make the lock occur is generated by a later call to
66533** codeTableLocks() which occurs during sqlite3FinishCoding().
66534*/
66535SQLITE_PRIVATE void sqlite3TableLock(
66536  Parse *pParse,     /* Parsing context */
66537  int iDb,           /* Index of the database containing the table to lock */
66538  int iTab,          /* Root page number of the table to be locked */
66539  u8 isWriteLock,    /* True for a write lock */
66540  const char *zName  /* Name of the table to be locked */
66541){
66542  Parse *pToplevel = sqlite3ParseToplevel(pParse);
66543  int i;
66544  int nBytes;
66545  TableLock *p;
66546  assert( iDb>=0 );
66547
66548  for(i=0; i<pToplevel->nTableLock; i++){
66549    p = &pToplevel->aTableLock[i];
66550    if( p->iDb==iDb && p->iTab==iTab ){
66551      p->isWriteLock = (p->isWriteLock || isWriteLock);
66552      return;
66553    }
66554  }
66555
66556  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
66557  pToplevel->aTableLock =
66558      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
66559  if( pToplevel->aTableLock ){
66560    p = &pToplevel->aTableLock[pToplevel->nTableLock++];
66561    p->iDb = iDb;
66562    p->iTab = iTab;
66563    p->isWriteLock = isWriteLock;
66564    p->zName = zName;
66565  }else{
66566    pToplevel->nTableLock = 0;
66567    pToplevel->db->mallocFailed = 1;
66568  }
66569}
66570
66571/*
66572** Code an OP_TableLock instruction for each table locked by the
66573** statement (configured by calls to sqlite3TableLock()).
66574*/
66575static void codeTableLocks(Parse *pParse){
66576  int i;
66577  Vdbe *pVdbe;
66578
66579  pVdbe = sqlite3GetVdbe(pParse);
66580  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
66581
66582  for(i=0; i<pParse->nTableLock; i++){
66583    TableLock *p = &pParse->aTableLock[i];
66584    int p1 = p->iDb;
66585    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
66586                      p->zName, P4_STATIC);
66587  }
66588}
66589#else
66590  #define codeTableLocks(x)
66591#endif
66592
66593/*
66594** This routine is called after a single SQL statement has been
66595** parsed and a VDBE program to execute that statement has been
66596** prepared.  This routine puts the finishing touches on the
66597** VDBE program and resets the pParse structure for the next
66598** parse.
66599**
66600** Note that if an error occurred, it might be the case that
66601** no VDBE code was generated.
66602*/
66603SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
66604  sqlite3 *db;
66605  Vdbe *v;
66606
66607  db = pParse->db;
66608  if( db->mallocFailed ) return;
66609  if( pParse->nested ) return;
66610  if( pParse->nErr ) return;
66611
66612  /* Begin by generating some termination code at the end of the
66613  ** vdbe program
66614  */
66615  v = sqlite3GetVdbe(pParse);
66616  assert( !pParse->isMultiWrite
66617       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
66618  if( v ){
66619    sqlite3VdbeAddOp0(v, OP_Halt);
66620
66621    /* The cookie mask contains one bit for each database file open.
66622    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
66623    ** set for each database that is used.  Generate code to start a
66624    ** transaction on each used database and to verify the schema cookie
66625    ** on each used database.
66626    */
66627    if( pParse->cookieGoto>0 ){
66628      u32 mask;
66629      int iDb;
66630      sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
66631      for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
66632        if( (mask & pParse->cookieMask)==0 ) continue;
66633        sqlite3VdbeUsesBtree(v, iDb);
66634        sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
66635        if( db->init.busy==0 ){
66636          sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
66637        }
66638      }
66639#ifndef SQLITE_OMIT_VIRTUALTABLE
66640      {
66641        int i;
66642        for(i=0; i<pParse->nVtabLock; i++){
66643          char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
66644          sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
66645        }
66646        pParse->nVtabLock = 0;
66647      }
66648#endif
66649
66650      /* Once all the cookies have been verified and transactions opened,
66651      ** obtain the required table-locks. This is a no-op unless the
66652      ** shared-cache feature is enabled.
66653      */
66654      codeTableLocks(pParse);
66655
66656      /* Initialize any AUTOINCREMENT data structures required.
66657      */
66658      sqlite3AutoincrementBegin(pParse);
66659
66660      /* Finally, jump back to the beginning of the executable code. */
66661      sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
66662    }
66663  }
66664
66665
66666  /* Get the VDBE program ready for execution
66667  */
66668  if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
66669#ifdef SQLITE_DEBUG
66670    FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
66671    sqlite3VdbeTrace(v, trace);
66672#endif
66673    assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
66674    /* A minimum of one cursor is required if autoincrement is used
66675    *  See ticket [a696379c1f08866] */
66676    if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
66677    sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
66678                         pParse->nTab, pParse->nMaxArg, pParse->explain,
66679                         pParse->isMultiWrite && pParse->mayAbort);
66680    pParse->rc = SQLITE_DONE;
66681    pParse->colNamesSet = 0;
66682  }else if( pParse->rc==SQLITE_OK ){
66683    pParse->rc = SQLITE_ERROR;
66684  }
66685  pParse->nTab = 0;
66686  pParse->nMem = 0;
66687  pParse->nSet = 0;
66688  pParse->nVar = 0;
66689  pParse->cookieMask = 0;
66690  pParse->cookieGoto = 0;
66691}
66692
66693/*
66694** Run the parser and code generator recursively in order to generate
66695** code for the SQL statement given onto the end of the pParse context
66696** currently under construction.  When the parser is run recursively
66697** this way, the final OP_Halt is not appended and other initialization
66698** and finalization steps are omitted because those are handling by the
66699** outermost parser.
66700**
66701** Not everything is nestable.  This facility is designed to permit
66702** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
66703** care if you decide to try to use this routine for some other purposes.
66704*/
66705SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
66706  va_list ap;
66707  char *zSql;
66708  char *zErrMsg = 0;
66709  sqlite3 *db = pParse->db;
66710# define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
66711  char saveBuf[SAVE_SZ];
66712
66713  if( pParse->nErr ) return;
66714  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
66715  va_start(ap, zFormat);
66716  zSql = sqlite3VMPrintf(db, zFormat, ap);
66717  va_end(ap);
66718  if( zSql==0 ){
66719    return;   /* A malloc must have failed */
66720  }
66721  pParse->nested++;
66722  memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
66723  memset(&pParse->nVar, 0, SAVE_SZ);
66724  sqlite3RunParser(pParse, zSql, &zErrMsg);
66725  sqlite3DbFree(db, zErrMsg);
66726  sqlite3DbFree(db, zSql);
66727  memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
66728  pParse->nested--;
66729}
66730
66731/*
66732** Locate the in-memory structure that describes a particular database
66733** table given the name of that table and (optionally) the name of the
66734** database containing the table.  Return NULL if not found.
66735**
66736** If zDatabase is 0, all databases are searched for the table and the
66737** first matching table is returned.  (No checking for duplicate table
66738** names is done.)  The search order is TEMP first, then MAIN, then any
66739** auxiliary databases added using the ATTACH command.
66740**
66741** See also sqlite3LocateTable().
66742*/
66743SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
66744  Table *p = 0;
66745  int i;
66746  int nName;
66747  assert( zName!=0 );
66748  nName = sqlite3Strlen30(zName);
66749  for(i=OMIT_TEMPDB; i<db->nDb; i++){
66750    int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
66751    if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
66752    p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
66753    if( p ) break;
66754  }
66755  return p;
66756}
66757
66758/*
66759** Locate the in-memory structure that describes a particular database
66760** table given the name of that table and (optionally) the name of the
66761** database containing the table.  Return NULL if not found.  Also leave an
66762** error message in pParse->zErrMsg.
66763**
66764** The difference between this routine and sqlite3FindTable() is that this
66765** routine leaves an error message in pParse->zErrMsg where
66766** sqlite3FindTable() does not.
66767*/
66768SQLITE_PRIVATE Table *sqlite3LocateTable(
66769  Parse *pParse,         /* context in which to report errors */
66770  int isView,            /* True if looking for a VIEW rather than a TABLE */
66771  const char *zName,     /* Name of the table we are looking for */
66772  const char *zDbase     /* Name of the database.  Might be NULL */
66773){
66774  Table *p;
66775
66776  /* Read the database schema. If an error occurs, leave an error message
66777  ** and code in pParse and return NULL. */
66778  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
66779    return 0;
66780  }
66781
66782  p = sqlite3FindTable(pParse->db, zName, zDbase);
66783  if( p==0 ){
66784    const char *zMsg = isView ? "no such view" : "no such table";
66785    if( zDbase ){
66786      sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
66787    }else{
66788      sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
66789    }
66790    pParse->checkSchema = 1;
66791  }
66792  return p;
66793}
66794
66795/*
66796** Locate the in-memory structure that describes
66797** a particular index given the name of that index
66798** and the name of the database that contains the index.
66799** Return NULL if not found.
66800**
66801** If zDatabase is 0, all databases are searched for the
66802** table and the first matching index is returned.  (No checking
66803** for duplicate index names is done.)  The search order is
66804** TEMP first, then MAIN, then any auxiliary databases added
66805** using the ATTACH command.
66806*/
66807SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
66808  Index *p = 0;
66809  int i;
66810  int nName = sqlite3Strlen30(zName);
66811  for(i=OMIT_TEMPDB; i<db->nDb; i++){
66812    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
66813    Schema *pSchema = db->aDb[j].pSchema;
66814    assert( pSchema );
66815    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
66816    p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
66817    if( p ) break;
66818  }
66819  return p;
66820}
66821
66822/*
66823** Reclaim the memory used by an index
66824*/
66825static void freeIndex(Index *p){
66826  sqlite3 *db = p->pTable->dbMem;
66827#ifndef SQLITE_OMIT_ANALYZE
66828  sqlite3DeleteIndexSamples(p);
66829#endif
66830  sqlite3DbFree(db, p->zColAff);
66831  sqlite3DbFree(db, p);
66832}
66833
66834/*
66835** Remove the given index from the index hash table, and free
66836** its memory structures.
66837**
66838** The index is removed from the database hash tables but
66839** it is not unlinked from the Table that it indexes.
66840** Unlinking from the Table must be done by the calling function.
66841*/
66842static void sqlite3DeleteIndex(Index *p){
66843  Index *pOld;
66844  const char *zName = p->zName;
66845
66846  pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
66847                           sqlite3Strlen30(zName), 0);
66848  assert( pOld==0 || pOld==p );
66849  freeIndex(p);
66850}
66851
66852/*
66853** For the index called zIdxName which is found in the database iDb,
66854** unlike that index from its Table then remove the index from
66855** the index hash table and free all memory structures associated
66856** with the index.
66857*/
66858SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
66859  Index *pIndex;
66860  int len;
66861  Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
66862
66863  len = sqlite3Strlen30(zIdxName);
66864  pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
66865  if( pIndex ){
66866    if( pIndex->pTable->pIndex==pIndex ){
66867      pIndex->pTable->pIndex = pIndex->pNext;
66868    }else{
66869      Index *p;
66870      /* Justification of ALWAYS();  The index must be on the list of
66871      ** indices. */
66872      p = pIndex->pTable->pIndex;
66873      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
66874      if( ALWAYS(p && p->pNext==pIndex) ){
66875        p->pNext = pIndex->pNext;
66876      }
66877    }
66878    freeIndex(pIndex);
66879  }
66880  db->flags |= SQLITE_InternChanges;
66881}
66882
66883/*
66884** Erase all schema information from the in-memory hash tables of
66885** a single database.  This routine is called to reclaim memory
66886** before the database closes.  It is also called during a rollback
66887** if there were schema changes during the transaction or if a
66888** schema-cookie mismatch occurs.
66889**
66890** If iDb==0 then reset the internal schema tables for all database
66891** files.  If iDb>=1 then reset the internal schema for only the
66892** single file indicated.
66893*/
66894SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
66895  int i, j;
66896  assert( iDb>=0 && iDb<db->nDb );
66897
66898  if( iDb==0 ){
66899    sqlite3BtreeEnterAll(db);
66900  }
66901  for(i=iDb; i<db->nDb; i++){
66902    Db *pDb = &db->aDb[i];
66903    if( pDb->pSchema ){
66904      assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
66905      sqlite3SchemaFree(pDb->pSchema);
66906    }
66907    if( iDb>0 ) return;
66908  }
66909  assert( iDb==0 );
66910  db->flags &= ~SQLITE_InternChanges;
66911  sqlite3VtabUnlockList(db);
66912  sqlite3BtreeLeaveAll(db);
66913
66914  /* If one or more of the auxiliary database files has been closed,
66915  ** then remove them from the auxiliary database list.  We take the
66916  ** opportunity to do this here since we have just deleted all of the
66917  ** schema hash tables and therefore do not have to make any changes
66918  ** to any of those tables.
66919  */
66920  for(i=j=2; i<db->nDb; i++){
66921    struct Db *pDb = &db->aDb[i];
66922    if( pDb->pBt==0 ){
66923      sqlite3DbFree(db, pDb->zName);
66924      pDb->zName = 0;
66925      continue;
66926    }
66927    if( j<i ){
66928      db->aDb[j] = db->aDb[i];
66929    }
66930    j++;
66931  }
66932  memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
66933  db->nDb = j;
66934  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
66935    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
66936    sqlite3DbFree(db, db->aDb);
66937    db->aDb = db->aDbStatic;
66938  }
66939}
66940
66941/*
66942** This routine is called when a commit occurs.
66943*/
66944SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
66945  db->flags &= ~SQLITE_InternChanges;
66946}
66947
66948/*
66949** Clear the column names from a table or view.
66950*/
66951static void sqliteResetColumnNames(Table *pTable){
66952  int i;
66953  Column *pCol;
66954  sqlite3 *db = pTable->dbMem;
66955  testcase( db==0 );
66956  assert( pTable!=0 );
66957  if( (pCol = pTable->aCol)!=0 ){
66958    for(i=0; i<pTable->nCol; i++, pCol++){
66959      sqlite3DbFree(db, pCol->zName);
66960      sqlite3ExprDelete(db, pCol->pDflt);
66961      sqlite3DbFree(db, pCol->zDflt);
66962      sqlite3DbFree(db, pCol->zType);
66963      sqlite3DbFree(db, pCol->zColl);
66964    }
66965    sqlite3DbFree(db, pTable->aCol);
66966  }
66967  pTable->aCol = 0;
66968  pTable->nCol = 0;
66969}
66970
66971/*
66972** Remove the memory data structures associated with the given
66973** Table.  No changes are made to disk by this routine.
66974**
66975** This routine just deletes the data structure.  It does not unlink
66976** the table data structure from the hash table.  But it does destroy
66977** memory structures of the indices and foreign keys associated with
66978** the table.
66979*/
66980SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
66981  Index *pIndex, *pNext;
66982  sqlite3 *db;
66983
66984  if( pTable==0 ) return;
66985  db = pTable->dbMem;
66986  testcase( db==0 );
66987
66988  /* Do not delete the table until the reference count reaches zero. */
66989  pTable->nRef--;
66990  if( pTable->nRef>0 ){
66991    return;
66992  }
66993  assert( pTable->nRef==0 );
66994
66995  /* Delete all indices associated with this table
66996  */
66997  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
66998    pNext = pIndex->pNext;
66999    assert( pIndex->pSchema==pTable->pSchema );
67000    sqlite3DeleteIndex(pIndex);
67001  }
67002
67003  /* Delete any foreign keys attached to this table. */
67004  sqlite3FkDelete(pTable);
67005
67006  /* Delete the Table structure itself.
67007  */
67008  sqliteResetColumnNames(pTable);
67009  sqlite3DbFree(db, pTable->zName);
67010  sqlite3DbFree(db, pTable->zColAff);
67011  sqlite3SelectDelete(db, pTable->pSelect);
67012#ifndef SQLITE_OMIT_CHECK
67013  sqlite3ExprDelete(db, pTable->pCheck);
67014#endif
67015  sqlite3VtabClear(pTable);
67016  sqlite3DbFree(db, pTable);
67017}
67018
67019/*
67020** Unlink the given table from the hash tables and the delete the
67021** table structure with all its indices and foreign keys.
67022*/
67023SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
67024  Table *p;
67025  Db *pDb;
67026
67027  assert( db!=0 );
67028  assert( iDb>=0 && iDb<db->nDb );
67029  assert( zTabName );
67030  testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
67031  pDb = &db->aDb[iDb];
67032  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
67033                        sqlite3Strlen30(zTabName),0);
67034  sqlite3DeleteTable(p);
67035  db->flags |= SQLITE_InternChanges;
67036}
67037
67038/*
67039** Given a token, return a string that consists of the text of that
67040** token.  Space to hold the returned string
67041** is obtained from sqliteMalloc() and must be freed by the calling
67042** function.
67043**
67044** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
67045** surround the body of the token are removed.
67046**
67047** Tokens are often just pointers into the original SQL text and so
67048** are not \000 terminated and are not persistent.  The returned string
67049** is \000 terminated and is persistent.
67050*/
67051SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
67052  char *zName;
67053  if( pName ){
67054    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
67055    sqlite3Dequote(zName);
67056  }else{
67057    zName = 0;
67058  }
67059  return zName;
67060}
67061
67062/*
67063** Open the sqlite_master table stored in database number iDb for
67064** writing. The table is opened using cursor 0.
67065*/
67066SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
67067  Vdbe *v = sqlite3GetVdbe(p);
67068  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
67069  sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
67070  sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
67071  if( p->nTab==0 ){
67072    p->nTab = 1;
67073  }
67074}
67075
67076/*
67077** Parameter zName points to a nul-terminated buffer containing the name
67078** of a database ("main", "temp" or the name of an attached db). This
67079** function returns the index of the named database in db->aDb[], or
67080** -1 if the named db cannot be found.
67081*/
67082SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
67083  int i = -1;         /* Database number */
67084  if( zName ){
67085    Db *pDb;
67086    int n = sqlite3Strlen30(zName);
67087    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
67088      if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
67089          0==sqlite3StrICmp(pDb->zName, zName) ){
67090        break;
67091      }
67092    }
67093  }
67094  return i;
67095}
67096
67097/*
67098** The token *pName contains the name of a database (either "main" or
67099** "temp" or the name of an attached db). This routine returns the
67100** index of the named database in db->aDb[], or -1 if the named db
67101** does not exist.
67102*/
67103SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
67104  int i;                               /* Database number */
67105  char *zName;                         /* Name we are searching for */
67106  zName = sqlite3NameFromToken(db, pName);
67107  i = sqlite3FindDbName(db, zName);
67108  sqlite3DbFree(db, zName);
67109  return i;
67110}
67111
67112/* The table or view or trigger name is passed to this routine via tokens
67113** pName1 and pName2. If the table name was fully qualified, for example:
67114**
67115** CREATE TABLE xxx.yyy (...);
67116**
67117** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
67118** the table name is not fully qualified, i.e.:
67119**
67120** CREATE TABLE yyy(...);
67121**
67122** Then pName1 is set to "yyy" and pName2 is "".
67123**
67124** This routine sets the *ppUnqual pointer to point at the token (pName1 or
67125** pName2) that stores the unqualified table name.  The index of the
67126** database "xxx" is returned.
67127*/
67128SQLITE_PRIVATE int sqlite3TwoPartName(
67129  Parse *pParse,      /* Parsing and code generating context */
67130  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
67131  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
67132  Token **pUnqual     /* Write the unqualified object name here */
67133){
67134  int iDb;                    /* Database holding the object */
67135  sqlite3 *db = pParse->db;
67136
67137  if( ALWAYS(pName2!=0) && pName2->n>0 ){
67138    if( db->init.busy ) {
67139      sqlite3ErrorMsg(pParse, "corrupt database");
67140      pParse->nErr++;
67141      return -1;
67142    }
67143    *pUnqual = pName2;
67144    iDb = sqlite3FindDb(db, pName1);
67145    if( iDb<0 ){
67146      sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
67147      pParse->nErr++;
67148      return -1;
67149    }
67150  }else{
67151    assert( db->init.iDb==0 || db->init.busy );
67152    iDb = db->init.iDb;
67153    *pUnqual = pName1;
67154  }
67155  return iDb;
67156}
67157
67158/*
67159** This routine is used to check if the UTF-8 string zName is a legal
67160** unqualified name for a new schema object (table, index, view or
67161** trigger). All names are legal except those that begin with the string
67162** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
67163** is reserved for internal use.
67164*/
67165SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
67166  if( !pParse->db->init.busy && pParse->nested==0
67167          && (pParse->db->flags & SQLITE_WriteSchema)==0
67168          && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
67169    sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
67170    return SQLITE_ERROR;
67171  }
67172  return SQLITE_OK;
67173}
67174
67175/*
67176** Begin constructing a new table representation in memory.  This is
67177** the first of several action routines that get called in response
67178** to a CREATE TABLE statement.  In particular, this routine is called
67179** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
67180** flag is true if the table should be stored in the auxiliary database
67181** file instead of in the main database file.  This is normally the case
67182** when the "TEMP" or "TEMPORARY" keyword occurs in between
67183** CREATE and TABLE.
67184**
67185** The new table record is initialized and put in pParse->pNewTable.
67186** As more of the CREATE TABLE statement is parsed, additional action
67187** routines will be called to add more information to this record.
67188** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
67189** is called to complete the construction of the new table record.
67190*/
67191SQLITE_PRIVATE void sqlite3StartTable(
67192  Parse *pParse,   /* Parser context */
67193  Token *pName1,   /* First part of the name of the table or view */
67194  Token *pName2,   /* Second part of the name of the table or view */
67195  int isTemp,      /* True if this is a TEMP table */
67196  int isView,      /* True if this is a VIEW */
67197  int isVirtual,   /* True if this is a VIRTUAL table */
67198  int noErr        /* Do nothing if table already exists */
67199){
67200  Table *pTable;
67201  char *zName = 0; /* The name of the new table */
67202  sqlite3 *db = pParse->db;
67203  Vdbe *v;
67204  int iDb;         /* Database number to create the table in */
67205  Token *pName;    /* Unqualified name of the table to create */
67206
67207  /* The table or view name to create is passed to this routine via tokens
67208  ** pName1 and pName2. If the table name was fully qualified, for example:
67209  **
67210  ** CREATE TABLE xxx.yyy (...);
67211  **
67212  ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
67213  ** the table name is not fully qualified, i.e.:
67214  **
67215  ** CREATE TABLE yyy(...);
67216  **
67217  ** Then pName1 is set to "yyy" and pName2 is "".
67218  **
67219  ** The call below sets the pName pointer to point at the token (pName1 or
67220  ** pName2) that stores the unqualified table name. The variable iDb is
67221  ** set to the index of the database that the table or view is to be
67222  ** created in.
67223  */
67224  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
67225  if( iDb<0 ) return;
67226  if( !OMIT_TEMPDB && isTemp && iDb>1 ){
67227    /* If creating a temp table, the name may not be qualified */
67228    sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
67229    return;
67230  }
67231  if( !OMIT_TEMPDB && isTemp ) iDb = 1;
67232
67233  pParse->sNameToken = *pName;
67234  zName = sqlite3NameFromToken(db, pName);
67235  if( zName==0 ) return;
67236  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
67237    goto begin_table_error;
67238  }
67239  if( db->init.iDb==1 ) isTemp = 1;
67240#ifndef SQLITE_OMIT_AUTHORIZATION
67241  assert( (isTemp & 1)==isTemp );
67242  {
67243    int code;
67244    char *zDb = db->aDb[iDb].zName;
67245    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
67246      goto begin_table_error;
67247    }
67248    if( isView ){
67249      if( !OMIT_TEMPDB && isTemp ){
67250        code = SQLITE_CREATE_TEMP_VIEW;
67251      }else{
67252        code = SQLITE_CREATE_VIEW;
67253      }
67254    }else{
67255      if( !OMIT_TEMPDB && isTemp ){
67256        code = SQLITE_CREATE_TEMP_TABLE;
67257      }else{
67258        code = SQLITE_CREATE_TABLE;
67259      }
67260    }
67261    if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
67262      goto begin_table_error;
67263    }
67264  }
67265#endif
67266
67267  /* Make sure the new table name does not collide with an existing
67268  ** index or table name in the same database.  Issue an error message if
67269  ** it does. The exception is if the statement being parsed was passed
67270  ** to an sqlite3_declare_vtab() call. In that case only the column names
67271  ** and types will be used, so there is no need to test for namespace
67272  ** collisions.
67273  */
67274  if( !IN_DECLARE_VTAB ){
67275    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
67276      goto begin_table_error;
67277    }
67278    pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
67279    if( pTable ){
67280      if( !noErr ){
67281        sqlite3ErrorMsg(pParse, "table %T already exists", pName);
67282      }
67283      goto begin_table_error;
67284    }
67285    if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
67286      sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
67287      goto begin_table_error;
67288    }
67289  }
67290
67291  pTable = sqlite3DbMallocZero(db, sizeof(Table));
67292  if( pTable==0 ){
67293    db->mallocFailed = 1;
67294    pParse->rc = SQLITE_NOMEM;
67295    pParse->nErr++;
67296    goto begin_table_error;
67297  }
67298  pTable->zName = zName;
67299  pTable->iPKey = -1;
67300  pTable->pSchema = db->aDb[iDb].pSchema;
67301  pTable->nRef = 1;
67302  pTable->dbMem = 0;
67303  assert( pParse->pNewTable==0 );
67304  pParse->pNewTable = pTable;
67305
67306  /* If this is the magic sqlite_sequence table used by autoincrement,
67307  ** then record a pointer to this table in the main database structure
67308  ** so that INSERT can find the table easily.
67309  */
67310#ifndef SQLITE_OMIT_AUTOINCREMENT
67311  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
67312    pTable->pSchema->pSeqTab = pTable;
67313  }
67314#endif
67315
67316  /* Begin generating the code that will insert the table record into
67317  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
67318  ** and allocate the record number for the table entry now.  Before any
67319  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
67320  ** indices to be created and the table record must come before the
67321  ** indices.  Hence, the record number for the table must be allocated
67322  ** now.
67323  */
67324  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
67325    int j1;
67326    int fileFormat;
67327    int reg1, reg2, reg3;
67328    sqlite3BeginWriteOperation(pParse, 0, iDb);
67329
67330#ifndef SQLITE_OMIT_VIRTUALTABLE
67331    if( isVirtual ){
67332      sqlite3VdbeAddOp0(v, OP_VBegin);
67333    }
67334#endif
67335
67336    /* If the file format and encoding in the database have not been set,
67337    ** set them now.
67338    */
67339    reg1 = pParse->regRowid = ++pParse->nMem;
67340    reg2 = pParse->regRoot = ++pParse->nMem;
67341    reg3 = ++pParse->nMem;
67342    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
67343    sqlite3VdbeUsesBtree(v, iDb);
67344    j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
67345    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
67346                  1 : SQLITE_MAX_FILE_FORMAT;
67347    sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
67348    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
67349    sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
67350    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
67351    sqlite3VdbeJumpHere(v, j1);
67352
67353    /* This just creates a place-holder record in the sqlite_master table.
67354    ** The record created does not contain anything yet.  It will be replaced
67355    ** by the real entry in code generated at sqlite3EndTable().
67356    **
67357    ** The rowid for the new entry is left in register pParse->regRowid.
67358    ** The root page number of the new table is left in reg pParse->regRoot.
67359    ** The rowid and root page number values are needed by the code that
67360    ** sqlite3EndTable will generate.
67361    */
67362#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
67363    if( isView || isVirtual ){
67364      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
67365    }else
67366#endif
67367    {
67368      sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
67369    }
67370    sqlite3OpenMasterTable(pParse, iDb);
67371    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
67372    sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
67373    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
67374    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
67375    sqlite3VdbeAddOp0(v, OP_Close);
67376  }
67377
67378  /* Normal (non-error) return. */
67379  return;
67380
67381  /* If an error occurs, we jump here */
67382begin_table_error:
67383  sqlite3DbFree(db, zName);
67384  return;
67385}
67386
67387/*
67388** This macro is used to compare two strings in a case-insensitive manner.
67389** It is slightly faster than calling sqlite3StrICmp() directly, but
67390** produces larger code.
67391**
67392** WARNING: This macro is not compatible with the strcmp() family. It
67393** returns true if the two strings are equal, otherwise false.
67394*/
67395#define STRICMP(x, y) (\
67396sqlite3UpperToLower[*(unsigned char *)(x)]==   \
67397sqlite3UpperToLower[*(unsigned char *)(y)]     \
67398&& sqlite3StrICmp((x)+1,(y)+1)==0 )
67399
67400/*
67401** Add a new column to the table currently being constructed.
67402**
67403** The parser calls this routine once for each column declaration
67404** in a CREATE TABLE statement.  sqlite3StartTable() gets called
67405** first to get things going.  Then this routine is called for each
67406** column.
67407*/
67408SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
67409  Table *p;
67410  int i;
67411  char *z;
67412  Column *pCol;
67413  sqlite3 *db = pParse->db;
67414  if( (p = pParse->pNewTable)==0 ) return;
67415#if SQLITE_MAX_COLUMN
67416  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
67417    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
67418    return;
67419  }
67420#endif
67421  z = sqlite3NameFromToken(db, pName);
67422  if( z==0 ) return;
67423  for(i=0; i<p->nCol; i++){
67424    if( STRICMP(z, p->aCol[i].zName) ){
67425      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
67426      sqlite3DbFree(db, z);
67427      return;
67428    }
67429  }
67430  if( (p->nCol & 0x7)==0 ){
67431    Column *aNew;
67432    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
67433    if( aNew==0 ){
67434      sqlite3DbFree(db, z);
67435      return;
67436    }
67437    p->aCol = aNew;
67438  }
67439  pCol = &p->aCol[p->nCol];
67440  memset(pCol, 0, sizeof(p->aCol[0]));
67441  pCol->zName = z;
67442
67443  /* If there is no type specified, columns have the default affinity
67444  ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
67445  ** be called next to set pCol->affinity correctly.
67446  */
67447  pCol->affinity = SQLITE_AFF_NONE;
67448  p->nCol++;
67449}
67450
67451/*
67452** This routine is called by the parser while in the middle of
67453** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
67454** been seen on a column.  This routine sets the notNull flag on
67455** the column currently under construction.
67456*/
67457SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
67458  Table *p;
67459  p = pParse->pNewTable;
67460  if( p==0 || NEVER(p->nCol<1) ) return;
67461  p->aCol[p->nCol-1].notNull = (u8)onError;
67462}
67463
67464/*
67465** Scan the column type name zType (length nType) and return the
67466** associated affinity type.
67467**
67468** This routine does a case-independent search of zType for the
67469** substrings in the following table. If one of the substrings is
67470** found, the corresponding affinity is returned. If zType contains
67471** more than one of the substrings, entries toward the top of
67472** the table take priority. For example, if zType is 'BLOBINT',
67473** SQLITE_AFF_INTEGER is returned.
67474**
67475** Substring     | Affinity
67476** --------------------------------
67477** 'INT'         | SQLITE_AFF_INTEGER
67478** 'CHAR'        | SQLITE_AFF_TEXT
67479** 'CLOB'        | SQLITE_AFF_TEXT
67480** 'TEXT'        | SQLITE_AFF_TEXT
67481** 'BLOB'        | SQLITE_AFF_NONE
67482** 'REAL'        | SQLITE_AFF_REAL
67483** 'FLOA'        | SQLITE_AFF_REAL
67484** 'DOUB'        | SQLITE_AFF_REAL
67485**
67486** If none of the substrings in the above table are found,
67487** SQLITE_AFF_NUMERIC is returned.
67488*/
67489SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
67490  u32 h = 0;
67491  char aff = SQLITE_AFF_NUMERIC;
67492
67493  if( zIn ) while( zIn[0] ){
67494    h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
67495    zIn++;
67496    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
67497      aff = SQLITE_AFF_TEXT;
67498    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
67499      aff = SQLITE_AFF_TEXT;
67500    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
67501      aff = SQLITE_AFF_TEXT;
67502    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
67503        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
67504      aff = SQLITE_AFF_NONE;
67505#ifndef SQLITE_OMIT_FLOATING_POINT
67506    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
67507        && aff==SQLITE_AFF_NUMERIC ){
67508      aff = SQLITE_AFF_REAL;
67509    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
67510        && aff==SQLITE_AFF_NUMERIC ){
67511      aff = SQLITE_AFF_REAL;
67512    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
67513        && aff==SQLITE_AFF_NUMERIC ){
67514      aff = SQLITE_AFF_REAL;
67515#endif
67516    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
67517      aff = SQLITE_AFF_INTEGER;
67518      break;
67519    }
67520  }
67521
67522  return aff;
67523}
67524
67525/*
67526** This routine is called by the parser while in the middle of
67527** parsing a CREATE TABLE statement.  The pFirst token is the first
67528** token in the sequence of tokens that describe the type of the
67529** column currently under construction.   pLast is the last token
67530** in the sequence.  Use this information to construct a string
67531** that contains the typename of the column and store that string
67532** in zType.
67533*/
67534SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
67535  Table *p;
67536  Column *pCol;
67537
67538  p = pParse->pNewTable;
67539  if( p==0 || NEVER(p->nCol<1) ) return;
67540  pCol = &p->aCol[p->nCol-1];
67541  assert( pCol->zType==0 );
67542  pCol->zType = sqlite3NameFromToken(pParse->db, pType);
67543  pCol->affinity = sqlite3AffinityType(pCol->zType);
67544}
67545
67546/*
67547** The expression is the default value for the most recently added column
67548** of the table currently under construction.
67549**
67550** Default value expressions must be constant.  Raise an exception if this
67551** is not the case.
67552**
67553** This routine is called by the parser while in the middle of
67554** parsing a CREATE TABLE statement.
67555*/
67556SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
67557  Table *p;
67558  Column *pCol;
67559  sqlite3 *db = pParse->db;
67560  p = pParse->pNewTable;
67561  if( p!=0 ){
67562    pCol = &(p->aCol[p->nCol-1]);
67563    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
67564      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
67565          pCol->zName);
67566    }else{
67567      /* A copy of pExpr is used instead of the original, as pExpr contains
67568      ** tokens that point to volatile memory. The 'span' of the expression
67569      ** is required by pragma table_info.
67570      */
67571      sqlite3ExprDelete(db, pCol->pDflt);
67572      pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
67573      sqlite3DbFree(db, pCol->zDflt);
67574      pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
67575                                     (int)(pSpan->zEnd - pSpan->zStart));
67576    }
67577  }
67578  sqlite3ExprDelete(db, pSpan->pExpr);
67579}
67580
67581/*
67582** Designate the PRIMARY KEY for the table.  pList is a list of names
67583** of columns that form the primary key.  If pList is NULL, then the
67584** most recently added column of the table is the primary key.
67585**
67586** A table can have at most one primary key.  If the table already has
67587** a primary key (and this is the second primary key) then create an
67588** error.
67589**
67590** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
67591** then we will try to use that column as the rowid.  Set the Table.iPKey
67592** field of the table under construction to be the index of the
67593** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
67594** no INTEGER PRIMARY KEY.
67595**
67596** If the key is not an INTEGER PRIMARY KEY, then create a unique
67597** index for the key.  No index is created for INTEGER PRIMARY KEYs.
67598*/
67599SQLITE_PRIVATE void sqlite3AddPrimaryKey(
67600  Parse *pParse,    /* Parsing context */
67601  ExprList *pList,  /* List of field names to be indexed */
67602  int onError,      /* What to do with a uniqueness conflict */
67603  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
67604  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
67605){
67606  Table *pTab = pParse->pNewTable;
67607  char *zType = 0;
67608  int iCol = -1, i;
67609  if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
67610  if( pTab->tabFlags & TF_HasPrimaryKey ){
67611    sqlite3ErrorMsg(pParse,
67612      "table \"%s\" has more than one primary key", pTab->zName);
67613    goto primary_key_exit;
67614  }
67615  pTab->tabFlags |= TF_HasPrimaryKey;
67616  if( pList==0 ){
67617    iCol = pTab->nCol - 1;
67618    pTab->aCol[iCol].isPrimKey = 1;
67619  }else{
67620    for(i=0; i<pList->nExpr; i++){
67621      for(iCol=0; iCol<pTab->nCol; iCol++){
67622        if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
67623          break;
67624        }
67625      }
67626      if( iCol<pTab->nCol ){
67627        pTab->aCol[iCol].isPrimKey = 1;
67628      }
67629    }
67630    if( pList->nExpr>1 ) iCol = -1;
67631  }
67632  if( iCol>=0 && iCol<pTab->nCol ){
67633    zType = pTab->aCol[iCol].zType;
67634  }
67635  if( zType && sqlite3StrICmp(zType, "INTEGER")==0
67636        && sortOrder==SQLITE_SO_ASC ){
67637    pTab->iPKey = iCol;
67638    pTab->keyConf = (u8)onError;
67639    assert( autoInc==0 || autoInc==1 );
67640    pTab->tabFlags |= autoInc*TF_Autoincrement;
67641  }else if( autoInc ){
67642#ifndef SQLITE_OMIT_AUTOINCREMENT
67643    sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
67644       "INTEGER PRIMARY KEY");
67645#endif
67646  }else{
67647    Index *p;
67648    p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
67649    if( p ){
67650      p->autoIndex = 2;
67651    }
67652    pList = 0;
67653  }
67654
67655primary_key_exit:
67656  sqlite3ExprListDelete(pParse->db, pList);
67657  return;
67658}
67659
67660/*
67661** Add a new CHECK constraint to the table currently under construction.
67662*/
67663SQLITE_PRIVATE void sqlite3AddCheckConstraint(
67664  Parse *pParse,    /* Parsing context */
67665  Expr *pCheckExpr  /* The check expression */
67666){
67667  sqlite3 *db = pParse->db;
67668#ifndef SQLITE_OMIT_CHECK
67669  Table *pTab = pParse->pNewTable;
67670  if( pTab && !IN_DECLARE_VTAB ){
67671    pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
67672  }else
67673#endif
67674  {
67675    sqlite3ExprDelete(db, pCheckExpr);
67676  }
67677}
67678
67679/*
67680** Set the collation function of the most recently parsed table column
67681** to the CollSeq given.
67682*/
67683SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
67684  Table *p;
67685  int i;
67686  char *zColl;              /* Dequoted name of collation sequence */
67687  sqlite3 *db;
67688
67689  if( (p = pParse->pNewTable)==0 ) return;
67690  i = p->nCol-1;
67691  db = pParse->db;
67692  zColl = sqlite3NameFromToken(db, pToken);
67693  if( !zColl ) return;
67694
67695  if( sqlite3LocateCollSeq(pParse, zColl) ){
67696    Index *pIdx;
67697    p->aCol[i].zColl = zColl;
67698
67699    /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
67700    ** then an index may have been created on this column before the
67701    ** collation type was added. Correct this if it is the case.
67702    */
67703    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
67704      assert( pIdx->nColumn==1 );
67705      if( pIdx->aiColumn[0]==i ){
67706        pIdx->azColl[0] = p->aCol[i].zColl;
67707      }
67708    }
67709  }else{
67710    sqlite3DbFree(db, zColl);
67711  }
67712}
67713
67714/*
67715** This function returns the collation sequence for database native text
67716** encoding identified by the string zName, length nName.
67717**
67718** If the requested collation sequence is not available, or not available
67719** in the database native encoding, the collation factory is invoked to
67720** request it. If the collation factory does not supply such a sequence,
67721** and the sequence is available in another text encoding, then that is
67722** returned instead.
67723**
67724** If no versions of the requested collations sequence are available, or
67725** another error occurs, NULL is returned and an error message written into
67726** pParse.
67727**
67728** This routine is a wrapper around sqlite3FindCollSeq().  This routine
67729** invokes the collation factory if the named collation cannot be found
67730** and generates an error message.
67731**
67732** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
67733*/
67734SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
67735  sqlite3 *db = pParse->db;
67736  u8 enc = ENC(db);
67737  u8 initbusy = db->init.busy;
67738  CollSeq *pColl;
67739
67740  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
67741  if( !initbusy && (!pColl || !pColl->xCmp) ){
67742    pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
67743    if( !pColl ){
67744      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
67745    }
67746  }
67747
67748  return pColl;
67749}
67750
67751
67752/*
67753** Generate code that will increment the schema cookie.
67754**
67755** The schema cookie is used to determine when the schema for the
67756** database changes.  After each schema change, the cookie value
67757** changes.  When a process first reads the schema it records the
67758** cookie.  Thereafter, whenever it goes to access the database,
67759** it checks the cookie to make sure the schema has not changed
67760** since it was last read.
67761**
67762** This plan is not completely bullet-proof.  It is possible for
67763** the schema to change multiple times and for the cookie to be
67764** set back to prior value.  But schema changes are infrequent
67765** and the probability of hitting the same cookie value is only
67766** 1 chance in 2^32.  So we're safe enough.
67767*/
67768SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
67769  int r1 = sqlite3GetTempReg(pParse);
67770  sqlite3 *db = pParse->db;
67771  Vdbe *v = pParse->pVdbe;
67772  sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
67773  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
67774  sqlite3ReleaseTempReg(pParse, r1);
67775}
67776
67777/*
67778** Measure the number of characters needed to output the given
67779** identifier.  The number returned includes any quotes used
67780** but does not include the null terminator.
67781**
67782** The estimate is conservative.  It might be larger that what is
67783** really needed.
67784*/
67785static int identLength(const char *z){
67786  int n;
67787  for(n=0; *z; n++, z++){
67788    if( *z=='"' ){ n++; }
67789  }
67790  return n + 2;
67791}
67792
67793/*
67794** The first parameter is a pointer to an output buffer. The second
67795** parameter is a pointer to an integer that contains the offset at
67796** which to write into the output buffer. This function copies the
67797** nul-terminated string pointed to by the third parameter, zSignedIdent,
67798** to the specified offset in the buffer and updates *pIdx to refer
67799** to the first byte after the last byte written before returning.
67800**
67801** If the string zSignedIdent consists entirely of alpha-numeric
67802** characters, does not begin with a digit and is not an SQL keyword,
67803** then it is copied to the output buffer exactly as it is. Otherwise,
67804** it is quoted using double-quotes.
67805*/
67806static void identPut(char *z, int *pIdx, char *zSignedIdent){
67807  unsigned char *zIdent = (unsigned char*)zSignedIdent;
67808  int i, j, needQuote;
67809  i = *pIdx;
67810
67811  for(j=0; zIdent[j]; j++){
67812    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
67813  }
67814  needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
67815  if( !needQuote ){
67816    needQuote = zIdent[j];
67817  }
67818
67819  if( needQuote ) z[i++] = '"';
67820  for(j=0; zIdent[j]; j++){
67821    z[i++] = zIdent[j];
67822    if( zIdent[j]=='"' ) z[i++] = '"';
67823  }
67824  if( needQuote ) z[i++] = '"';
67825  z[i] = 0;
67826  *pIdx = i;
67827}
67828
67829/*
67830** Generate a CREATE TABLE statement appropriate for the given
67831** table.  Memory to hold the text of the statement is obtained
67832** from sqliteMalloc() and must be freed by the calling function.
67833*/
67834static char *createTableStmt(sqlite3 *db, Table *p){
67835  int i, k, n;
67836  char *zStmt;
67837  char *zSep, *zSep2, *zEnd;
67838  Column *pCol;
67839  n = 0;
67840  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
67841    n += identLength(pCol->zName) + 5;
67842  }
67843  n += identLength(p->zName);
67844  if( n<50 ){
67845    zSep = "";
67846    zSep2 = ",";
67847    zEnd = ")";
67848  }else{
67849    zSep = "\n  ";
67850    zSep2 = ",\n  ";
67851    zEnd = "\n)";
67852  }
67853  n += 35 + 6*p->nCol;
67854  zStmt = sqlite3Malloc( n );
67855  if( zStmt==0 ){
67856    db->mallocFailed = 1;
67857    return 0;
67858  }
67859  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
67860  k = sqlite3Strlen30(zStmt);
67861  identPut(zStmt, &k, p->zName);
67862  zStmt[k++] = '(';
67863  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
67864    static const char * const azType[] = {
67865        /* SQLITE_AFF_TEXT    */ " TEXT",
67866        /* SQLITE_AFF_NONE    */ "",
67867        /* SQLITE_AFF_NUMERIC */ " NUM",
67868        /* SQLITE_AFF_INTEGER */ " INT",
67869        /* SQLITE_AFF_REAL    */ " REAL"
67870    };
67871    int len;
67872    const char *zType;
67873
67874    sqlite3_snprintf(n-k, &zStmt[k], zSep);
67875    k += sqlite3Strlen30(&zStmt[k]);
67876    zSep = zSep2;
67877    identPut(zStmt, &k, pCol->zName);
67878    assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
67879    assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
67880    testcase( pCol->affinity==SQLITE_AFF_TEXT );
67881    testcase( pCol->affinity==SQLITE_AFF_NONE );
67882    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
67883    testcase( pCol->affinity==SQLITE_AFF_INTEGER );
67884    testcase( pCol->affinity==SQLITE_AFF_REAL );
67885
67886    zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
67887    len = sqlite3Strlen30(zType);
67888    assert( pCol->affinity==SQLITE_AFF_NONE
67889            || pCol->affinity==sqlite3AffinityType(zType) );
67890    memcpy(&zStmt[k], zType, len);
67891    k += len;
67892    assert( k<=n );
67893  }
67894  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
67895  return zStmt;
67896}
67897
67898/*
67899** This routine is called to report the final ")" that terminates
67900** a CREATE TABLE statement.
67901**
67902** The table structure that other action routines have been building
67903** is added to the internal hash tables, assuming no errors have
67904** occurred.
67905**
67906** An entry for the table is made in the master table on disk, unless
67907** this is a temporary table or db->init.busy==1.  When db->init.busy==1
67908** it means we are reading the sqlite_master table because we just
67909** connected to the database or because the sqlite_master table has
67910** recently changed, so the entry for this table already exists in
67911** the sqlite_master table.  We do not want to create it again.
67912**
67913** If the pSelect argument is not NULL, it means that this routine
67914** was called to create a table generated from a
67915** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
67916** the new table will match the result set of the SELECT.
67917*/
67918SQLITE_PRIVATE void sqlite3EndTable(
67919  Parse *pParse,          /* Parse context */
67920  Token *pCons,           /* The ',' token after the last column defn. */
67921  Token *pEnd,            /* The final ')' token in the CREATE TABLE */
67922  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
67923){
67924  Table *p;
67925  sqlite3 *db = pParse->db;
67926  int iDb;
67927
67928  if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
67929    return;
67930  }
67931  p = pParse->pNewTable;
67932  if( p==0 ) return;
67933
67934  assert( !db->init.busy || !pSelect );
67935
67936  iDb = sqlite3SchemaToIndex(db, p->pSchema);
67937
67938#ifndef SQLITE_OMIT_CHECK
67939  /* Resolve names in all CHECK constraint expressions.
67940  */
67941  if( p->pCheck ){
67942    SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
67943    NameContext sNC;                /* Name context for pParse->pNewTable */
67944
67945    memset(&sNC, 0, sizeof(sNC));
67946    memset(&sSrc, 0, sizeof(sSrc));
67947    sSrc.nSrc = 1;
67948    sSrc.a[0].zName = p->zName;
67949    sSrc.a[0].pTab = p;
67950    sSrc.a[0].iCursor = -1;
67951    sNC.pParse = pParse;
67952    sNC.pSrcList = &sSrc;
67953    sNC.isCheck = 1;
67954    if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
67955      return;
67956    }
67957  }
67958#endif /* !defined(SQLITE_OMIT_CHECK) */
67959
67960  /* If the db->init.busy is 1 it means we are reading the SQL off the
67961  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
67962  ** So do not write to the disk again.  Extract the root page number
67963  ** for the table from the db->init.newTnum field.  (The page number
67964  ** should have been put there by the sqliteOpenCb routine.)
67965  */
67966  if( db->init.busy ){
67967    p->tnum = db->init.newTnum;
67968  }
67969
67970  /* If not initializing, then create a record for the new table
67971  ** in the SQLITE_MASTER table of the database.
67972  **
67973  ** If this is a TEMPORARY table, write the entry into the auxiliary
67974  ** file instead of into the main database file.
67975  */
67976  if( !db->init.busy ){
67977    int n;
67978    Vdbe *v;
67979    char *zType;    /* "view" or "table" */
67980    char *zType2;   /* "VIEW" or "TABLE" */
67981    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
67982
67983    v = sqlite3GetVdbe(pParse);
67984    if( NEVER(v==0) ) return;
67985
67986    sqlite3VdbeAddOp1(v, OP_Close, 0);
67987
67988    /*
67989    ** Initialize zType for the new view or table.
67990    */
67991    if( p->pSelect==0 ){
67992      /* A regular table */
67993      zType = "table";
67994      zType2 = "TABLE";
67995#ifndef SQLITE_OMIT_VIEW
67996    }else{
67997      /* A view */
67998      zType = "view";
67999      zType2 = "VIEW";
68000#endif
68001    }
68002
68003    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
68004    ** statement to populate the new table. The root-page number for the
68005    ** new table is in register pParse->regRoot.
68006    **
68007    ** Once the SELECT has been coded by sqlite3Select(), it is in a
68008    ** suitable state to query for the column names and types to be used
68009    ** by the new table.
68010    **
68011    ** A shared-cache write-lock is not required to write to the new table,
68012    ** as a schema-lock must have already been obtained to create it. Since
68013    ** a schema-lock excludes all other database users, the write-lock would
68014    ** be redundant.
68015    */
68016    if( pSelect ){
68017      SelectDest dest;
68018      Table *pSelTab;
68019
68020      assert(pParse->nTab==1);
68021      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
68022      sqlite3VdbeChangeP5(v, 1);
68023      pParse->nTab = 2;
68024      sqlite3SelectDestInit(&dest, SRT_Table, 1);
68025      sqlite3Select(pParse, pSelect, &dest);
68026      sqlite3VdbeAddOp1(v, OP_Close, 1);
68027      if( pParse->nErr==0 ){
68028        pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
68029        if( pSelTab==0 ) return;
68030        assert( p->aCol==0 );
68031        p->nCol = pSelTab->nCol;
68032        p->aCol = pSelTab->aCol;
68033        pSelTab->nCol = 0;
68034        pSelTab->aCol = 0;
68035        sqlite3DeleteTable(pSelTab);
68036      }
68037    }
68038
68039    /* Compute the complete text of the CREATE statement */
68040    if( pSelect ){
68041      zStmt = createTableStmt(db, p);
68042    }else{
68043      n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
68044      zStmt = sqlite3MPrintf(db,
68045          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
68046      );
68047    }
68048
68049    /* A slot for the record has already been allocated in the
68050    ** SQLITE_MASTER table.  We just need to update that slot with all
68051    ** the information we've collected.
68052    */
68053    sqlite3NestedParse(pParse,
68054      "UPDATE %Q.%s "
68055         "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
68056       "WHERE rowid=#%d",
68057      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
68058      zType,
68059      p->zName,
68060      p->zName,
68061      pParse->regRoot,
68062      zStmt,
68063      pParse->regRowid
68064    );
68065    sqlite3DbFree(db, zStmt);
68066    sqlite3ChangeCookie(pParse, iDb);
68067
68068#ifndef SQLITE_OMIT_AUTOINCREMENT
68069    /* Check to see if we need to create an sqlite_sequence table for
68070    ** keeping track of autoincrement keys.
68071    */
68072    if( p->tabFlags & TF_Autoincrement ){
68073      Db *pDb = &db->aDb[iDb];
68074      if( pDb->pSchema->pSeqTab==0 ){
68075        sqlite3NestedParse(pParse,
68076          "CREATE TABLE %Q.sqlite_sequence(name,seq)",
68077          pDb->zName
68078        );
68079      }
68080    }
68081#endif
68082
68083    /* Reparse everything to update our internal data structures */
68084    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
68085        sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
68086  }
68087
68088
68089  /* Add the table to the in-memory representation of the database.
68090  */
68091  if( db->init.busy ){
68092    Table *pOld;
68093    Schema *pSchema = p->pSchema;
68094    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
68095                             sqlite3Strlen30(p->zName),p);
68096    if( pOld ){
68097      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
68098      db->mallocFailed = 1;
68099      return;
68100    }
68101    pParse->pNewTable = 0;
68102    db->nTable++;
68103    db->flags |= SQLITE_InternChanges;
68104
68105#ifndef SQLITE_OMIT_ALTERTABLE
68106    if( !p->pSelect ){
68107      const char *zName = (const char *)pParse->sNameToken.z;
68108      int nName;
68109      assert( !pSelect && pCons && pEnd );
68110      if( pCons->z==0 ){
68111        pCons = pEnd;
68112      }
68113      nName = (int)((const char *)pCons->z - zName);
68114      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
68115    }
68116#endif
68117  }
68118}
68119
68120#ifndef SQLITE_OMIT_VIEW
68121/*
68122** The parser calls this routine in order to create a new VIEW
68123*/
68124SQLITE_PRIVATE void sqlite3CreateView(
68125  Parse *pParse,     /* The parsing context */
68126  Token *pBegin,     /* The CREATE token that begins the statement */
68127  Token *pName1,     /* The token that holds the name of the view */
68128  Token *pName2,     /* The token that holds the name of the view */
68129  Select *pSelect,   /* A SELECT statement that will become the new view */
68130  int isTemp,        /* TRUE for a TEMPORARY view */
68131  int noErr          /* Suppress error messages if VIEW already exists */
68132){
68133  Table *p;
68134  int n;
68135  const char *z;
68136  Token sEnd;
68137  DbFixer sFix;
68138  Token *pName;
68139  int iDb;
68140  sqlite3 *db = pParse->db;
68141
68142  if( pParse->nVar>0 ){
68143    sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
68144    sqlite3SelectDelete(db, pSelect);
68145    return;
68146  }
68147  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
68148  p = pParse->pNewTable;
68149  if( p==0 ){
68150    sqlite3SelectDelete(db, pSelect);
68151    return;
68152  }
68153  assert( pParse->nErr==0 ); /* If sqlite3StartTable return non-NULL then
68154                             ** there could not have been an error */
68155  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
68156  iDb = sqlite3SchemaToIndex(db, p->pSchema);
68157  if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
68158    && sqlite3FixSelect(&sFix, pSelect)
68159  ){
68160    sqlite3SelectDelete(db, pSelect);
68161    return;
68162  }
68163
68164  /* Make a copy of the entire SELECT statement that defines the view.
68165  ** This will force all the Expr.token.z values to be dynamically
68166  ** allocated rather than point to the input string - which means that
68167  ** they will persist after the current sqlite3_exec() call returns.
68168  */
68169  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
68170  sqlite3SelectDelete(db, pSelect);
68171  if( db->mallocFailed ){
68172    return;
68173  }
68174  if( !db->init.busy ){
68175    sqlite3ViewGetColumnNames(pParse, p);
68176  }
68177
68178  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
68179  ** the end.
68180  */
68181  sEnd = pParse->sLastToken;
68182  if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
68183    sEnd.z += sEnd.n;
68184  }
68185  sEnd.n = 0;
68186  n = (int)(sEnd.z - pBegin->z);
68187  z = pBegin->z;
68188  while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
68189  sEnd.z = &z[n-1];
68190  sEnd.n = 1;
68191
68192  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
68193  sqlite3EndTable(pParse, 0, &sEnd, 0);
68194  return;
68195}
68196#endif /* SQLITE_OMIT_VIEW */
68197
68198#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
68199/*
68200** The Table structure pTable is really a VIEW.  Fill in the names of
68201** the columns of the view in the pTable structure.  Return the number
68202** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
68203*/
68204SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
68205  Table *pSelTab;   /* A fake table from which we get the result set */
68206  Select *pSel;     /* Copy of the SELECT that implements the view */
68207  int nErr = 0;     /* Number of errors encountered */
68208  int n;            /* Temporarily holds the number of cursors assigned */
68209  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
68210  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
68211
68212  assert( pTable );
68213
68214#ifndef SQLITE_OMIT_VIRTUALTABLE
68215  if( sqlite3VtabCallConnect(pParse, pTable) ){
68216    return SQLITE_ERROR;
68217  }
68218  if( IsVirtual(pTable) ) return 0;
68219#endif
68220
68221#ifndef SQLITE_OMIT_VIEW
68222  /* A positive nCol means the columns names for this view are
68223  ** already known.
68224  */
68225  if( pTable->nCol>0 ) return 0;
68226
68227  /* A negative nCol is a special marker meaning that we are currently
68228  ** trying to compute the column names.  If we enter this routine with
68229  ** a negative nCol, it means two or more views form a loop, like this:
68230  **
68231  **     CREATE VIEW one AS SELECT * FROM two;
68232  **     CREATE VIEW two AS SELECT * FROM one;
68233  **
68234  ** Actually, the error above is now caught prior to reaching this point.
68235  ** But the following test is still important as it does come up
68236  ** in the following:
68237  **
68238  **     CREATE TABLE main.ex1(a);
68239  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
68240  **     SELECT * FROM temp.ex1;
68241  */
68242  if( pTable->nCol<0 ){
68243    sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
68244    return 1;
68245  }
68246  assert( pTable->nCol>=0 );
68247
68248  /* If we get this far, it means we need to compute the table names.
68249  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
68250  ** "*" elements in the results set of the view and will assign cursors
68251  ** to the elements of the FROM clause.  But we do not want these changes
68252  ** to be permanent.  So the computation is done on a copy of the SELECT
68253  ** statement that defines the view.
68254  */
68255  assert( pTable->pSelect );
68256  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
68257  if( pSel ){
68258    u8 enableLookaside = db->lookaside.bEnabled;
68259    n = pParse->nTab;
68260    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
68261    pTable->nCol = -1;
68262    db->lookaside.bEnabled = 0;
68263#ifndef SQLITE_OMIT_AUTHORIZATION
68264    xAuth = db->xAuth;
68265    db->xAuth = 0;
68266    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
68267    db->xAuth = xAuth;
68268#else
68269    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
68270#endif
68271    db->lookaside.bEnabled = enableLookaside;
68272    pParse->nTab = n;
68273    if( pSelTab ){
68274      assert( pTable->aCol==0 );
68275      pTable->nCol = pSelTab->nCol;
68276      pTable->aCol = pSelTab->aCol;
68277      pSelTab->nCol = 0;
68278      pSelTab->aCol = 0;
68279      sqlite3DeleteTable(pSelTab);
68280      pTable->pSchema->flags |= DB_UnresetViews;
68281    }else{
68282      pTable->nCol = 0;
68283      nErr++;
68284    }
68285    sqlite3SelectDelete(db, pSel);
68286  } else {
68287    nErr++;
68288  }
68289#endif /* SQLITE_OMIT_VIEW */
68290  return nErr;
68291}
68292#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
68293
68294#ifndef SQLITE_OMIT_VIEW
68295/*
68296** Clear the column names from every VIEW in database idx.
68297*/
68298static void sqliteViewResetAll(sqlite3 *db, int idx){
68299  HashElem *i;
68300  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
68301  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
68302    Table *pTab = sqliteHashData(i);
68303    if( pTab->pSelect ){
68304      sqliteResetColumnNames(pTab);
68305    }
68306  }
68307  DbClearProperty(db, idx, DB_UnresetViews);
68308}
68309#else
68310# define sqliteViewResetAll(A,B)
68311#endif /* SQLITE_OMIT_VIEW */
68312
68313/*
68314** This function is called by the VDBE to adjust the internal schema
68315** used by SQLite when the btree layer moves a table root page. The
68316** root-page of a table or index in database iDb has changed from iFrom
68317** to iTo.
68318**
68319** Ticket #1728:  The symbol table might still contain information
68320** on tables and/or indices that are the process of being deleted.
68321** If you are unlucky, one of those deleted indices or tables might
68322** have the same rootpage number as the real table or index that is
68323** being moved.  So we cannot stop searching after the first match
68324** because the first match might be for one of the deleted indices
68325** or tables and not the table/index that is actually being moved.
68326** We must continue looping until all tables and indices with
68327** rootpage==iFrom have been converted to have a rootpage of iTo
68328** in order to be certain that we got the right one.
68329*/
68330#ifndef SQLITE_OMIT_AUTOVACUUM
68331SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
68332  HashElem *pElem;
68333  Hash *pHash;
68334
68335  pHash = &pDb->pSchema->tblHash;
68336  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
68337    Table *pTab = sqliteHashData(pElem);
68338    if( pTab->tnum==iFrom ){
68339      pTab->tnum = iTo;
68340    }
68341  }
68342  pHash = &pDb->pSchema->idxHash;
68343  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
68344    Index *pIdx = sqliteHashData(pElem);
68345    if( pIdx->tnum==iFrom ){
68346      pIdx->tnum = iTo;
68347    }
68348  }
68349}
68350#endif
68351
68352/*
68353** Write code to erase the table with root-page iTable from database iDb.
68354** Also write code to modify the sqlite_master table and internal schema
68355** if a root-page of another table is moved by the btree-layer whilst
68356** erasing iTable (this can happen with an auto-vacuum database).
68357*/
68358static void destroyRootPage(Parse *pParse, int iTable, int iDb){
68359  Vdbe *v = sqlite3GetVdbe(pParse);
68360  int r1 = sqlite3GetTempReg(pParse);
68361  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
68362  sqlite3MayAbort(pParse);
68363#ifndef SQLITE_OMIT_AUTOVACUUM
68364  /* OP_Destroy stores an in integer r1. If this integer
68365  ** is non-zero, then it is the root page number of a table moved to
68366  ** location iTable. The following code modifies the sqlite_master table to
68367  ** reflect this.
68368  **
68369  ** The "#NNN" in the SQL is a special constant that means whatever value
68370  ** is in register NNN.  See grammar rules associated with the TK_REGISTER
68371  ** token for additional information.
68372  */
68373  sqlite3NestedParse(pParse,
68374     "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
68375     pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
68376#endif
68377  sqlite3ReleaseTempReg(pParse, r1);
68378}
68379
68380/*
68381** Write VDBE code to erase table pTab and all associated indices on disk.
68382** Code to update the sqlite_master tables and internal schema definitions
68383** in case a root-page belonging to another table is moved by the btree layer
68384** is also added (this can happen with an auto-vacuum database).
68385*/
68386static void destroyTable(Parse *pParse, Table *pTab){
68387#ifdef SQLITE_OMIT_AUTOVACUUM
68388  Index *pIdx;
68389  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
68390  destroyRootPage(pParse, pTab->tnum, iDb);
68391  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
68392    destroyRootPage(pParse, pIdx->tnum, iDb);
68393  }
68394#else
68395  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
68396  ** is not defined), then it is important to call OP_Destroy on the
68397  ** table and index root-pages in order, starting with the numerically
68398  ** largest root-page number. This guarantees that none of the root-pages
68399  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
68400  ** following were coded:
68401  **
68402  ** OP_Destroy 4 0
68403  ** ...
68404  ** OP_Destroy 5 0
68405  **
68406  ** and root page 5 happened to be the largest root-page number in the
68407  ** database, then root page 5 would be moved to page 4 by the
68408  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
68409  ** a free-list page.
68410  */
68411  int iTab = pTab->tnum;
68412  int iDestroyed = 0;
68413
68414  while( 1 ){
68415    Index *pIdx;
68416    int iLargest = 0;
68417
68418    if( iDestroyed==0 || iTab<iDestroyed ){
68419      iLargest = iTab;
68420    }
68421    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
68422      int iIdx = pIdx->tnum;
68423      assert( pIdx->pSchema==pTab->pSchema );
68424      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
68425        iLargest = iIdx;
68426      }
68427    }
68428    if( iLargest==0 ){
68429      return;
68430    }else{
68431      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
68432      destroyRootPage(pParse, iLargest, iDb);
68433      iDestroyed = iLargest;
68434    }
68435  }
68436#endif
68437}
68438
68439/*
68440** This routine is called to do the work of a DROP TABLE statement.
68441** pName is the name of the table to be dropped.
68442*/
68443SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
68444  Table *pTab;
68445  Vdbe *v;
68446  sqlite3 *db = pParse->db;
68447  int iDb;
68448
68449  if( db->mallocFailed ){
68450    goto exit_drop_table;
68451  }
68452  assert( pParse->nErr==0 );
68453  assert( pName->nSrc==1 );
68454  if( noErr ) db->suppressErr++;
68455  pTab = sqlite3LocateTable(pParse, isView,
68456                            pName->a[0].zName, pName->a[0].zDatabase);
68457  if( noErr ) db->suppressErr--;
68458
68459  if( pTab==0 ){
68460    goto exit_drop_table;
68461  }
68462  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
68463  assert( iDb>=0 && iDb<db->nDb );
68464
68465  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
68466  ** it is initialized.
68467  */
68468  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
68469    goto exit_drop_table;
68470  }
68471#ifndef SQLITE_OMIT_AUTHORIZATION
68472  {
68473    int code;
68474    const char *zTab = SCHEMA_TABLE(iDb);
68475    const char *zDb = db->aDb[iDb].zName;
68476    const char *zArg2 = 0;
68477    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
68478      goto exit_drop_table;
68479    }
68480    if( isView ){
68481      if( !OMIT_TEMPDB && iDb==1 ){
68482        code = SQLITE_DROP_TEMP_VIEW;
68483      }else{
68484        code = SQLITE_DROP_VIEW;
68485      }
68486#ifndef SQLITE_OMIT_VIRTUALTABLE
68487    }else if( IsVirtual(pTab) ){
68488      code = SQLITE_DROP_VTABLE;
68489      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
68490#endif
68491    }else{
68492      if( !OMIT_TEMPDB && iDb==1 ){
68493        code = SQLITE_DROP_TEMP_TABLE;
68494      }else{
68495        code = SQLITE_DROP_TABLE;
68496      }
68497    }
68498    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
68499      goto exit_drop_table;
68500    }
68501    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
68502      goto exit_drop_table;
68503    }
68504  }
68505#endif
68506  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
68507    sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
68508    goto exit_drop_table;
68509  }
68510
68511#ifndef SQLITE_OMIT_VIEW
68512  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
68513  ** on a table.
68514  */
68515  if( isView && pTab->pSelect==0 ){
68516    sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
68517    goto exit_drop_table;
68518  }
68519  if( !isView && pTab->pSelect ){
68520    sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
68521    goto exit_drop_table;
68522  }
68523#endif
68524
68525  /* Generate code to remove the table from the master table
68526  ** on disk.
68527  */
68528  v = sqlite3GetVdbe(pParse);
68529  if( v ){
68530    Trigger *pTrigger;
68531    Db *pDb = &db->aDb[iDb];
68532    sqlite3BeginWriteOperation(pParse, 1, iDb);
68533
68534#ifndef SQLITE_OMIT_VIRTUALTABLE
68535    if( IsVirtual(pTab) ){
68536      sqlite3VdbeAddOp0(v, OP_VBegin);
68537    }
68538#endif
68539    sqlite3FkDropTable(pParse, pName, pTab);
68540
68541    /* Drop all triggers associated with the table being dropped. Code
68542    ** is generated to remove entries from sqlite_master and/or
68543    ** sqlite_temp_master if required.
68544    */
68545    pTrigger = sqlite3TriggerList(pParse, pTab);
68546    while( pTrigger ){
68547      assert( pTrigger->pSchema==pTab->pSchema ||
68548          pTrigger->pSchema==db->aDb[1].pSchema );
68549      sqlite3DropTriggerPtr(pParse, pTrigger);
68550      pTrigger = pTrigger->pNext;
68551    }
68552
68553#ifndef SQLITE_OMIT_AUTOINCREMENT
68554    /* Remove any entries of the sqlite_sequence table associated with
68555    ** the table being dropped. This is done before the table is dropped
68556    ** at the btree level, in case the sqlite_sequence table needs to
68557    ** move as a result of the drop (can happen in auto-vacuum mode).
68558    */
68559    if( pTab->tabFlags & TF_Autoincrement ){
68560      sqlite3NestedParse(pParse,
68561        "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
68562        pDb->zName, pTab->zName
68563      );
68564    }
68565#endif
68566
68567    /* Drop all SQLITE_MASTER table and index entries that refer to the
68568    ** table. The program name loops through the master table and deletes
68569    ** every row that refers to a table of the same name as the one being
68570    ** dropped. Triggers are handled seperately because a trigger can be
68571    ** created in the temp database that refers to a table in another
68572    ** database.
68573    */
68574    sqlite3NestedParse(pParse,
68575        "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
68576        pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
68577
68578    /* Drop any statistics from the sqlite_stat1 table, if it exists */
68579    if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
68580      sqlite3NestedParse(pParse,
68581        "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
68582      );
68583    }
68584
68585    if( !isView && !IsVirtual(pTab) ){
68586      destroyTable(pParse, pTab);
68587    }
68588
68589    /* Remove the table entry from SQLite's internal schema and modify
68590    ** the schema cookie.
68591    */
68592    if( IsVirtual(pTab) ){
68593      sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
68594    }
68595    sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
68596    sqlite3ChangeCookie(pParse, iDb);
68597  }
68598  sqliteViewResetAll(db, iDb);
68599
68600exit_drop_table:
68601  sqlite3SrcListDelete(db, pName);
68602}
68603
68604/*
68605** This routine is called to create a new foreign key on the table
68606** currently under construction.  pFromCol determines which columns
68607** in the current table point to the foreign key.  If pFromCol==0 then
68608** connect the key to the last column inserted.  pTo is the name of
68609** the table referred to.  pToCol is a list of tables in the other
68610** pTo table that the foreign key points to.  flags contains all
68611** information about the conflict resolution algorithms specified
68612** in the ON DELETE, ON UPDATE and ON INSERT clauses.
68613**
68614** An FKey structure is created and added to the table currently
68615** under construction in the pParse->pNewTable field.
68616**
68617** The foreign key is set for IMMEDIATE processing.  A subsequent call
68618** to sqlite3DeferForeignKey() might change this to DEFERRED.
68619*/
68620SQLITE_PRIVATE void sqlite3CreateForeignKey(
68621  Parse *pParse,       /* Parsing context */
68622  ExprList *pFromCol,  /* Columns in this table that point to other table */
68623  Token *pTo,          /* Name of the other table */
68624  ExprList *pToCol,    /* Columns in the other table */
68625  int flags            /* Conflict resolution algorithms. */
68626){
68627  sqlite3 *db = pParse->db;
68628#ifndef SQLITE_OMIT_FOREIGN_KEY
68629  FKey *pFKey = 0;
68630  FKey *pNextTo;
68631  Table *p = pParse->pNewTable;
68632  int nByte;
68633  int i;
68634  int nCol;
68635  char *z;
68636
68637  assert( pTo!=0 );
68638  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
68639  if( pFromCol==0 ){
68640    int iCol = p->nCol-1;
68641    if( NEVER(iCol<0) ) goto fk_end;
68642    if( pToCol && pToCol->nExpr!=1 ){
68643      sqlite3ErrorMsg(pParse, "foreign key on %s"
68644         " should reference only one column of table %T",
68645         p->aCol[iCol].zName, pTo);
68646      goto fk_end;
68647    }
68648    nCol = 1;
68649  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
68650    sqlite3ErrorMsg(pParse,
68651        "number of columns in foreign key does not match the number of "
68652        "columns in the referenced table");
68653    goto fk_end;
68654  }else{
68655    nCol = pFromCol->nExpr;
68656  }
68657  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
68658  if( pToCol ){
68659    for(i=0; i<pToCol->nExpr; i++){
68660      nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
68661    }
68662  }
68663  pFKey = sqlite3DbMallocZero(db, nByte );
68664  if( pFKey==0 ){
68665    goto fk_end;
68666  }
68667  pFKey->pFrom = p;
68668  pFKey->pNextFrom = p->pFKey;
68669  z = (char*)&pFKey->aCol[nCol];
68670  pFKey->zTo = z;
68671  memcpy(z, pTo->z, pTo->n);
68672  z[pTo->n] = 0;
68673  sqlite3Dequote(z);
68674  z += pTo->n+1;
68675  pFKey->nCol = nCol;
68676  if( pFromCol==0 ){
68677    pFKey->aCol[0].iFrom = p->nCol-1;
68678  }else{
68679    for(i=0; i<nCol; i++){
68680      int j;
68681      for(j=0; j<p->nCol; j++){
68682        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
68683          pFKey->aCol[i].iFrom = j;
68684          break;
68685        }
68686      }
68687      if( j>=p->nCol ){
68688        sqlite3ErrorMsg(pParse,
68689          "unknown column \"%s\" in foreign key definition",
68690          pFromCol->a[i].zName);
68691        goto fk_end;
68692      }
68693    }
68694  }
68695  if( pToCol ){
68696    for(i=0; i<nCol; i++){
68697      int n = sqlite3Strlen30(pToCol->a[i].zName);
68698      pFKey->aCol[i].zCol = z;
68699      memcpy(z, pToCol->a[i].zName, n);
68700      z[n] = 0;
68701      z += n+1;
68702    }
68703  }
68704  pFKey->isDeferred = 0;
68705  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
68706  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
68707
68708  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
68709      pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
68710  );
68711  if( pNextTo==pFKey ){
68712    db->mallocFailed = 1;
68713    goto fk_end;
68714  }
68715  if( pNextTo ){
68716    assert( pNextTo->pPrevTo==0 );
68717    pFKey->pNextTo = pNextTo;
68718    pNextTo->pPrevTo = pFKey;
68719  }
68720
68721  /* Link the foreign key to the table as the last step.
68722  */
68723  p->pFKey = pFKey;
68724  pFKey = 0;
68725
68726fk_end:
68727  sqlite3DbFree(db, pFKey);
68728#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
68729  sqlite3ExprListDelete(db, pFromCol);
68730  sqlite3ExprListDelete(db, pToCol);
68731}
68732
68733/*
68734** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
68735** clause is seen as part of a foreign key definition.  The isDeferred
68736** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
68737** The behavior of the most recently created foreign key is adjusted
68738** accordingly.
68739*/
68740SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
68741#ifndef SQLITE_OMIT_FOREIGN_KEY
68742  Table *pTab;
68743  FKey *pFKey;
68744  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
68745  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
68746  pFKey->isDeferred = (u8)isDeferred;
68747#endif
68748}
68749
68750/*
68751** Generate code that will erase and refill index *pIdx.  This is
68752** used to initialize a newly created index or to recompute the
68753** content of an index in response to a REINDEX command.
68754**
68755** if memRootPage is not negative, it means that the index is newly
68756** created.  The register specified by memRootPage contains the
68757** root page number of the index.  If memRootPage is negative, then
68758** the index already exists and must be cleared before being refilled and
68759** the root page number of the index is taken from pIndex->tnum.
68760*/
68761static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
68762  Table *pTab = pIndex->pTable;  /* The table that is indexed */
68763  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
68764  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
68765  int addr1;                     /* Address of top of loop */
68766  int tnum;                      /* Root page of index */
68767  Vdbe *v;                       /* Generate code into this virtual machine */
68768  KeyInfo *pKey;                 /* KeyInfo for index */
68769  int regIdxKey;                 /* Registers containing the index key */
68770  int regRecord;                 /* Register holding assemblied index record */
68771  sqlite3 *db = pParse->db;      /* The database connection */
68772  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
68773
68774#ifndef SQLITE_OMIT_AUTHORIZATION
68775  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
68776      db->aDb[iDb].zName ) ){
68777    return;
68778  }
68779#endif
68780
68781  /* Require a write-lock on the table to perform this operation */
68782  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
68783
68784  v = sqlite3GetVdbe(pParse);
68785  if( v==0 ) return;
68786  if( memRootPage>=0 ){
68787    tnum = memRootPage;
68788  }else{
68789    tnum = pIndex->tnum;
68790    sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
68791  }
68792  pKey = sqlite3IndexKeyinfo(pParse, pIndex);
68793  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
68794                    (char *)pKey, P4_KEYINFO_HANDOFF);
68795  if( memRootPage>=0 ){
68796    sqlite3VdbeChangeP5(v, 1);
68797  }
68798  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
68799  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
68800  regRecord = sqlite3GetTempReg(pParse);
68801  regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
68802  if( pIndex->onError!=OE_None ){
68803    const int regRowid = regIdxKey + pIndex->nColumn;
68804    const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
68805    void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
68806
68807    /* The registers accessed by the OP_IsUnique opcode were allocated
68808    ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
68809    ** call above. Just before that function was freed they were released
68810    ** (made available to the compiler for reuse) using
68811    ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
68812    ** opcode use the values stored within seems dangerous. However, since
68813    ** we can be sure that no other temp registers have been allocated
68814    ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
68815    */
68816    sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
68817    sqlite3HaltConstraint(
68818        pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
68819  }
68820  sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
68821  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
68822  sqlite3ReleaseTempReg(pParse, regRecord);
68823  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
68824  sqlite3VdbeJumpHere(v, addr1);
68825  sqlite3VdbeAddOp1(v, OP_Close, iTab);
68826  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
68827}
68828
68829/*
68830** Create a new index for an SQL table.  pName1.pName2 is the name of the index
68831** and pTblList is the name of the table that is to be indexed.  Both will
68832** be NULL for a primary key or an index that is created to satisfy a
68833** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
68834** as the table to be indexed.  pParse->pNewTable is a table that is
68835** currently being constructed by a CREATE TABLE statement.
68836**
68837** pList is a list of columns to be indexed.  pList will be NULL if this
68838** is a primary key or unique-constraint on the most recent column added
68839** to the table currently under construction.
68840**
68841** If the index is created successfully, return a pointer to the new Index
68842** structure. This is used by sqlite3AddPrimaryKey() to mark the index
68843** as the tables primary key (Index.autoIndex==2).
68844*/
68845SQLITE_PRIVATE Index *sqlite3CreateIndex(
68846  Parse *pParse,     /* All information about this parse */
68847  Token *pName1,     /* First part of index name. May be NULL */
68848  Token *pName2,     /* Second part of index name. May be NULL */
68849  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
68850  ExprList *pList,   /* A list of columns to be indexed */
68851  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
68852  Token *pStart,     /* The CREATE token that begins this statement */
68853  Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
68854  int sortOrder,     /* Sort order of primary key when pList==NULL */
68855  int ifNotExist     /* Omit error if index already exists */
68856){
68857  Index *pRet = 0;     /* Pointer to return */
68858  Table *pTab = 0;     /* Table to be indexed */
68859  Index *pIndex = 0;   /* The index to be created */
68860  char *zName = 0;     /* Name of the index */
68861  int nName;           /* Number of characters in zName */
68862  int i, j;
68863  Token nullId;        /* Fake token for an empty ID list */
68864  DbFixer sFix;        /* For assigning database names to pTable */
68865  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
68866  sqlite3 *db = pParse->db;
68867  Db *pDb;             /* The specific table containing the indexed database */
68868  int iDb;             /* Index of the database that is being written */
68869  Token *pName = 0;    /* Unqualified name of the index to create */
68870  struct ExprList_item *pListItem; /* For looping over pList */
68871  int nCol;
68872  int nExtra = 0;
68873  char *zExtra;
68874
68875  assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
68876  assert( pParse->nErr==0 );      /* Never called with prior errors */
68877  if( db->mallocFailed || IN_DECLARE_VTAB ){
68878    goto exit_create_index;
68879  }
68880  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
68881    goto exit_create_index;
68882  }
68883
68884  /*
68885  ** Find the table that is to be indexed.  Return early if not found.
68886  */
68887  if( pTblName!=0 ){
68888
68889    /* Use the two-part index name to determine the database
68890    ** to search for the table. 'Fix' the table name to this db
68891    ** before looking up the table.
68892    */
68893    assert( pName1 && pName2 );
68894    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
68895    if( iDb<0 ) goto exit_create_index;
68896
68897#ifndef SQLITE_OMIT_TEMPDB
68898    /* If the index name was unqualified, check if the the table
68899    ** is a temp table. If so, set the database to 1. Do not do this
68900    ** if initialising a database schema.
68901    */
68902    if( !db->init.busy ){
68903      pTab = sqlite3SrcListLookup(pParse, pTblName);
68904      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
68905        iDb = 1;
68906      }
68907    }
68908#endif
68909
68910    if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
68911        sqlite3FixSrcList(&sFix, pTblName)
68912    ){
68913      /* Because the parser constructs pTblName from a single identifier,
68914      ** sqlite3FixSrcList can never fail. */
68915      assert(0);
68916    }
68917    pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
68918        pTblName->a[0].zDatabase);
68919    if( !pTab || db->mallocFailed ) goto exit_create_index;
68920    assert( db->aDb[iDb].pSchema==pTab->pSchema );
68921  }else{
68922    assert( pName==0 );
68923    pTab = pParse->pNewTable;
68924    if( !pTab ) goto exit_create_index;
68925    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
68926  }
68927  pDb = &db->aDb[iDb];
68928
68929  assert( pTab!=0 );
68930  assert( pParse->nErr==0 );
68931  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
68932       && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
68933    sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
68934    goto exit_create_index;
68935  }
68936#ifndef SQLITE_OMIT_VIEW
68937  if( pTab->pSelect ){
68938    sqlite3ErrorMsg(pParse, "views may not be indexed");
68939    goto exit_create_index;
68940  }
68941#endif
68942#ifndef SQLITE_OMIT_VIRTUALTABLE
68943  if( IsVirtual(pTab) ){
68944    sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
68945    goto exit_create_index;
68946  }
68947#endif
68948
68949  /*
68950  ** Find the name of the index.  Make sure there is not already another
68951  ** index or table with the same name.
68952  **
68953  ** Exception:  If we are reading the names of permanent indices from the
68954  ** sqlite_master table (because some other process changed the schema) and
68955  ** one of the index names collides with the name of a temporary table or
68956  ** index, then we will continue to process this index.
68957  **
68958  ** If pName==0 it means that we are
68959  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
68960  ** own name.
68961  */
68962  if( pName ){
68963    zName = sqlite3NameFromToken(db, pName);
68964    if( zName==0 ) goto exit_create_index;
68965    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
68966      goto exit_create_index;
68967    }
68968    if( !db->init.busy ){
68969      if( sqlite3FindTable(db, zName, 0)!=0 ){
68970        sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
68971        goto exit_create_index;
68972      }
68973    }
68974    if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
68975      if( !ifNotExist ){
68976        sqlite3ErrorMsg(pParse, "index %s already exists", zName);
68977      }
68978      goto exit_create_index;
68979    }
68980  }else{
68981    int n;
68982    Index *pLoop;
68983    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
68984    zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
68985    if( zName==0 ){
68986      goto exit_create_index;
68987    }
68988  }
68989
68990  /* Check for authorization to create an index.
68991  */
68992#ifndef SQLITE_OMIT_AUTHORIZATION
68993  {
68994    const char *zDb = pDb->zName;
68995    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
68996      goto exit_create_index;
68997    }
68998    i = SQLITE_CREATE_INDEX;
68999    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
69000    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
69001      goto exit_create_index;
69002    }
69003  }
69004#endif
69005
69006  /* If pList==0, it means this routine was called to make a primary
69007  ** key out of the last column added to the table under construction.
69008  ** So create a fake list to simulate this.
69009  */
69010  if( pList==0 ){
69011    nullId.z = pTab->aCol[pTab->nCol-1].zName;
69012    nullId.n = sqlite3Strlen30((char*)nullId.z);
69013    pList = sqlite3ExprListAppend(pParse, 0, 0);
69014    if( pList==0 ) goto exit_create_index;
69015    sqlite3ExprListSetName(pParse, pList, &nullId, 0);
69016    pList->a[0].sortOrder = (u8)sortOrder;
69017  }
69018
69019  /* Figure out how many bytes of space are required to store explicitly
69020  ** specified collation sequence names.
69021  */
69022  for(i=0; i<pList->nExpr; i++){
69023    Expr *pExpr = pList->a[i].pExpr;
69024    if( pExpr ){
69025      CollSeq *pColl = pExpr->pColl;
69026      /* Either pColl!=0 or there was an OOM failure.  But if an OOM
69027      ** failure we have quit before reaching this point. */
69028      if( ALWAYS(pColl) ){
69029        nExtra += (1 + sqlite3Strlen30(pColl->zName));
69030      }
69031    }
69032  }
69033
69034  /*
69035  ** Allocate the index structure.
69036  */
69037  nName = sqlite3Strlen30(zName);
69038  nCol = pList->nExpr;
69039  pIndex = sqlite3DbMallocZero(db,
69040      sizeof(Index) +              /* Index structure  */
69041      sizeof(int)*nCol +           /* Index.aiColumn   */
69042      sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
69043      sizeof(char *)*nCol +        /* Index.azColl     */
69044      sizeof(u8)*nCol +            /* Index.aSortOrder */
69045      nName + 1 +                  /* Index.zName      */
69046      nExtra                       /* Collation sequence names */
69047  );
69048  if( db->mallocFailed ){
69049    goto exit_create_index;
69050  }
69051  pIndex->azColl = (char**)(&pIndex[1]);
69052  pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
69053  pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
69054  pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
69055  pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
69056  zExtra = (char *)(&pIndex->zName[nName+1]);
69057  memcpy(pIndex->zName, zName, nName+1);
69058  pIndex->pTable = pTab;
69059  pIndex->nColumn = pList->nExpr;
69060  pIndex->onError = (u8)onError;
69061  pIndex->autoIndex = (u8)(pName==0);
69062  pIndex->pSchema = db->aDb[iDb].pSchema;
69063
69064  /* Check to see if we should honor DESC requests on index columns
69065  */
69066  if( pDb->pSchema->file_format>=4 ){
69067    sortOrderMask = -1;   /* Honor DESC */
69068  }else{
69069    sortOrderMask = 0;    /* Ignore DESC */
69070  }
69071
69072  /* Scan the names of the columns of the table to be indexed and
69073  ** load the column indices into the Index structure.  Report an error
69074  ** if any column is not found.
69075  **
69076  ** TODO:  Add a test to make sure that the same column is not named
69077  ** more than once within the same index.  Only the first instance of
69078  ** the column will ever be used by the optimizer.  Note that using the
69079  ** same column more than once cannot be an error because that would
69080  ** break backwards compatibility - it needs to be a warning.
69081  */
69082  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
69083    const char *zColName = pListItem->zName;
69084    Column *pTabCol;
69085    int requestedSortOrder;
69086    char *zColl;                   /* Collation sequence name */
69087
69088    for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
69089      if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
69090    }
69091    if( j>=pTab->nCol ){
69092      sqlite3ErrorMsg(pParse, "table %s has no column named %s",
69093        pTab->zName, zColName);
69094      goto exit_create_index;
69095    }
69096    pIndex->aiColumn[i] = j;
69097    /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
69098    ** the way the "idxlist" non-terminal is constructed by the parser,
69099    ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
69100    ** must exist or else there must have been an OOM error.  But if there
69101    ** was an OOM error, we would never reach this point. */
69102    if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
69103      int nColl;
69104      zColl = pListItem->pExpr->pColl->zName;
69105      nColl = sqlite3Strlen30(zColl) + 1;
69106      assert( nExtra>=nColl );
69107      memcpy(zExtra, zColl, nColl);
69108      zColl = zExtra;
69109      zExtra += nColl;
69110      nExtra -= nColl;
69111    }else{
69112      zColl = pTab->aCol[j].zColl;
69113      if( !zColl ){
69114        zColl = db->pDfltColl->zName;
69115      }
69116    }
69117    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
69118      goto exit_create_index;
69119    }
69120    pIndex->azColl[i] = zColl;
69121    requestedSortOrder = pListItem->sortOrder & sortOrderMask;
69122    pIndex->aSortOrder[i] = (u8)requestedSortOrder;
69123  }
69124  sqlite3DefaultRowEst(pIndex);
69125
69126  if( pTab==pParse->pNewTable ){
69127    /* This routine has been called to create an automatic index as a
69128    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
69129    ** a PRIMARY KEY or UNIQUE clause following the column definitions.
69130    ** i.e. one of:
69131    **
69132    ** CREATE TABLE t(x PRIMARY KEY, y);
69133    ** CREATE TABLE t(x, y, UNIQUE(x, y));
69134    **
69135    ** Either way, check to see if the table already has such an index. If
69136    ** so, don't bother creating this one. This only applies to
69137    ** automatically created indices. Users can do as they wish with
69138    ** explicit indices.
69139    **
69140    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
69141    ** (and thus suppressing the second one) even if they have different
69142    ** sort orders.
69143    **
69144    ** If there are different collating sequences or if the columns of
69145    ** the constraint occur in different orders, then the constraints are
69146    ** considered distinct and both result in separate indices.
69147    */
69148    Index *pIdx;
69149    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
69150      int k;
69151      assert( pIdx->onError!=OE_None );
69152      assert( pIdx->autoIndex );
69153      assert( pIndex->onError!=OE_None );
69154
69155      if( pIdx->nColumn!=pIndex->nColumn ) continue;
69156      for(k=0; k<pIdx->nColumn; k++){
69157        const char *z1;
69158        const char *z2;
69159        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
69160        z1 = pIdx->azColl[k];
69161        z2 = pIndex->azColl[k];
69162        if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
69163      }
69164      if( k==pIdx->nColumn ){
69165        if( pIdx->onError!=pIndex->onError ){
69166          /* This constraint creates the same index as a previous
69167          ** constraint specified somewhere in the CREATE TABLE statement.
69168          ** However the ON CONFLICT clauses are different. If both this
69169          ** constraint and the previous equivalent constraint have explicit
69170          ** ON CONFLICT clauses this is an error. Otherwise, use the
69171          ** explicitly specified behaviour for the index.
69172          */
69173          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
69174            sqlite3ErrorMsg(pParse,
69175                "conflicting ON CONFLICT clauses specified", 0);
69176          }
69177          if( pIdx->onError==OE_Default ){
69178            pIdx->onError = pIndex->onError;
69179          }
69180        }
69181        goto exit_create_index;
69182      }
69183    }
69184  }
69185
69186  /* Link the new Index structure to its table and to the other
69187  ** in-memory database structures.
69188  */
69189  if( db->init.busy ){
69190    Index *p;
69191    p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
69192                          pIndex->zName, sqlite3Strlen30(pIndex->zName),
69193                          pIndex);
69194    if( p ){
69195      assert( p==pIndex );  /* Malloc must have failed */
69196      db->mallocFailed = 1;
69197      goto exit_create_index;
69198    }
69199    db->flags |= SQLITE_InternChanges;
69200    if( pTblName!=0 ){
69201      pIndex->tnum = db->init.newTnum;
69202    }
69203  }
69204
69205  /* If the db->init.busy is 0 then create the index on disk.  This
69206  ** involves writing the index into the master table and filling in the
69207  ** index with the current table contents.
69208  **
69209  ** The db->init.busy is 0 when the user first enters a CREATE INDEX
69210  ** command.  db->init.busy is 1 when a database is opened and
69211  ** CREATE INDEX statements are read out of the master table.  In
69212  ** the latter case the index already exists on disk, which is why
69213  ** we don't want to recreate it.
69214  **
69215  ** If pTblName==0 it means this index is generated as a primary key
69216  ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
69217  ** has just been created, it contains no data and the index initialization
69218  ** step can be skipped.
69219  */
69220  else{ /* if( db->init.busy==0 ) */
69221    Vdbe *v;
69222    char *zStmt;
69223    int iMem = ++pParse->nMem;
69224
69225    v = sqlite3GetVdbe(pParse);
69226    if( v==0 ) goto exit_create_index;
69227
69228
69229    /* Create the rootpage for the index
69230    */
69231    sqlite3BeginWriteOperation(pParse, 1, iDb);
69232    sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
69233
69234    /* Gather the complete text of the CREATE INDEX statement into
69235    ** the zStmt variable
69236    */
69237    if( pStart ){
69238      assert( pEnd!=0 );
69239      /* A named index with an explicit CREATE INDEX statement */
69240      zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
69241        onError==OE_None ? "" : " UNIQUE",
69242        pEnd->z - pName->z + 1,
69243        pName->z);
69244    }else{
69245      /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
69246      /* zStmt = sqlite3MPrintf(""); */
69247      zStmt = 0;
69248    }
69249
69250    /* Add an entry in sqlite_master for this index
69251    */
69252    sqlite3NestedParse(pParse,
69253        "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
69254        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
69255        pIndex->zName,
69256        pTab->zName,
69257        iMem,
69258        zStmt
69259    );
69260    sqlite3DbFree(db, zStmt);
69261
69262    /* Fill the index with data and reparse the schema. Code an OP_Expire
69263    ** to invalidate all pre-compiled statements.
69264    */
69265    if( pTblName ){
69266      sqlite3RefillIndex(pParse, pIndex, iMem);
69267      sqlite3ChangeCookie(pParse, iDb);
69268      sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
69269         sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
69270      sqlite3VdbeAddOp1(v, OP_Expire, 0);
69271    }
69272  }
69273
69274  /* When adding an index to the list of indices for a table, make
69275  ** sure all indices labeled OE_Replace come after all those labeled
69276  ** OE_Ignore.  This is necessary for the correct constraint check
69277  ** processing (in sqlite3GenerateConstraintChecks()) as part of
69278  ** UPDATE and INSERT statements.
69279  */
69280  if( db->init.busy || pTblName==0 ){
69281    if( onError!=OE_Replace || pTab->pIndex==0
69282         || pTab->pIndex->onError==OE_Replace){
69283      pIndex->pNext = pTab->pIndex;
69284      pTab->pIndex = pIndex;
69285    }else{
69286      Index *pOther = pTab->pIndex;
69287      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
69288        pOther = pOther->pNext;
69289      }
69290      pIndex->pNext = pOther->pNext;
69291      pOther->pNext = pIndex;
69292    }
69293    pRet = pIndex;
69294    pIndex = 0;
69295  }
69296
69297  /* Clean up before exiting */
69298exit_create_index:
69299  if( pIndex ){
69300    sqlite3_free(pIndex->zColAff);
69301    sqlite3DbFree(db, pIndex);
69302  }
69303  sqlite3ExprListDelete(db, pList);
69304  sqlite3SrcListDelete(db, pTblName);
69305  sqlite3DbFree(db, zName);
69306  return pRet;
69307}
69308
69309/*
69310** Fill the Index.aiRowEst[] array with default information - information
69311** to be used when we have not run the ANALYZE command.
69312**
69313** aiRowEst[0] is suppose to contain the number of elements in the index.
69314** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
69315** number of rows in the table that match any particular value of the
69316** first column of the index.  aiRowEst[2] is an estimate of the number
69317** of rows that match any particular combiniation of the first 2 columns
69318** of the index.  And so forth.  It must always be the case that
69319*
69320**           aiRowEst[N]<=aiRowEst[N-1]
69321**           aiRowEst[N]>=1
69322**
69323** Apart from that, we have little to go on besides intuition as to
69324** how aiRowEst[] should be initialized.  The numbers generated here
69325** are based on typical values found in actual indices.
69326*/
69327SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
69328  unsigned *a = pIdx->aiRowEst;
69329  int i;
69330  assert( a!=0 );
69331  a[0] = 1000000;
69332  for(i=pIdx->nColumn; i>=5; i--){
69333    a[i] = 5;
69334  }
69335  while( i>=1 ){
69336    a[i] = 11 - i;
69337    i--;
69338  }
69339  if( pIdx->onError!=OE_None ){
69340    a[pIdx->nColumn] = 1;
69341  }
69342}
69343
69344/*
69345** This routine will drop an existing named index.  This routine
69346** implements the DROP INDEX statement.
69347*/
69348SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
69349  Index *pIndex;
69350  Vdbe *v;
69351  sqlite3 *db = pParse->db;
69352  int iDb;
69353
69354  assert( pParse->nErr==0 );   /* Never called with prior errors */
69355  if( db->mallocFailed ){
69356    goto exit_drop_index;
69357  }
69358  assert( pName->nSrc==1 );
69359  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
69360    goto exit_drop_index;
69361  }
69362  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
69363  if( pIndex==0 ){
69364    if( !ifExists ){
69365      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
69366    }
69367    pParse->checkSchema = 1;
69368    goto exit_drop_index;
69369  }
69370  if( pIndex->autoIndex ){
69371    sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
69372      "or PRIMARY KEY constraint cannot be dropped", 0);
69373    goto exit_drop_index;
69374  }
69375  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
69376#ifndef SQLITE_OMIT_AUTHORIZATION
69377  {
69378    int code = SQLITE_DROP_INDEX;
69379    Table *pTab = pIndex->pTable;
69380    const char *zDb = db->aDb[iDb].zName;
69381    const char *zTab = SCHEMA_TABLE(iDb);
69382    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
69383      goto exit_drop_index;
69384    }
69385    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
69386    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
69387      goto exit_drop_index;
69388    }
69389  }
69390#endif
69391
69392  /* Generate code to remove the index and from the master table */
69393  v = sqlite3GetVdbe(pParse);
69394  if( v ){
69395    sqlite3BeginWriteOperation(pParse, 1, iDb);
69396    sqlite3NestedParse(pParse,
69397       "DELETE FROM %Q.%s WHERE name=%Q",
69398       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
69399       pIndex->zName
69400    );
69401    if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
69402      sqlite3NestedParse(pParse,
69403        "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
69404        db->aDb[iDb].zName, pIndex->zName
69405      );
69406    }
69407    sqlite3ChangeCookie(pParse, iDb);
69408    destroyRootPage(pParse, pIndex->tnum, iDb);
69409    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
69410  }
69411
69412exit_drop_index:
69413  sqlite3SrcListDelete(db, pName);
69414}
69415
69416/*
69417** pArray is a pointer to an array of objects.  Each object in the
69418** array is szEntry bytes in size.  This routine allocates a new
69419** object on the end of the array.
69420**
69421** *pnEntry is the number of entries already in use.  *pnAlloc is
69422** the previously allocated size of the array.  initSize is the
69423** suggested initial array size allocation.
69424**
69425** The index of the new entry is returned in *pIdx.
69426**
69427** This routine returns a pointer to the array of objects.  This
69428** might be the same as the pArray parameter or it might be a different
69429** pointer if the array was resized.
69430*/
69431SQLITE_PRIVATE void *sqlite3ArrayAllocate(
69432  sqlite3 *db,      /* Connection to notify of malloc failures */
69433  void *pArray,     /* Array of objects.  Might be reallocated */
69434  int szEntry,      /* Size of each object in the array */
69435  int initSize,     /* Suggested initial allocation, in elements */
69436  int *pnEntry,     /* Number of objects currently in use */
69437  int *pnAlloc,     /* Current size of the allocation, in elements */
69438  int *pIdx         /* Write the index of a new slot here */
69439){
69440  char *z;
69441  if( *pnEntry >= *pnAlloc ){
69442    void *pNew;
69443    int newSize;
69444    newSize = (*pnAlloc)*2 + initSize;
69445    pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
69446    if( pNew==0 ){
69447      *pIdx = -1;
69448      return pArray;
69449    }
69450    *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
69451    pArray = pNew;
69452  }
69453  z = (char*)pArray;
69454  memset(&z[*pnEntry * szEntry], 0, szEntry);
69455  *pIdx = *pnEntry;
69456  ++*pnEntry;
69457  return pArray;
69458}
69459
69460/*
69461** Append a new element to the given IdList.  Create a new IdList if
69462** need be.
69463**
69464** A new IdList is returned, or NULL if malloc() fails.
69465*/
69466SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
69467  int i;
69468  if( pList==0 ){
69469    pList = sqlite3DbMallocZero(db, sizeof(IdList) );
69470    if( pList==0 ) return 0;
69471    pList->nAlloc = 0;
69472  }
69473  pList->a = sqlite3ArrayAllocate(
69474      db,
69475      pList->a,
69476      sizeof(pList->a[0]),
69477      5,
69478      &pList->nId,
69479      &pList->nAlloc,
69480      &i
69481  );
69482  if( i<0 ){
69483    sqlite3IdListDelete(db, pList);
69484    return 0;
69485  }
69486  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
69487  return pList;
69488}
69489
69490/*
69491** Delete an IdList.
69492*/
69493SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
69494  int i;
69495  if( pList==0 ) return;
69496  for(i=0; i<pList->nId; i++){
69497    sqlite3DbFree(db, pList->a[i].zName);
69498  }
69499  sqlite3DbFree(db, pList->a);
69500  sqlite3DbFree(db, pList);
69501}
69502
69503/*
69504** Return the index in pList of the identifier named zId.  Return -1
69505** if not found.
69506*/
69507SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
69508  int i;
69509  if( pList==0 ) return -1;
69510  for(i=0; i<pList->nId; i++){
69511    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
69512  }
69513  return -1;
69514}
69515
69516/*
69517** Expand the space allocated for the given SrcList object by
69518** creating nExtra new slots beginning at iStart.  iStart is zero based.
69519** New slots are zeroed.
69520**
69521** For example, suppose a SrcList initially contains two entries: A,B.
69522** To append 3 new entries onto the end, do this:
69523**
69524**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
69525**
69526** After the call above it would contain:  A, B, nil, nil, nil.
69527** If the iStart argument had been 1 instead of 2, then the result
69528** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
69529** the iStart value would be 0.  The result then would
69530** be: nil, nil, nil, A, B.
69531**
69532** If a memory allocation fails the SrcList is unchanged.  The
69533** db->mallocFailed flag will be set to true.
69534*/
69535SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
69536  sqlite3 *db,       /* Database connection to notify of OOM errors */
69537  SrcList *pSrc,     /* The SrcList to be enlarged */
69538  int nExtra,        /* Number of new slots to add to pSrc->a[] */
69539  int iStart         /* Index in pSrc->a[] of first new slot */
69540){
69541  int i;
69542
69543  /* Sanity checking on calling parameters */
69544  assert( iStart>=0 );
69545  assert( nExtra>=1 );
69546  assert( pSrc!=0 );
69547  assert( iStart<=pSrc->nSrc );
69548
69549  /* Allocate additional space if needed */
69550  if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
69551    SrcList *pNew;
69552    int nAlloc = pSrc->nSrc+nExtra;
69553    int nGot;
69554    pNew = sqlite3DbRealloc(db, pSrc,
69555               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
69556    if( pNew==0 ){
69557      assert( db->mallocFailed );
69558      return pSrc;
69559    }
69560    pSrc = pNew;
69561    nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
69562    pSrc->nAlloc = (u16)nGot;
69563  }
69564
69565  /* Move existing slots that come after the newly inserted slots
69566  ** out of the way */
69567  for(i=pSrc->nSrc-1; i>=iStart; i--){
69568    pSrc->a[i+nExtra] = pSrc->a[i];
69569  }
69570  pSrc->nSrc += (i16)nExtra;
69571
69572  /* Zero the newly allocated slots */
69573  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
69574  for(i=iStart; i<iStart+nExtra; i++){
69575    pSrc->a[i].iCursor = -1;
69576  }
69577
69578  /* Return a pointer to the enlarged SrcList */
69579  return pSrc;
69580}
69581
69582
69583/*
69584** Append a new table name to the given SrcList.  Create a new SrcList if
69585** need be.  A new entry is created in the SrcList even if pTable is NULL.
69586**
69587** A SrcList is returned, or NULL if there is an OOM error.  The returned
69588** SrcList might be the same as the SrcList that was input or it might be
69589** a new one.  If an OOM error does occurs, then the prior value of pList
69590** that is input to this routine is automatically freed.
69591**
69592** If pDatabase is not null, it means that the table has an optional
69593** database name prefix.  Like this:  "database.table".  The pDatabase
69594** points to the table name and the pTable points to the database name.
69595** The SrcList.a[].zName field is filled with the table name which might
69596** come from pTable (if pDatabase is NULL) or from pDatabase.
69597** SrcList.a[].zDatabase is filled with the database name from pTable,
69598** or with NULL if no database is specified.
69599**
69600** In other words, if call like this:
69601**
69602**         sqlite3SrcListAppend(D,A,B,0);
69603**
69604** Then B is a table name and the database name is unspecified.  If called
69605** like this:
69606**
69607**         sqlite3SrcListAppend(D,A,B,C);
69608**
69609** Then C is the table name and B is the database name.  If C is defined
69610** then so is B.  In other words, we never have a case where:
69611**
69612**         sqlite3SrcListAppend(D,A,0,C);
69613**
69614** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
69615** before being added to the SrcList.
69616*/
69617SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
69618  sqlite3 *db,        /* Connection to notify of malloc failures */
69619  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
69620  Token *pTable,      /* Table to append */
69621  Token *pDatabase    /* Database of the table */
69622){
69623  struct SrcList_item *pItem;
69624  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
69625  if( pList==0 ){
69626    pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
69627    if( pList==0 ) return 0;
69628    pList->nAlloc = 1;
69629  }
69630  pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
69631  if( db->mallocFailed ){
69632    sqlite3SrcListDelete(db, pList);
69633    return 0;
69634  }
69635  pItem = &pList->a[pList->nSrc-1];
69636  if( pDatabase && pDatabase->z==0 ){
69637    pDatabase = 0;
69638  }
69639  if( pDatabase ){
69640    Token *pTemp = pDatabase;
69641    pDatabase = pTable;
69642    pTable = pTemp;
69643  }
69644  pItem->zName = sqlite3NameFromToken(db, pTable);
69645  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
69646  return pList;
69647}
69648
69649/*
69650** Assign VdbeCursor index numbers to all tables in a SrcList
69651*/
69652SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
69653  int i;
69654  struct SrcList_item *pItem;
69655  assert(pList || pParse->db->mallocFailed );
69656  if( pList ){
69657    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
69658      if( pItem->iCursor>=0 ) break;
69659      pItem->iCursor = pParse->nTab++;
69660      if( pItem->pSelect ){
69661        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
69662      }
69663    }
69664  }
69665}
69666
69667/*
69668** Delete an entire SrcList including all its substructure.
69669*/
69670SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
69671  int i;
69672  struct SrcList_item *pItem;
69673  if( pList==0 ) return;
69674  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
69675    sqlite3DbFree(db, pItem->zDatabase);
69676    sqlite3DbFree(db, pItem->zName);
69677    sqlite3DbFree(db, pItem->zAlias);
69678    sqlite3DbFree(db, pItem->zIndex);
69679    sqlite3DeleteTable(pItem->pTab);
69680    sqlite3SelectDelete(db, pItem->pSelect);
69681    sqlite3ExprDelete(db, pItem->pOn);
69682    sqlite3IdListDelete(db, pItem->pUsing);
69683  }
69684  sqlite3DbFree(db, pList);
69685}
69686
69687/*
69688** This routine is called by the parser to add a new term to the
69689** end of a growing FROM clause.  The "p" parameter is the part of
69690** the FROM clause that has already been constructed.  "p" is NULL
69691** if this is the first term of the FROM clause.  pTable and pDatabase
69692** are the name of the table and database named in the FROM clause term.
69693** pDatabase is NULL if the database name qualifier is missing - the
69694** usual case.  If the term has a alias, then pAlias points to the
69695** alias token.  If the term is a subquery, then pSubquery is the
69696** SELECT statement that the subquery encodes.  The pTable and
69697** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
69698** parameters are the content of the ON and USING clauses.
69699**
69700** Return a new SrcList which encodes is the FROM with the new
69701** term added.
69702*/
69703SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
69704  Parse *pParse,          /* Parsing context */
69705  SrcList *p,             /* The left part of the FROM clause already seen */
69706  Token *pTable,          /* Name of the table to add to the FROM clause */
69707  Token *pDatabase,       /* Name of the database containing pTable */
69708  Token *pAlias,          /* The right-hand side of the AS subexpression */
69709  Select *pSubquery,      /* A subquery used in place of a table name */
69710  Expr *pOn,              /* The ON clause of a join */
69711  IdList *pUsing          /* The USING clause of a join */
69712){
69713  struct SrcList_item *pItem;
69714  sqlite3 *db = pParse->db;
69715  if( !p && (pOn || pUsing) ){
69716    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
69717      (pOn ? "ON" : "USING")
69718    );
69719    goto append_from_error;
69720  }
69721  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
69722  if( p==0 || NEVER(p->nSrc==0) ){
69723    goto append_from_error;
69724  }
69725  pItem = &p->a[p->nSrc-1];
69726  assert( pAlias!=0 );
69727  if( pAlias->n ){
69728    pItem->zAlias = sqlite3NameFromToken(db, pAlias);
69729  }
69730  pItem->pSelect = pSubquery;
69731  pItem->pOn = pOn;
69732  pItem->pUsing = pUsing;
69733  return p;
69734
69735 append_from_error:
69736  assert( p==0 );
69737  sqlite3ExprDelete(db, pOn);
69738  sqlite3IdListDelete(db, pUsing);
69739  sqlite3SelectDelete(db, pSubquery);
69740  return 0;
69741}
69742
69743/*
69744** Add an INDEXED BY or NOT INDEXED clause to the most recently added
69745** element of the source-list passed as the second argument.
69746*/
69747SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
69748  assert( pIndexedBy!=0 );
69749  if( p && ALWAYS(p->nSrc>0) ){
69750    struct SrcList_item *pItem = &p->a[p->nSrc-1];
69751    assert( pItem->notIndexed==0 && pItem->zIndex==0 );
69752    if( pIndexedBy->n==1 && !pIndexedBy->z ){
69753      /* A "NOT INDEXED" clause was supplied. See parse.y
69754      ** construct "indexed_opt" for details. */
69755      pItem->notIndexed = 1;
69756    }else{
69757      pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
69758    }
69759  }
69760}
69761
69762/*
69763** When building up a FROM clause in the parser, the join operator
69764** is initially attached to the left operand.  But the code generator
69765** expects the join operator to be on the right operand.  This routine
69766** Shifts all join operators from left to right for an entire FROM
69767** clause.
69768**
69769** Example: Suppose the join is like this:
69770**
69771**           A natural cross join B
69772**
69773** The operator is "natural cross join".  The A and B operands are stored
69774** in p->a[0] and p->a[1], respectively.  The parser initially stores the
69775** operator with A.  This routine shifts that operator over to B.
69776*/
69777SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
69778  if( p && p->a ){
69779    int i;
69780    for(i=p->nSrc-1; i>0; i--){
69781      p->a[i].jointype = p->a[i-1].jointype;
69782    }
69783    p->a[0].jointype = 0;
69784  }
69785}
69786
69787/*
69788** Begin a transaction
69789*/
69790SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
69791  sqlite3 *db;
69792  Vdbe *v;
69793  int i;
69794
69795  assert( pParse!=0 );
69796  db = pParse->db;
69797  assert( db!=0 );
69798/*  if( db->aDb[0].pBt==0 ) return; */
69799  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
69800    return;
69801  }
69802  v = sqlite3GetVdbe(pParse);
69803  if( !v ) return;
69804  if( type!=TK_DEFERRED ){
69805    for(i=0; i<db->nDb; i++){
69806      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
69807      sqlite3VdbeUsesBtree(v, i);
69808    }
69809  }
69810  sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
69811}
69812
69813/*
69814** Commit a transaction
69815*/
69816SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
69817  sqlite3 *db;
69818  Vdbe *v;
69819
69820  assert( pParse!=0 );
69821  db = pParse->db;
69822  assert( db!=0 );
69823/*  if( db->aDb[0].pBt==0 ) return; */
69824  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
69825    return;
69826  }
69827  v = sqlite3GetVdbe(pParse);
69828  if( v ){
69829    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
69830  }
69831}
69832
69833/*
69834** Rollback a transaction
69835*/
69836SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
69837  sqlite3 *db;
69838  Vdbe *v;
69839
69840  assert( pParse!=0 );
69841  db = pParse->db;
69842  assert( db!=0 );
69843/*  if( db->aDb[0].pBt==0 ) return; */
69844  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
69845    return;
69846  }
69847  v = sqlite3GetVdbe(pParse);
69848  if( v ){
69849    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
69850  }
69851}
69852
69853/*
69854** This function is called by the parser when it parses a command to create,
69855** release or rollback an SQL savepoint.
69856*/
69857SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
69858  char *zName = sqlite3NameFromToken(pParse->db, pName);
69859  if( zName ){
69860    Vdbe *v = sqlite3GetVdbe(pParse);
69861#ifndef SQLITE_OMIT_AUTHORIZATION
69862    static const char *az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
69863    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
69864#endif
69865    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
69866      sqlite3DbFree(pParse->db, zName);
69867      return;
69868    }
69869    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
69870  }
69871}
69872
69873/*
69874** Make sure the TEMP database is open and available for use.  Return
69875** the number of errors.  Leave any error messages in the pParse structure.
69876*/
69877SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
69878  sqlite3 *db = pParse->db;
69879  if( db->aDb[1].pBt==0 && !pParse->explain ){
69880    int rc;
69881    static const int flags =
69882          SQLITE_OPEN_READWRITE |
69883          SQLITE_OPEN_CREATE |
69884          SQLITE_OPEN_EXCLUSIVE |
69885          SQLITE_OPEN_DELETEONCLOSE |
69886          SQLITE_OPEN_TEMP_DB;
69887
69888    rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
69889                                 &db->aDb[1].pBt);
69890    if( rc!=SQLITE_OK ){
69891      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
69892        "file for storing temporary tables");
69893      pParse->rc = rc;
69894      return 1;
69895    }
69896    assert( db->aDb[1].pSchema );
69897    sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
69898                            db->dfltJournalMode);
69899  }
69900  return 0;
69901}
69902
69903/*
69904** Generate VDBE code that will verify the schema cookie and start
69905** a read-transaction for all named database files.
69906**
69907** It is important that all schema cookies be verified and all
69908** read transactions be started before anything else happens in
69909** the VDBE program.  But this routine can be called after much other
69910** code has been generated.  So here is what we do:
69911**
69912** The first time this routine is called, we code an OP_Goto that
69913** will jump to a subroutine at the end of the program.  Then we
69914** record every database that needs its schema verified in the
69915** pParse->cookieMask field.  Later, after all other code has been
69916** generated, the subroutine that does the cookie verifications and
69917** starts the transactions will be coded and the OP_Goto P2 value
69918** will be made to point to that subroutine.  The generation of the
69919** cookie verification subroutine code happens in sqlite3FinishCoding().
69920**
69921** If iDb<0 then code the OP_Goto only - don't set flag to verify the
69922** schema on any databases.  This can be used to position the OP_Goto
69923** early in the code, before we know if any database tables will be used.
69924*/
69925SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
69926  Parse *pToplevel = sqlite3ParseToplevel(pParse);
69927
69928  if( pToplevel->cookieGoto==0 ){
69929    Vdbe *v = sqlite3GetVdbe(pToplevel);
69930    if( v==0 ) return;  /* This only happens if there was a prior error */
69931    pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
69932  }
69933  if( iDb>=0 ){
69934    sqlite3 *db = pToplevel->db;
69935    int mask;
69936
69937    assert( iDb<db->nDb );
69938    assert( db->aDb[iDb].pBt!=0 || iDb==1 );
69939    assert( iDb<SQLITE_MAX_ATTACHED+2 );
69940    mask = 1<<iDb;
69941    if( (pToplevel->cookieMask & mask)==0 ){
69942      pToplevel->cookieMask |= mask;
69943      pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
69944      if( !OMIT_TEMPDB && iDb==1 ){
69945        sqlite3OpenTempDatabase(pToplevel);
69946      }
69947    }
69948  }
69949}
69950
69951/*
69952** Generate VDBE code that prepares for doing an operation that
69953** might change the database.
69954**
69955** This routine starts a new transaction if we are not already within
69956** a transaction.  If we are already within a transaction, then a checkpoint
69957** is set if the setStatement parameter is true.  A checkpoint should
69958** be set for operations that might fail (due to a constraint) part of
69959** the way through and which will need to undo some writes without having to
69960** rollback the whole transaction.  For operations where all constraints
69961** can be checked before any changes are made to the database, it is never
69962** necessary to undo a write and the checkpoint should not be set.
69963*/
69964SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
69965  Parse *pToplevel = sqlite3ParseToplevel(pParse);
69966  sqlite3CodeVerifySchema(pParse, iDb);
69967  pToplevel->writeMask |= 1<<iDb;
69968  pToplevel->isMultiWrite |= setStatement;
69969}
69970
69971/*
69972** Indicate that the statement currently under construction might write
69973** more than one entry (example: deleting one row then inserting another,
69974** inserting multiple rows in a table, or inserting a row and index entries.)
69975** If an abort occurs after some of these writes have completed, then it will
69976** be necessary to undo the completed writes.
69977*/
69978SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
69979  Parse *pToplevel = sqlite3ParseToplevel(pParse);
69980  pToplevel->isMultiWrite = 1;
69981}
69982
69983/*
69984** The code generator calls this routine if is discovers that it is
69985** possible to abort a statement prior to completion.  In order to
69986** perform this abort without corrupting the database, we need to make
69987** sure that the statement is protected by a statement transaction.
69988**
69989** Technically, we only need to set the mayAbort flag if the
69990** isMultiWrite flag was previously set.  There is a time dependency
69991** such that the abort must occur after the multiwrite.  This makes
69992** some statements involving the REPLACE conflict resolution algorithm
69993** go a little faster.  But taking advantage of this time dependency
69994** makes it more difficult to prove that the code is correct (in
69995** particular, it prevents us from writing an effective
69996** implementation of sqlite3AssertMayAbort()) and so we have chosen
69997** to take the safe route and skip the optimization.
69998*/
69999SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
70000  Parse *pToplevel = sqlite3ParseToplevel(pParse);
70001  pToplevel->mayAbort = 1;
70002}
70003
70004/*
70005** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
70006** error. The onError parameter determines which (if any) of the statement
70007** and/or current transaction is rolled back.
70008*/
70009SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
70010  Vdbe *v = sqlite3GetVdbe(pParse);
70011  if( onError==OE_Abort ){
70012    sqlite3MayAbort(pParse);
70013  }
70014  sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
70015}
70016
70017/*
70018** Check to see if pIndex uses the collating sequence pColl.  Return
70019** true if it does and false if it does not.
70020*/
70021#ifndef SQLITE_OMIT_REINDEX
70022static int collationMatch(const char *zColl, Index *pIndex){
70023  int i;
70024  assert( zColl!=0 );
70025  for(i=0; i<pIndex->nColumn; i++){
70026    const char *z = pIndex->azColl[i];
70027    assert( z!=0 );
70028    if( 0==sqlite3StrICmp(z, zColl) ){
70029      return 1;
70030    }
70031  }
70032  return 0;
70033}
70034#endif
70035
70036/*
70037** Recompute all indices of pTab that use the collating sequence pColl.
70038** If pColl==0 then recompute all indices of pTab.
70039*/
70040#ifndef SQLITE_OMIT_REINDEX
70041static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
70042  Index *pIndex;              /* An index associated with pTab */
70043
70044  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
70045    if( zColl==0 || collationMatch(zColl, pIndex) ){
70046      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
70047      sqlite3BeginWriteOperation(pParse, 0, iDb);
70048      sqlite3RefillIndex(pParse, pIndex, -1);
70049    }
70050  }
70051}
70052#endif
70053
70054/*
70055** Recompute all indices of all tables in all databases where the
70056** indices use the collating sequence pColl.  If pColl==0 then recompute
70057** all indices everywhere.
70058*/
70059#ifndef SQLITE_OMIT_REINDEX
70060static void reindexDatabases(Parse *pParse, char const *zColl){
70061  Db *pDb;                    /* A single database */
70062  int iDb;                    /* The database index number */
70063  sqlite3 *db = pParse->db;   /* The database connection */
70064  HashElem *k;                /* For looping over tables in pDb */
70065  Table *pTab;                /* A table in the database */
70066
70067  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
70068    assert( pDb!=0 );
70069    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
70070      pTab = (Table*)sqliteHashData(k);
70071      reindexTable(pParse, pTab, zColl);
70072    }
70073  }
70074}
70075#endif
70076
70077/*
70078** Generate code for the REINDEX command.
70079**
70080**        REINDEX                            -- 1
70081**        REINDEX  <collation>               -- 2
70082**        REINDEX  ?<database>.?<tablename>  -- 3
70083**        REINDEX  ?<database>.?<indexname>  -- 4
70084**
70085** Form 1 causes all indices in all attached databases to be rebuilt.
70086** Form 2 rebuilds all indices in all databases that use the named
70087** collating function.  Forms 3 and 4 rebuild the named index or all
70088** indices associated with the named table.
70089*/
70090#ifndef SQLITE_OMIT_REINDEX
70091SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
70092  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
70093  char *z;                    /* Name of a table or index */
70094  const char *zDb;            /* Name of the database */
70095  Table *pTab;                /* A table in the database */
70096  Index *pIndex;              /* An index associated with pTab */
70097  int iDb;                    /* The database index number */
70098  sqlite3 *db = pParse->db;   /* The database connection */
70099  Token *pObjName;            /* Name of the table or index to be reindexed */
70100
70101  /* Read the database schema. If an error occurs, leave an error message
70102  ** and code in pParse and return NULL. */
70103  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
70104    return;
70105  }
70106
70107  if( pName1==0 ){
70108    reindexDatabases(pParse, 0);
70109    return;
70110  }else if( NEVER(pName2==0) || pName2->z==0 ){
70111    char *zColl;
70112    assert( pName1->z );
70113    zColl = sqlite3NameFromToken(pParse->db, pName1);
70114    if( !zColl ) return;
70115    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
70116    if( pColl ){
70117      reindexDatabases(pParse, zColl);
70118      sqlite3DbFree(db, zColl);
70119      return;
70120    }
70121    sqlite3DbFree(db, zColl);
70122  }
70123  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
70124  if( iDb<0 ) return;
70125  z = sqlite3NameFromToken(db, pObjName);
70126  if( z==0 ) return;
70127  zDb = db->aDb[iDb].zName;
70128  pTab = sqlite3FindTable(db, z, zDb);
70129  if( pTab ){
70130    reindexTable(pParse, pTab, 0);
70131    sqlite3DbFree(db, z);
70132    return;
70133  }
70134  pIndex = sqlite3FindIndex(db, z, zDb);
70135  sqlite3DbFree(db, z);
70136  if( pIndex ){
70137    sqlite3BeginWriteOperation(pParse, 0, iDb);
70138    sqlite3RefillIndex(pParse, pIndex, -1);
70139    return;
70140  }
70141  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
70142}
70143#endif
70144
70145/*
70146** Return a dynamicly allocated KeyInfo structure that can be used
70147** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
70148**
70149** If successful, a pointer to the new structure is returned. In this case
70150** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
70151** pointer. If an error occurs (out of memory or missing collation
70152** sequence), NULL is returned and the state of pParse updated to reflect
70153** the error.
70154*/
70155SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
70156  int i;
70157  int nCol = pIdx->nColumn;
70158  int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
70159  sqlite3 *db = pParse->db;
70160  KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
70161
70162  if( pKey ){
70163    pKey->db = pParse->db;
70164    pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
70165    assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
70166    for(i=0; i<nCol; i++){
70167      char *zColl = pIdx->azColl[i];
70168      assert( zColl );
70169      pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
70170      pKey->aSortOrder[i] = pIdx->aSortOrder[i];
70171    }
70172    pKey->nField = (u16)nCol;
70173  }
70174
70175  if( pParse->nErr ){
70176    sqlite3DbFree(db, pKey);
70177    pKey = 0;
70178  }
70179  return pKey;
70180}
70181
70182/************** End of build.c ***********************************************/
70183/************** Begin file callback.c ****************************************/
70184/*
70185** 2005 May 23
70186**
70187** The author disclaims copyright to this source code.  In place of
70188** a legal notice, here is a blessing:
70189**
70190**    May you do good and not evil.
70191**    May you find forgiveness for yourself and forgive others.
70192**    May you share freely, never taking more than you give.
70193**
70194*************************************************************************
70195**
70196** This file contains functions used to access the internal hash tables
70197** of user defined functions and collation sequences.
70198*/
70199
70200
70201/*
70202** Invoke the 'collation needed' callback to request a collation sequence
70203** in the encoding enc of name zName, length nName.
70204*/
70205static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
70206  assert( !db->xCollNeeded || !db->xCollNeeded16 );
70207  if( db->xCollNeeded ){
70208    char *zExternal = sqlite3DbStrDup(db, zName);
70209    if( !zExternal ) return;
70210    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
70211    sqlite3DbFree(db, zExternal);
70212  }
70213#ifndef SQLITE_OMIT_UTF16
70214  if( db->xCollNeeded16 ){
70215    char const *zExternal;
70216    sqlite3_value *pTmp = sqlite3ValueNew(db);
70217    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
70218    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
70219    if( zExternal ){
70220      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
70221    }
70222    sqlite3ValueFree(pTmp);
70223  }
70224#endif
70225}
70226
70227/*
70228** This routine is called if the collation factory fails to deliver a
70229** collation function in the best encoding but there may be other versions
70230** of this collation function (for other text encodings) available. Use one
70231** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
70232** possible.
70233*/
70234static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
70235  CollSeq *pColl2;
70236  char *z = pColl->zName;
70237  int i;
70238  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
70239  for(i=0; i<3; i++){
70240    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
70241    if( pColl2->xCmp!=0 ){
70242      memcpy(pColl, pColl2, sizeof(CollSeq));
70243      pColl->xDel = 0;         /* Do not copy the destructor */
70244      return SQLITE_OK;
70245    }
70246  }
70247  return SQLITE_ERROR;
70248}
70249
70250/*
70251** This function is responsible for invoking the collation factory callback
70252** or substituting a collation sequence of a different encoding when the
70253** requested collation sequence is not available in the desired encoding.
70254**
70255** If it is not NULL, then pColl must point to the database native encoding
70256** collation sequence with name zName, length nName.
70257**
70258** The return value is either the collation sequence to be used in database
70259** db for collation type name zName, length nName, or NULL, if no collation
70260** sequence can be found.
70261**
70262** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
70263*/
70264SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
70265  sqlite3* db,          /* The database connection */
70266  u8 enc,               /* The desired encoding for the collating sequence */
70267  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
70268  const char *zName     /* Collating sequence name */
70269){
70270  CollSeq *p;
70271
70272  p = pColl;
70273  if( !p ){
70274    p = sqlite3FindCollSeq(db, enc, zName, 0);
70275  }
70276  if( !p || !p->xCmp ){
70277    /* No collation sequence of this type for this encoding is registered.
70278    ** Call the collation factory to see if it can supply us with one.
70279    */
70280    callCollNeeded(db, enc, zName);
70281    p = sqlite3FindCollSeq(db, enc, zName, 0);
70282  }
70283  if( p && !p->xCmp && synthCollSeq(db, p) ){
70284    p = 0;
70285  }
70286  assert( !p || p->xCmp );
70287  return p;
70288}
70289
70290/*
70291** This routine is called on a collation sequence before it is used to
70292** check that it is defined. An undefined collation sequence exists when
70293** a database is loaded that contains references to collation sequences
70294** that have not been defined by sqlite3_create_collation() etc.
70295**
70296** If required, this routine calls the 'collation needed' callback to
70297** request a definition of the collating sequence. If this doesn't work,
70298** an equivalent collating sequence that uses a text encoding different
70299** from the main database is substituted, if one is available.
70300*/
70301SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
70302  if( pColl ){
70303    const char *zName = pColl->zName;
70304    sqlite3 *db = pParse->db;
70305    CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
70306    if( !p ){
70307      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
70308      pParse->nErr++;
70309      return SQLITE_ERROR;
70310    }
70311    assert( p==pColl );
70312  }
70313  return SQLITE_OK;
70314}
70315
70316
70317
70318/*
70319** Locate and return an entry from the db.aCollSeq hash table. If the entry
70320** specified by zName and nName is not found and parameter 'create' is
70321** true, then create a new entry. Otherwise return NULL.
70322**
70323** Each pointer stored in the sqlite3.aCollSeq hash table contains an
70324** array of three CollSeq structures. The first is the collation sequence
70325** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
70326**
70327** Stored immediately after the three collation sequences is a copy of
70328** the collation sequence name. A pointer to this string is stored in
70329** each collation sequence structure.
70330*/
70331static CollSeq *findCollSeqEntry(
70332  sqlite3 *db,          /* Database connection */
70333  const char *zName,    /* Name of the collating sequence */
70334  int create            /* Create a new entry if true */
70335){
70336  CollSeq *pColl;
70337  int nName = sqlite3Strlen30(zName);
70338  pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
70339
70340  if( 0==pColl && create ){
70341    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
70342    if( pColl ){
70343      CollSeq *pDel = 0;
70344      pColl[0].zName = (char*)&pColl[3];
70345      pColl[0].enc = SQLITE_UTF8;
70346      pColl[1].zName = (char*)&pColl[3];
70347      pColl[1].enc = SQLITE_UTF16LE;
70348      pColl[2].zName = (char*)&pColl[3];
70349      pColl[2].enc = SQLITE_UTF16BE;
70350      memcpy(pColl[0].zName, zName, nName);
70351      pColl[0].zName[nName] = 0;
70352      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
70353
70354      /* If a malloc() failure occurred in sqlite3HashInsert(), it will
70355      ** return the pColl pointer to be deleted (because it wasn't added
70356      ** to the hash table).
70357      */
70358      assert( pDel==0 || pDel==pColl );
70359      if( pDel!=0 ){
70360        db->mallocFailed = 1;
70361        sqlite3DbFree(db, pDel);
70362        pColl = 0;
70363      }
70364    }
70365  }
70366  return pColl;
70367}
70368
70369/*
70370** Parameter zName points to a UTF-8 encoded string nName bytes long.
70371** Return the CollSeq* pointer for the collation sequence named zName
70372** for the encoding 'enc' from the database 'db'.
70373**
70374** If the entry specified is not found and 'create' is true, then create a
70375** new entry.  Otherwise return NULL.
70376**
70377** A separate function sqlite3LocateCollSeq() is a wrapper around
70378** this routine.  sqlite3LocateCollSeq() invokes the collation factory
70379** if necessary and generates an error message if the collating sequence
70380** cannot be found.
70381**
70382** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
70383*/
70384SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
70385  sqlite3 *db,
70386  u8 enc,
70387  const char *zName,
70388  int create
70389){
70390  CollSeq *pColl;
70391  if( zName ){
70392    pColl = findCollSeqEntry(db, zName, create);
70393  }else{
70394    pColl = db->pDfltColl;
70395  }
70396  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
70397  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
70398  if( pColl ) pColl += enc-1;
70399  return pColl;
70400}
70401
70402/* During the search for the best function definition, this procedure
70403** is called to test how well the function passed as the first argument
70404** matches the request for a function with nArg arguments in a system
70405** that uses encoding enc. The value returned indicates how well the
70406** request is matched. A higher value indicates a better match.
70407**
70408** The returned value is always between 0 and 6, as follows:
70409**
70410** 0: Not a match, or if nArg<0 and the function is has no implementation.
70411** 1: A variable arguments function that prefers UTF-8 when a UTF-16
70412**    encoding is requested, or vice versa.
70413** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
70414**    requested, or vice versa.
70415** 3: A variable arguments function using the same text encoding.
70416** 4: A function with the exact number of arguments requested that
70417**    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
70418** 5: A function with the exact number of arguments requested that
70419**    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
70420** 6: An exact match.
70421**
70422*/
70423static int matchQuality(FuncDef *p, int nArg, u8 enc){
70424  int match = 0;
70425  if( p->nArg==-1 || p->nArg==nArg
70426   || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
70427  ){
70428    match = 1;
70429    if( p->nArg==nArg || nArg==-1 ){
70430      match = 4;
70431    }
70432    if( enc==p->iPrefEnc ){
70433      match += 2;
70434    }
70435    else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
70436             (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
70437      match += 1;
70438    }
70439  }
70440  return match;
70441}
70442
70443/*
70444** Search a FuncDefHash for a function with the given name.  Return
70445** a pointer to the matching FuncDef if found, or 0 if there is no match.
70446*/
70447static FuncDef *functionSearch(
70448  FuncDefHash *pHash,  /* Hash table to search */
70449  int h,               /* Hash of the name */
70450  const char *zFunc,   /* Name of function */
70451  int nFunc            /* Number of bytes in zFunc */
70452){
70453  FuncDef *p;
70454  for(p=pHash->a[h]; p; p=p->pHash){
70455    if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
70456      return p;
70457    }
70458  }
70459  return 0;
70460}
70461
70462/*
70463** Insert a new FuncDef into a FuncDefHash hash table.
70464*/
70465SQLITE_PRIVATE void sqlite3FuncDefInsert(
70466  FuncDefHash *pHash,  /* The hash table into which to insert */
70467  FuncDef *pDef        /* The function definition to insert */
70468){
70469  FuncDef *pOther;
70470  int nName = sqlite3Strlen30(pDef->zName);
70471  u8 c1 = (u8)pDef->zName[0];
70472  int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
70473  pOther = functionSearch(pHash, h, pDef->zName, nName);
70474  if( pOther ){
70475    assert( pOther!=pDef && pOther->pNext!=pDef );
70476    pDef->pNext = pOther->pNext;
70477    pOther->pNext = pDef;
70478  }else{
70479    pDef->pNext = 0;
70480    pDef->pHash = pHash->a[h];
70481    pHash->a[h] = pDef;
70482  }
70483}
70484
70485
70486
70487/*
70488** Locate a user function given a name, a number of arguments and a flag
70489** indicating whether the function prefers UTF-16 over UTF-8.  Return a
70490** pointer to the FuncDef structure that defines that function, or return
70491** NULL if the function does not exist.
70492**
70493** If the createFlag argument is true, then a new (blank) FuncDef
70494** structure is created and liked into the "db" structure if a
70495** no matching function previously existed.  When createFlag is true
70496** and the nArg parameter is -1, then only a function that accepts
70497** any number of arguments will be returned.
70498**
70499** If createFlag is false and nArg is -1, then the first valid
70500** function found is returned.  A function is valid if either xFunc
70501** or xStep is non-zero.
70502**
70503** If createFlag is false, then a function with the required name and
70504** number of arguments may be returned even if the eTextRep flag does not
70505** match that requested.
70506*/
70507SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
70508  sqlite3 *db,       /* An open database */
70509  const char *zName, /* Name of the function.  Not null-terminated */
70510  int nName,         /* Number of characters in the name */
70511  int nArg,          /* Number of arguments.  -1 means any number */
70512  u8 enc,            /* Preferred text encoding */
70513  int createFlag     /* Create new entry if true and does not otherwise exist */
70514){
70515  FuncDef *p;         /* Iterator variable */
70516  FuncDef *pBest = 0; /* Best match found so far */
70517  int bestScore = 0;  /* Score of best match */
70518  int h;              /* Hash value */
70519
70520
70521  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
70522  h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
70523
70524  /* First search for a match amongst the application-defined functions.
70525  */
70526  p = functionSearch(&db->aFunc, h, zName, nName);
70527  while( p ){
70528    int score = matchQuality(p, nArg, enc);
70529    if( score>bestScore ){
70530      pBest = p;
70531      bestScore = score;
70532    }
70533    p = p->pNext;
70534  }
70535
70536  /* If no match is found, search the built-in functions.
70537  **
70538  ** Except, if createFlag is true, that means that we are trying to
70539  ** install a new function.  Whatever FuncDef structure is returned will
70540  ** have fields overwritten with new information appropriate for the
70541  ** new function.  But the FuncDefs for built-in functions are read-only.
70542  ** So we must not search for built-ins when creating a new function.
70543  */
70544  if( !createFlag && !pBest ){
70545    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
70546    p = functionSearch(pHash, h, zName, nName);
70547    while( p ){
70548      int score = matchQuality(p, nArg, enc);
70549      if( score>bestScore ){
70550        pBest = p;
70551        bestScore = score;
70552      }
70553      p = p->pNext;
70554    }
70555  }
70556
70557  /* If the createFlag parameter is true and the search did not reveal an
70558  ** exact match for the name, number of arguments and encoding, then add a
70559  ** new entry to the hash table and return it.
70560  */
70561  if( createFlag && (bestScore<6 || pBest->nArg!=nArg) &&
70562      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
70563    pBest->zName = (char *)&pBest[1];
70564    pBest->nArg = (u16)nArg;
70565    pBest->iPrefEnc = enc;
70566    memcpy(pBest->zName, zName, nName);
70567    pBest->zName[nName] = 0;
70568    sqlite3FuncDefInsert(&db->aFunc, pBest);
70569  }
70570
70571  if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
70572    return pBest;
70573  }
70574  return 0;
70575}
70576
70577/*
70578** Free all resources held by the schema structure. The void* argument points
70579** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
70580** pointer itself, it just cleans up subsiduary resources (i.e. the contents
70581** of the schema hash tables).
70582**
70583** The Schema.cache_size variable is not cleared.
70584*/
70585SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
70586  Hash temp1;
70587  Hash temp2;
70588  HashElem *pElem;
70589  Schema *pSchema = (Schema *)p;
70590
70591  temp1 = pSchema->tblHash;
70592  temp2 = pSchema->trigHash;
70593  sqlite3HashInit(&pSchema->trigHash);
70594  sqlite3HashClear(&pSchema->idxHash);
70595  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
70596    sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
70597  }
70598  sqlite3HashClear(&temp2);
70599  sqlite3HashInit(&pSchema->tblHash);
70600  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
70601    Table *pTab = sqliteHashData(pElem);
70602    assert( pTab->dbMem==0 );
70603    sqlite3DeleteTable(pTab);
70604  }
70605  sqlite3HashClear(&temp1);
70606  sqlite3HashClear(&pSchema->fkeyHash);
70607  pSchema->pSeqTab = 0;
70608  pSchema->flags &= ~DB_SchemaLoaded;
70609}
70610
70611/*
70612** Find and return the schema associated with a BTree.  Create
70613** a new one if necessary.
70614*/
70615SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
70616  Schema * p;
70617  if( pBt ){
70618    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
70619  }else{
70620    p = (Schema *)sqlite3MallocZero(sizeof(Schema));
70621  }
70622  if( !p ){
70623    db->mallocFailed = 1;
70624  }else if ( 0==p->file_format ){
70625    sqlite3HashInit(&p->tblHash);
70626    sqlite3HashInit(&p->idxHash);
70627    sqlite3HashInit(&p->trigHash);
70628    sqlite3HashInit(&p->fkeyHash);
70629    p->enc = SQLITE_UTF8;
70630  }
70631  return p;
70632}
70633
70634/************** End of callback.c ********************************************/
70635/************** Begin file delete.c ******************************************/
70636/*
70637** 2001 September 15
70638**
70639** The author disclaims copyright to this source code.  In place of
70640** a legal notice, here is a blessing:
70641**
70642**    May you do good and not evil.
70643**    May you find forgiveness for yourself and forgive others.
70644**    May you share freely, never taking more than you give.
70645**
70646*************************************************************************
70647** This file contains C code routines that are called by the parser
70648** in order to generate code for DELETE FROM statements.
70649*/
70650
70651/*
70652** Look up every table that is named in pSrc.  If any table is not found,
70653** add an error message to pParse->zErrMsg and return NULL.  If all tables
70654** are found, return a pointer to the last table.
70655*/
70656SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
70657  struct SrcList_item *pItem = pSrc->a;
70658  Table *pTab;
70659  assert( pItem && pSrc->nSrc==1 );
70660  pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
70661  sqlite3DeleteTable(pItem->pTab);
70662  pItem->pTab = pTab;
70663  if( pTab ){
70664    pTab->nRef++;
70665  }
70666  if( sqlite3IndexedByLookup(pParse, pItem) ){
70667    pTab = 0;
70668  }
70669  return pTab;
70670}
70671
70672/*
70673** Check to make sure the given table is writable.  If it is not
70674** writable, generate an error message and return 1.  If it is
70675** writable return 0;
70676*/
70677SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
70678  /* A table is not writable under the following circumstances:
70679  **
70680  **   1) It is a virtual table and no implementation of the xUpdate method
70681  **      has been provided, or
70682  **   2) It is a system table (i.e. sqlite_master), this call is not
70683  **      part of a nested parse and writable_schema pragma has not
70684  **      been specified.
70685  **
70686  ** In either case leave an error message in pParse and return non-zero.
70687  */
70688  if( ( IsVirtual(pTab)
70689     && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
70690   || ( (pTab->tabFlags & TF_Readonly)!=0
70691     && (pParse->db->flags & SQLITE_WriteSchema)==0
70692     && pParse->nested==0 )
70693  ){
70694    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
70695    return 1;
70696  }
70697
70698#ifndef SQLITE_OMIT_VIEW
70699  if( !viewOk && pTab->pSelect ){
70700    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
70701    return 1;
70702  }
70703#endif
70704  return 0;
70705}
70706
70707
70708#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
70709/*
70710** Evaluate a view and store its result in an ephemeral table.  The
70711** pWhere argument is an optional WHERE clause that restricts the
70712** set of rows in the view that are to be added to the ephemeral table.
70713*/
70714SQLITE_PRIVATE void sqlite3MaterializeView(
70715  Parse *pParse,       /* Parsing context */
70716  Table *pView,        /* View definition */
70717  Expr *pWhere,        /* Optional WHERE clause to be added */
70718  int iCur             /* Cursor number for ephemerial table */
70719){
70720  SelectDest dest;
70721  Select *pDup;
70722  sqlite3 *db = pParse->db;
70723
70724  pDup = sqlite3SelectDup(db, pView->pSelect, 0);
70725  if( pWhere ){
70726    SrcList *pFrom;
70727
70728    pWhere = sqlite3ExprDup(db, pWhere, 0);
70729    pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
70730    if( pFrom ){
70731      assert( pFrom->nSrc==1 );
70732      pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
70733      pFrom->a[0].pSelect = pDup;
70734      assert( pFrom->a[0].pOn==0 );
70735      assert( pFrom->a[0].pUsing==0 );
70736    }else{
70737      sqlite3SelectDelete(db, pDup);
70738    }
70739    pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
70740  }
70741  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
70742  sqlite3Select(pParse, pDup, &dest);
70743  sqlite3SelectDelete(db, pDup);
70744}
70745#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
70746
70747#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
70748/*
70749** Generate an expression tree to implement the WHERE, ORDER BY,
70750** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
70751**
70752**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
70753**                            \__________________________/
70754**                               pLimitWhere (pInClause)
70755*/
70756SQLITE_PRIVATE Expr *sqlite3LimitWhere(
70757  Parse *pParse,               /* The parser context */
70758  SrcList *pSrc,               /* the FROM clause -- which tables to scan */
70759  Expr *pWhere,                /* The WHERE clause.  May be null */
70760  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
70761  Expr *pLimit,                /* The LIMIT clause.  May be null */
70762  Expr *pOffset,               /* The OFFSET clause.  May be null */
70763  char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
70764){
70765  Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
70766  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
70767  Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
70768  ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
70769  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
70770  Select *pSelect = NULL;      /* Complete SELECT tree */
70771
70772  /* Check that there isn't an ORDER BY without a LIMIT clause.
70773  */
70774  if( pOrderBy && (pLimit == 0) ) {
70775    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
70776    pParse->parseError = 1;
70777    goto limit_where_cleanup_2;
70778  }
70779
70780  /* We only need to generate a select expression if there
70781  ** is a limit/offset term to enforce.
70782  */
70783  if( pLimit == 0 ) {
70784    /* if pLimit is null, pOffset will always be null as well. */
70785    assert( pOffset == 0 );
70786    return pWhere;
70787  }
70788
70789  /* Generate a select expression tree to enforce the limit/offset
70790  ** term for the DELETE or UPDATE statement.  For example:
70791  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
70792  ** becomes:
70793  **   DELETE FROM table_a WHERE rowid IN (
70794  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
70795  **   );
70796  */
70797
70798  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
70799  if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
70800  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
70801  if( pEList == 0 ) goto limit_where_cleanup_2;
70802
70803  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
70804  ** and the SELECT subtree. */
70805  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
70806  if( pSelectSrc == 0 ) {
70807    sqlite3ExprListDelete(pParse->db, pEList);
70808    goto limit_where_cleanup_2;
70809  }
70810
70811  /* generate the SELECT expression tree. */
70812  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
70813                             pOrderBy,0,pLimit,pOffset);
70814  if( pSelect == 0 ) return 0;
70815
70816  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
70817  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
70818  if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
70819  pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
70820  if( pInClause == 0 ) goto limit_where_cleanup_1;
70821
70822  pInClause->x.pSelect = pSelect;
70823  pInClause->flags |= EP_xIsSelect;
70824  sqlite3ExprSetHeight(pParse, pInClause);
70825  return pInClause;
70826
70827  /* something went wrong. clean up anything allocated. */
70828limit_where_cleanup_1:
70829  sqlite3SelectDelete(pParse->db, pSelect);
70830  return 0;
70831
70832limit_where_cleanup_2:
70833  sqlite3ExprDelete(pParse->db, pWhere);
70834  sqlite3ExprListDelete(pParse->db, pOrderBy);
70835  sqlite3ExprDelete(pParse->db, pLimit);
70836  sqlite3ExprDelete(pParse->db, pOffset);
70837  return 0;
70838}
70839#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
70840
70841/*
70842** Generate code for a DELETE FROM statement.
70843**
70844**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
70845**                 \________/       \________________/
70846**                  pTabList              pWhere
70847*/
70848SQLITE_PRIVATE void sqlite3DeleteFrom(
70849  Parse *pParse,         /* The parser context */
70850  SrcList *pTabList,     /* The table from which we should delete things */
70851  Expr *pWhere           /* The WHERE clause.  May be null */
70852){
70853  Vdbe *v;               /* The virtual database engine */
70854  Table *pTab;           /* The table from which records will be deleted */
70855  const char *zDb;       /* Name of database holding pTab */
70856  int end, addr = 0;     /* A couple addresses of generated code */
70857  int i;                 /* Loop counter */
70858  WhereInfo *pWInfo;     /* Information about the WHERE clause */
70859  Index *pIdx;           /* For looping over indices of the table */
70860  int iCur;              /* VDBE Cursor number for pTab */
70861  sqlite3 *db;           /* Main database structure */
70862  AuthContext sContext;  /* Authorization context */
70863  NameContext sNC;       /* Name context to resolve expressions in */
70864  int iDb;               /* Database number */
70865  int memCnt = -1;       /* Memory cell used for change counting */
70866  int rcauth;            /* Value returned by authorization callback */
70867
70868#ifndef SQLITE_OMIT_TRIGGER
70869  int isView;                  /* True if attempting to delete from a view */
70870  Trigger *pTrigger;           /* List of table triggers, if required */
70871#endif
70872
70873  memset(&sContext, 0, sizeof(sContext));
70874  db = pParse->db;
70875  if( pParse->nErr || db->mallocFailed ){
70876    goto delete_from_cleanup;
70877  }
70878  assert( pTabList->nSrc==1 );
70879
70880  /* Locate the table which we want to delete.  This table has to be
70881  ** put in an SrcList structure because some of the subroutines we
70882  ** will be calling are designed to work with multiple tables and expect
70883  ** an SrcList* parameter instead of just a Table* parameter.
70884  */
70885  pTab = sqlite3SrcListLookup(pParse, pTabList);
70886  if( pTab==0 )  goto delete_from_cleanup;
70887
70888  /* Figure out if we have any triggers and if the table being
70889  ** deleted from is a view
70890  */
70891#ifndef SQLITE_OMIT_TRIGGER
70892  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
70893  isView = pTab->pSelect!=0;
70894#else
70895# define pTrigger 0
70896# define isView 0
70897#endif
70898#ifdef SQLITE_OMIT_VIEW
70899# undef isView
70900# define isView 0
70901#endif
70902
70903  /* If pTab is really a view, make sure it has been initialized.
70904  */
70905  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
70906    goto delete_from_cleanup;
70907  }
70908
70909  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
70910    goto delete_from_cleanup;
70911  }
70912  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
70913  assert( iDb<db->nDb );
70914  zDb = db->aDb[iDb].zName;
70915  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
70916  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
70917  if( rcauth==SQLITE_DENY ){
70918    goto delete_from_cleanup;
70919  }
70920  assert(!isView || pTrigger);
70921
70922  /* Assign  cursor number to the table and all its indices.
70923  */
70924  assert( pTabList->nSrc==1 );
70925  iCur = pTabList->a[0].iCursor = pParse->nTab++;
70926  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
70927    pParse->nTab++;
70928  }
70929
70930  /* Start the view context
70931  */
70932  if( isView ){
70933    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
70934  }
70935
70936  /* Begin generating code.
70937  */
70938  v = sqlite3GetVdbe(pParse);
70939  if( v==0 ){
70940    goto delete_from_cleanup;
70941  }
70942  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
70943  sqlite3BeginWriteOperation(pParse, 1, iDb);
70944
70945  /* If we are trying to delete from a view, realize that view into
70946  ** a ephemeral table.
70947  */
70948#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
70949  if( isView ){
70950    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
70951  }
70952#endif
70953
70954  /* Resolve the column names in the WHERE clause.
70955  */
70956  memset(&sNC, 0, sizeof(sNC));
70957  sNC.pParse = pParse;
70958  sNC.pSrcList = pTabList;
70959  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
70960    goto delete_from_cleanup;
70961  }
70962
70963  /* Initialize the counter of the number of rows deleted, if
70964  ** we are counting rows.
70965  */
70966  if( db->flags & SQLITE_CountRows ){
70967    memCnt = ++pParse->nMem;
70968    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
70969  }
70970
70971#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
70972  /* Special case: A DELETE without a WHERE clause deletes everything.
70973  ** It is easier just to erase the whole table. Prior to version 3.6.5,
70974  ** this optimization caused the row change count (the value returned by
70975  ** API function sqlite3_count_changes) to be set incorrectly.  */
70976  if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
70977   && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
70978  ){
70979    assert( !isView );
70980    sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
70981                      pTab->zName, P4_STATIC);
70982    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
70983      assert( pIdx->pSchema==pTab->pSchema );
70984      sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
70985    }
70986  }else
70987#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
70988  /* The usual case: There is a WHERE clause so we have to scan through
70989  ** the table and pick which records to delete.
70990  */
70991  {
70992    int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
70993    int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
70994    int regRowid;                   /* Actual register containing rowids */
70995
70996    /* Collect rowids of every row to be deleted.
70997    */
70998    sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
70999    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
71000    if( pWInfo==0 ) goto delete_from_cleanup;
71001    regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
71002    sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
71003    if( db->flags & SQLITE_CountRows ){
71004      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
71005    }
71006    sqlite3WhereEnd(pWInfo);
71007
71008    /* Delete every item whose key was written to the list during the
71009    ** database scan.  We have to delete items after the scan is complete
71010    ** because deleting an item can change the scan order.  */
71011    end = sqlite3VdbeMakeLabel(v);
71012
71013    /* Unless this is a view, open cursors for the table we are
71014    ** deleting from and all its indices. If this is a view, then the
71015    ** only effect this statement has is to fire the INSTEAD OF
71016    ** triggers.  */
71017    if( !isView ){
71018      sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
71019    }
71020
71021    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
71022
71023    /* Delete the row */
71024#ifndef SQLITE_OMIT_VIRTUALTABLE
71025    if( IsVirtual(pTab) ){
71026      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
71027      sqlite3VtabMakeWritable(pParse, pTab);
71028      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
71029      sqlite3MayAbort(pParse);
71030    }else
71031#endif
71032    {
71033      int count = (pParse->nested==0);    /* True to count changes */
71034      sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
71035    }
71036
71037    /* End of the delete loop */
71038    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
71039    sqlite3VdbeResolveLabel(v, end);
71040
71041    /* Close the cursors open on the table and its indexes. */
71042    if( !isView && !IsVirtual(pTab) ){
71043      for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
71044        sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
71045      }
71046      sqlite3VdbeAddOp1(v, OP_Close, iCur);
71047    }
71048  }
71049
71050  /* Update the sqlite_sequence table by storing the content of the
71051  ** maximum rowid counter values recorded while inserting into
71052  ** autoincrement tables.
71053  */
71054  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
71055    sqlite3AutoincrementEnd(pParse);
71056  }
71057
71058  /* Return the number of rows that were deleted. If this routine is
71059  ** generating code because of a call to sqlite3NestedParse(), do not
71060  ** invoke the callback function.
71061  */
71062  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
71063    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
71064    sqlite3VdbeSetNumCols(v, 1);
71065    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
71066  }
71067
71068delete_from_cleanup:
71069  sqlite3AuthContextPop(&sContext);
71070  sqlite3SrcListDelete(db, pTabList);
71071  sqlite3ExprDelete(db, pWhere);
71072  return;
71073}
71074/* Make sure "isView" and other macros defined above are undefined. Otherwise
71075** thely may interfere with compilation of other functions in this file
71076** (or in another file, if this file becomes part of the amalgamation).  */
71077#ifdef isView
71078 #undef isView
71079#endif
71080#ifdef pTrigger
71081 #undef pTrigger
71082#endif
71083
71084/*
71085** This routine generates VDBE code that causes a single row of a
71086** single table to be deleted.
71087**
71088** The VDBE must be in a particular state when this routine is called.
71089** These are the requirements:
71090**
71091**   1.  A read/write cursor pointing to pTab, the table containing the row
71092**       to be deleted, must be opened as cursor number $iCur.
71093**
71094**   2.  Read/write cursors for all indices of pTab must be open as
71095**       cursor number base+i for the i-th index.
71096**
71097**   3.  The record number of the row to be deleted must be stored in
71098**       memory cell iRowid.
71099**
71100** This routine generates code to remove both the table record and all
71101** index entries that point to that record.
71102*/
71103SQLITE_PRIVATE void sqlite3GenerateRowDelete(
71104  Parse *pParse,     /* Parsing context */
71105  Table *pTab,       /* Table containing the row to be deleted */
71106  int iCur,          /* Cursor number for the table */
71107  int iRowid,        /* Memory cell that contains the rowid to delete */
71108  int count,         /* If non-zero, increment the row change counter */
71109  Trigger *pTrigger, /* List of triggers to (potentially) fire */
71110  int onconf         /* Default ON CONFLICT policy for triggers */
71111){
71112  Vdbe *v = pParse->pVdbe;        /* Vdbe */
71113  int iOld = 0;                   /* First register in OLD.* array */
71114  int iLabel;                     /* Label resolved to end of generated code */
71115
71116  /* Vdbe is guaranteed to have been allocated by this stage. */
71117  assert( v );
71118
71119  /* Seek cursor iCur to the row to delete. If this row no longer exists
71120  ** (this can happen if a trigger program has already deleted it), do
71121  ** not attempt to delete it or fire any DELETE triggers.  */
71122  iLabel = sqlite3VdbeMakeLabel(v);
71123  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
71124
71125  /* If there are any triggers to fire, allocate a range of registers to
71126  ** use for the old.* references in the triggers.  */
71127  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
71128    u32 mask;                     /* Mask of OLD.* columns in use */
71129    int iCol;                     /* Iterator used while populating OLD.* */
71130
71131    /* TODO: Could use temporary registers here. Also could attempt to
71132    ** avoid copying the contents of the rowid register.  */
71133    mask = sqlite3TriggerColmask(
71134        pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
71135    );
71136    mask |= sqlite3FkOldmask(pParse, pTab);
71137    iOld = pParse->nMem+1;
71138    pParse->nMem += (1 + pTab->nCol);
71139
71140    /* Populate the OLD.* pseudo-table register array. These values will be
71141    ** used by any BEFORE and AFTER triggers that exist.  */
71142    sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
71143    for(iCol=0; iCol<pTab->nCol; iCol++){
71144      if( mask==0xffffffff || mask&(1<<iCol) ){
71145        int iTarget = iOld + iCol + 1;
71146        sqlite3VdbeAddOp3(v, OP_Column, iCur, iCol, iTarget);
71147        sqlite3ColumnDefault(v, pTab, iCol, iTarget);
71148      }
71149    }
71150
71151    /* Invoke BEFORE DELETE trigger programs. */
71152    sqlite3CodeRowTrigger(pParse, pTrigger,
71153        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
71154    );
71155
71156    /* Seek the cursor to the row to be deleted again. It may be that
71157    ** the BEFORE triggers coded above have already removed the row
71158    ** being deleted. Do not attempt to delete the row a second time, and
71159    ** do not fire AFTER triggers.  */
71160    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
71161
71162    /* Do FK processing. This call checks that any FK constraints that
71163    ** refer to this table (i.e. constraints attached to other tables)
71164    ** are not violated by deleting this row.  */
71165    sqlite3FkCheck(pParse, pTab, iOld, 0);
71166  }
71167
71168  /* Delete the index and table entries. Skip this step if pTab is really
71169  ** a view (in which case the only effect of the DELETE statement is to
71170  ** fire the INSTEAD OF triggers).  */
71171  if( pTab->pSelect==0 ){
71172    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
71173    sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
71174    if( count ){
71175      sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
71176    }
71177  }
71178
71179  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
71180  ** handle rows (possibly in other tables) that refer via a foreign key
71181  ** to the row just deleted. */
71182  sqlite3FkActions(pParse, pTab, 0, iOld);
71183
71184  /* Invoke AFTER DELETE trigger programs. */
71185  sqlite3CodeRowTrigger(pParse, pTrigger,
71186      TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
71187  );
71188
71189  /* Jump here if the row had already been deleted before any BEFORE
71190  ** trigger programs were invoked. Or if a trigger program throws a
71191  ** RAISE(IGNORE) exception.  */
71192  sqlite3VdbeResolveLabel(v, iLabel);
71193}
71194
71195/*
71196** This routine generates VDBE code that causes the deletion of all
71197** index entries associated with a single row of a single table.
71198**
71199** The VDBE must be in a particular state when this routine is called.
71200** These are the requirements:
71201**
71202**   1.  A read/write cursor pointing to pTab, the table containing the row
71203**       to be deleted, must be opened as cursor number "iCur".
71204**
71205**   2.  Read/write cursors for all indices of pTab must be open as
71206**       cursor number iCur+i for the i-th index.
71207**
71208**   3.  The "iCur" cursor must be pointing to the row that is to be
71209**       deleted.
71210*/
71211SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
71212  Parse *pParse,     /* Parsing and code generating context */
71213  Table *pTab,       /* Table containing the row to be deleted */
71214  int iCur,          /* Cursor number for the table */
71215  int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
71216){
71217  int i;
71218  Index *pIdx;
71219  int r1;
71220
71221  for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
71222    if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
71223    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
71224    sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
71225  }
71226}
71227
71228/*
71229** Generate code that will assemble an index key and put it in register
71230** regOut.  The key with be for index pIdx which is an index on pTab.
71231** iCur is the index of a cursor open on the pTab table and pointing to
71232** the entry that needs indexing.
71233**
71234** Return a register number which is the first in a block of
71235** registers that holds the elements of the index key.  The
71236** block of registers has already been deallocated by the time
71237** this routine returns.
71238*/
71239SQLITE_PRIVATE int sqlite3GenerateIndexKey(
71240  Parse *pParse,     /* Parsing context */
71241  Index *pIdx,       /* The index for which to generate a key */
71242  int iCur,          /* Cursor number for the pIdx->pTable table */
71243  int regOut,        /* Write the new index key to this register */
71244  int doMakeRec      /* Run the OP_MakeRecord instruction if true */
71245){
71246  Vdbe *v = pParse->pVdbe;
71247  int j;
71248  Table *pTab = pIdx->pTable;
71249  int regBase;
71250  int nCol;
71251
71252  nCol = pIdx->nColumn;
71253  regBase = sqlite3GetTempRange(pParse, nCol+1);
71254  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
71255  for(j=0; j<nCol; j++){
71256    int idx = pIdx->aiColumn[j];
71257    if( idx==pTab->iPKey ){
71258      sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
71259    }else{
71260      sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
71261      sqlite3ColumnDefault(v, pTab, idx, -1);
71262    }
71263  }
71264  if( doMakeRec ){
71265    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
71266    sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
71267  }
71268  sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
71269  return regBase;
71270}
71271
71272/************** End of delete.c **********************************************/
71273/************** Begin file func.c ********************************************/
71274/*
71275** 2002 February 23
71276**
71277** The author disclaims copyright to this source code.  In place of
71278** a legal notice, here is a blessing:
71279**
71280**    May you do good and not evil.
71281**    May you find forgiveness for yourself and forgive others.
71282**    May you share freely, never taking more than you give.
71283**
71284*************************************************************************
71285** This file contains the C functions that implement various SQL
71286** functions of SQLite.
71287**
71288** There is only one exported symbol in this file - the function
71289** sqliteRegisterBuildinFunctions() found at the bottom of the file.
71290** All other code has file scope.
71291*/
71292
71293/*
71294** Return the collating function associated with a function.
71295*/
71296static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
71297  return context->pColl;
71298}
71299
71300/*
71301** Implementation of the non-aggregate min() and max() functions
71302*/
71303static void minmaxFunc(
71304  sqlite3_context *context,
71305  int argc,
71306  sqlite3_value **argv
71307){
71308  int i;
71309  int mask;    /* 0 for min() or 0xffffffff for max() */
71310  int iBest;
71311  CollSeq *pColl;
71312
71313  assert( argc>1 );
71314  mask = sqlite3_user_data(context)==0 ? 0 : -1;
71315  pColl = sqlite3GetFuncCollSeq(context);
71316  assert( pColl );
71317  assert( mask==-1 || mask==0 );
71318  iBest = 0;
71319  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
71320  for(i=1; i<argc; i++){
71321    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
71322    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
71323      testcase( mask==0 );
71324      iBest = i;
71325    }
71326  }
71327  sqlite3_result_value(context, argv[iBest]);
71328}
71329
71330/*
71331** Return the type of the argument.
71332*/
71333static void typeofFunc(
71334  sqlite3_context *context,
71335  int NotUsed,
71336  sqlite3_value **argv
71337){
71338  const char *z = 0;
71339  UNUSED_PARAMETER(NotUsed);
71340  switch( sqlite3_value_type(argv[0]) ){
71341    case SQLITE_INTEGER: z = "integer"; break;
71342    case SQLITE_TEXT:    z = "text";    break;
71343    case SQLITE_FLOAT:   z = "real";    break;
71344    case SQLITE_BLOB:    z = "blob";    break;
71345    default:             z = "null";    break;
71346  }
71347  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
71348}
71349
71350
71351/*
71352** Implementation of the length() function
71353*/
71354static void lengthFunc(
71355  sqlite3_context *context,
71356  int argc,
71357  sqlite3_value **argv
71358){
71359  int len;
71360
71361  assert( argc==1 );
71362  UNUSED_PARAMETER(argc);
71363  switch( sqlite3_value_type(argv[0]) ){
71364    case SQLITE_BLOB:
71365    case SQLITE_INTEGER:
71366    case SQLITE_FLOAT: {
71367      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
71368      break;
71369    }
71370    case SQLITE_TEXT: {
71371      const unsigned char *z = sqlite3_value_text(argv[0]);
71372      if( z==0 ) return;
71373      len = 0;
71374      while( *z ){
71375        len++;
71376        SQLITE_SKIP_UTF8(z);
71377      }
71378      sqlite3_result_int(context, len);
71379      break;
71380    }
71381    default: {
71382      sqlite3_result_null(context);
71383      break;
71384    }
71385  }
71386}
71387
71388/*
71389** Implementation of the abs() function.
71390**
71391** IMP: R-23979-26855 The abs(X) function returns the absolute value of
71392** the numeric argument X.
71393*/
71394static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71395  assert( argc==1 );
71396  UNUSED_PARAMETER(argc);
71397  switch( sqlite3_value_type(argv[0]) ){
71398    case SQLITE_INTEGER: {
71399      i64 iVal = sqlite3_value_int64(argv[0]);
71400      if( iVal<0 ){
71401        if( (iVal<<1)==0 ){
71402          /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
71403          ** abs(X) throws an integer overflow error since there is no
71404          ** equivalent positive 64-bit two complement value. */
71405          sqlite3_result_error(context, "integer overflow", -1);
71406          return;
71407        }
71408        iVal = -iVal;
71409      }
71410      sqlite3_result_int64(context, iVal);
71411      break;
71412    }
71413    case SQLITE_NULL: {
71414      /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
71415      sqlite3_result_null(context);
71416      break;
71417    }
71418    default: {
71419      /* Because sqlite3_value_double() returns 0.0 if the argument is not
71420      ** something that can be converted into a number, we have:
71421      ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
71422      ** cannot be converted to a numeric value.
71423      */
71424      double rVal = sqlite3_value_double(argv[0]);
71425      if( rVal<0 ) rVal = -rVal;
71426      sqlite3_result_double(context, rVal);
71427      break;
71428    }
71429  }
71430}
71431
71432/*
71433** Implementation of the substr() function.
71434**
71435** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
71436** p1 is 1-indexed.  So substr(x,1,1) returns the first character
71437** of x.  If x is text, then we actually count UTF-8 characters.
71438** If x is a blob, then we count bytes.
71439**
71440** If p1 is negative, then we begin abs(p1) from the end of x[].
71441**
71442** If p2 is negative, return the p2 characters preceeding p1.
71443*/
71444static void substrFunc(
71445  sqlite3_context *context,
71446  int argc,
71447  sqlite3_value **argv
71448){
71449  const unsigned char *z;
71450  const unsigned char *z2;
71451  int len;
71452  int p0type;
71453  i64 p1, p2;
71454  int negP2 = 0;
71455
71456  assert( argc==3 || argc==2 );
71457  if( sqlite3_value_type(argv[1])==SQLITE_NULL
71458   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
71459  ){
71460    return;
71461  }
71462  p0type = sqlite3_value_type(argv[0]);
71463  p1 = sqlite3_value_int(argv[1]);
71464  if( p0type==SQLITE_BLOB ){
71465    len = sqlite3_value_bytes(argv[0]);
71466    z = sqlite3_value_blob(argv[0]);
71467    if( z==0 ) return;
71468    assert( len==sqlite3_value_bytes(argv[0]) );
71469  }else{
71470    z = sqlite3_value_text(argv[0]);
71471    if( z==0 ) return;
71472    len = 0;
71473    if( p1<0 ){
71474      for(z2=z; *z2; len++){
71475        SQLITE_SKIP_UTF8(z2);
71476      }
71477    }
71478  }
71479  if( argc==3 ){
71480    p2 = sqlite3_value_int(argv[2]);
71481    if( p2<0 ){
71482      p2 = -p2;
71483      negP2 = 1;
71484    }
71485  }else{
71486    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
71487  }
71488  if( p1<0 ){
71489    p1 += len;
71490    if( p1<0 ){
71491      p2 += p1;
71492      if( p2<0 ) p2 = 0;
71493      p1 = 0;
71494    }
71495  }else if( p1>0 ){
71496    p1--;
71497  }else if( p2>0 ){
71498    p2--;
71499  }
71500  if( negP2 ){
71501    p1 -= p2;
71502    if( p1<0 ){
71503      p2 += p1;
71504      p1 = 0;
71505    }
71506  }
71507  assert( p1>=0 && p2>=0 );
71508  if( p0type!=SQLITE_BLOB ){
71509    while( *z && p1 ){
71510      SQLITE_SKIP_UTF8(z);
71511      p1--;
71512    }
71513    for(z2=z; *z2 && p2; p2--){
71514      SQLITE_SKIP_UTF8(z2);
71515    }
71516    sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
71517  }else{
71518    if( p1+p2>len ){
71519      p2 = len-p1;
71520      if( p2<0 ) p2 = 0;
71521    }
71522    sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
71523  }
71524}
71525
71526/*
71527** Implementation of the round() function
71528*/
71529#ifndef SQLITE_OMIT_FLOATING_POINT
71530static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71531  int n = 0;
71532  double r;
71533  char *zBuf;
71534  assert( argc==1 || argc==2 );
71535  if( argc==2 ){
71536    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
71537    n = sqlite3_value_int(argv[1]);
71538    if( n>30 ) n = 30;
71539    if( n<0 ) n = 0;
71540  }
71541  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
71542  r = sqlite3_value_double(argv[0]);
71543  zBuf = sqlite3_mprintf("%.*f",n,r);
71544  if( zBuf==0 ){
71545    sqlite3_result_error_nomem(context);
71546  }else{
71547    sqlite3AtoF(zBuf, &r);
71548    sqlite3_free(zBuf);
71549    sqlite3_result_double(context, r);
71550  }
71551}
71552#endif
71553
71554/*
71555** Allocate nByte bytes of space using sqlite3_malloc(). If the
71556** allocation fails, call sqlite3_result_error_nomem() to notify
71557** the database handle that malloc() has failed and return NULL.
71558** If nByte is larger than the maximum string or blob length, then
71559** raise an SQLITE_TOOBIG exception and return NULL.
71560*/
71561static void *contextMalloc(sqlite3_context *context, i64 nByte){
71562  char *z;
71563  sqlite3 *db = sqlite3_context_db_handle(context);
71564  assert( nByte>0 );
71565  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
71566  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
71567  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
71568    sqlite3_result_error_toobig(context);
71569    z = 0;
71570  }else{
71571    z = sqlite3Malloc((int)nByte);
71572    if( !z ){
71573      sqlite3_result_error_nomem(context);
71574    }
71575  }
71576  return z;
71577}
71578
71579/*
71580** Implementation of the upper() and lower() SQL functions.
71581*/
71582static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71583  char *z1;
71584  const char *z2;
71585  int i, n;
71586  UNUSED_PARAMETER(argc);
71587  z2 = (char*)sqlite3_value_text(argv[0]);
71588  n = sqlite3_value_bytes(argv[0]);
71589  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
71590  assert( z2==(char*)sqlite3_value_text(argv[0]) );
71591  if( z2 ){
71592    z1 = contextMalloc(context, ((i64)n)+1);
71593    if( z1 ){
71594      memcpy(z1, z2, n+1);
71595      for(i=0; z1[i]; i++){
71596        z1[i] = (char)sqlite3Toupper(z1[i]);
71597      }
71598      sqlite3_result_text(context, z1, -1, sqlite3_free);
71599    }
71600  }
71601}
71602static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71603  u8 *z1;
71604  const char *z2;
71605  int i, n;
71606  UNUSED_PARAMETER(argc);
71607  z2 = (char*)sqlite3_value_text(argv[0]);
71608  n = sqlite3_value_bytes(argv[0]);
71609  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
71610  assert( z2==(char*)sqlite3_value_text(argv[0]) );
71611  if( z2 ){
71612    z1 = contextMalloc(context, ((i64)n)+1);
71613    if( z1 ){
71614      memcpy(z1, z2, n+1);
71615      for(i=0; z1[i]; i++){
71616        z1[i] = sqlite3Tolower(z1[i]);
71617      }
71618      sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
71619    }
71620  }
71621}
71622
71623
71624#if 0  /* This function is never used. */
71625/*
71626** The COALESCE() and IFNULL() functions used to be implemented as shown
71627** here.  But now they are implemented as VDBE code so that unused arguments
71628** do not have to be computed.  This legacy implementation is retained as
71629** comment.
71630*/
71631/*
71632** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
71633** All three do the same thing.  They return the first non-NULL
71634** argument.
71635*/
71636static void ifnullFunc(
71637  sqlite3_context *context,
71638  int argc,
71639  sqlite3_value **argv
71640){
71641  int i;
71642  for(i=0; i<argc; i++){
71643    if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
71644      sqlite3_result_value(context, argv[i]);
71645      break;
71646    }
71647  }
71648}
71649#endif /* NOT USED */
71650#define ifnullFunc versionFunc   /* Substitute function - never called */
71651
71652/*
71653** Implementation of random().  Return a random integer.
71654*/
71655static void randomFunc(
71656  sqlite3_context *context,
71657  int NotUsed,
71658  sqlite3_value **NotUsed2
71659){
71660  sqlite_int64 r;
71661  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71662  sqlite3_randomness(sizeof(r), &r);
71663  if( r<0 ){
71664    /* We need to prevent a random number of 0x8000000000000000
71665    ** (or -9223372036854775808) since when you do abs() of that
71666    ** number of you get the same value back again.  To do this
71667    ** in a way that is testable, mask the sign bit off of negative
71668    ** values, resulting in a positive value.  Then take the
71669    ** 2s complement of that positive value.  The end result can
71670    ** therefore be no less than -9223372036854775807.
71671    */
71672    r = -(r ^ (((sqlite3_int64)1)<<63));
71673  }
71674  sqlite3_result_int64(context, r);
71675}
71676
71677/*
71678** Implementation of randomblob(N).  Return a random blob
71679** that is N bytes long.
71680*/
71681static void randomBlob(
71682  sqlite3_context *context,
71683  int argc,
71684  sqlite3_value **argv
71685){
71686  int n;
71687  unsigned char *p;
71688  assert( argc==1 );
71689  UNUSED_PARAMETER(argc);
71690  n = sqlite3_value_int(argv[0]);
71691  if( n<1 ){
71692    n = 1;
71693  }
71694  p = contextMalloc(context, n);
71695  if( p ){
71696    sqlite3_randomness(n, p);
71697    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
71698  }
71699}
71700
71701/*
71702** Implementation of the last_insert_rowid() SQL function.  The return
71703** value is the same as the sqlite3_last_insert_rowid() API function.
71704*/
71705static void last_insert_rowid(
71706  sqlite3_context *context,
71707  int NotUsed,
71708  sqlite3_value **NotUsed2
71709){
71710  sqlite3 *db = sqlite3_context_db_handle(context);
71711  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71712  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
71713}
71714
71715/*
71716** Implementation of the changes() SQL function.  The return value is the
71717** same as the sqlite3_changes() API function.
71718*/
71719static void changes(
71720  sqlite3_context *context,
71721  int NotUsed,
71722  sqlite3_value **NotUsed2
71723){
71724  sqlite3 *db = sqlite3_context_db_handle(context);
71725  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71726  sqlite3_result_int(context, sqlite3_changes(db));
71727}
71728
71729/*
71730** Implementation of the total_changes() SQL function.  The return value is
71731** the same as the sqlite3_total_changes() API function.
71732*/
71733static void total_changes(
71734  sqlite3_context *context,
71735  int NotUsed,
71736  sqlite3_value **NotUsed2
71737){
71738  sqlite3 *db = sqlite3_context_db_handle(context);
71739  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71740  sqlite3_result_int(context, sqlite3_total_changes(db));
71741}
71742
71743/*
71744** A structure defining how to do GLOB-style comparisons.
71745*/
71746struct compareInfo {
71747  u8 matchAll;
71748  u8 matchOne;
71749  u8 matchSet;
71750  u8 noCase;
71751};
71752
71753/*
71754** For LIKE and GLOB matching on EBCDIC machines, assume that every
71755** character is exactly one byte in size.  Also, all characters are
71756** able to participate in upper-case-to-lower-case mappings in EBCDIC
71757** whereas only characters less than 0x80 do in ASCII.
71758*/
71759#if defined(SQLITE_EBCDIC)
71760# define sqlite3Utf8Read(A,C)    (*(A++))
71761# define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
71762#else
71763# define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
71764#endif
71765
71766static const struct compareInfo globInfo = { '*', '?', '[', 0 };
71767/* The correct SQL-92 behavior is for the LIKE operator to ignore
71768** case.  Thus  'a' LIKE 'A' would be true. */
71769static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
71770/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
71771** is case sensitive causing 'a' LIKE 'A' to be false */
71772static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
71773
71774/*
71775** Compare two UTF-8 strings for equality where the first string can
71776** potentially be a "glob" expression.  Return true (1) if they
71777** are the same and false (0) if they are different.
71778**
71779** Globbing rules:
71780**
71781**      '*'       Matches any sequence of zero or more characters.
71782**
71783**      '?'       Matches exactly one character.
71784**
71785**     [...]      Matches one character from the enclosed list of
71786**                characters.
71787**
71788**     [^...]     Matches one character not in the enclosed list.
71789**
71790** With the [...] and [^...] matching, a ']' character can be included
71791** in the list by making it the first character after '[' or '^'.  A
71792** range of characters can be specified using '-'.  Example:
71793** "[a-z]" matches any single lower-case letter.  To match a '-', make
71794** it the last character in the list.
71795**
71796** This routine is usually quick, but can be N**2 in the worst case.
71797**
71798** Hints: to match '*' or '?', put them in "[]".  Like this:
71799**
71800**         abc[*]xyz        Matches "abc*xyz" only
71801*/
71802static int patternCompare(
71803  const u8 *zPattern,              /* The glob pattern */
71804  const u8 *zString,               /* The string to compare against the glob */
71805  const struct compareInfo *pInfo, /* Information about how to do the compare */
71806  const int esc                    /* The escape character */
71807){
71808  int c, c2;
71809  int invert;
71810  int seen;
71811  u8 matchOne = pInfo->matchOne;
71812  u8 matchAll = pInfo->matchAll;
71813  u8 matchSet = pInfo->matchSet;
71814  u8 noCase = pInfo->noCase;
71815  int prevEscape = 0;     /* True if the previous character was 'escape' */
71816
71817  while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
71818    if( !prevEscape && c==matchAll ){
71819      while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
71820               || c == matchOne ){
71821        if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
71822          return 0;
71823        }
71824      }
71825      if( c==0 ){
71826        return 1;
71827      }else if( c==esc ){
71828        c = sqlite3Utf8Read(zPattern, &zPattern);
71829        if( c==0 ){
71830          return 0;
71831        }
71832      }else if( c==matchSet ){
71833        assert( esc==0 );         /* This is GLOB, not LIKE */
71834        assert( matchSet<0x80 );  /* '[' is a single-byte character */
71835        while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
71836          SQLITE_SKIP_UTF8(zString);
71837        }
71838        return *zString!=0;
71839      }
71840      while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
71841        if( noCase ){
71842          GlogUpperToLower(c2);
71843          GlogUpperToLower(c);
71844          while( c2 != 0 && c2 != c ){
71845            c2 = sqlite3Utf8Read(zString, &zString);
71846            GlogUpperToLower(c2);
71847          }
71848        }else{
71849          while( c2 != 0 && c2 != c ){
71850            c2 = sqlite3Utf8Read(zString, &zString);
71851          }
71852        }
71853        if( c2==0 ) return 0;
71854        if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
71855      }
71856      return 0;
71857    }else if( !prevEscape && c==matchOne ){
71858      if( sqlite3Utf8Read(zString, &zString)==0 ){
71859        return 0;
71860      }
71861    }else if( c==matchSet ){
71862      int prior_c = 0;
71863      assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
71864      seen = 0;
71865      invert = 0;
71866      c = sqlite3Utf8Read(zString, &zString);
71867      if( c==0 ) return 0;
71868      c2 = sqlite3Utf8Read(zPattern, &zPattern);
71869      if( c2=='^' ){
71870        invert = 1;
71871        c2 = sqlite3Utf8Read(zPattern, &zPattern);
71872      }
71873      if( c2==']' ){
71874        if( c==']' ) seen = 1;
71875        c2 = sqlite3Utf8Read(zPattern, &zPattern);
71876      }
71877      while( c2 && c2!=']' ){
71878        if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
71879          c2 = sqlite3Utf8Read(zPattern, &zPattern);
71880          if( c>=prior_c && c<=c2 ) seen = 1;
71881          prior_c = 0;
71882        }else{
71883          if( c==c2 ){
71884            seen = 1;
71885          }
71886          prior_c = c2;
71887        }
71888        c2 = sqlite3Utf8Read(zPattern, &zPattern);
71889      }
71890      if( c2==0 || (seen ^ invert)==0 ){
71891        return 0;
71892      }
71893    }else if( esc==c && !prevEscape ){
71894      prevEscape = 1;
71895    }else{
71896      c2 = sqlite3Utf8Read(zString, &zString);
71897      if( noCase ){
71898        GlogUpperToLower(c);
71899        GlogUpperToLower(c2);
71900      }
71901      if( c!=c2 ){
71902        return 0;
71903      }
71904      prevEscape = 0;
71905    }
71906  }
71907  return *zString==0;
71908}
71909
71910/*
71911** Count the number of times that the LIKE operator (or GLOB which is
71912** just a variation of LIKE) gets called.  This is used for testing
71913** only.
71914*/
71915#ifdef SQLITE_TEST
71916SQLITE_API int sqlite3_like_count = 0;
71917#endif
71918
71919
71920/*
71921** Implementation of the like() SQL function.  This function implements
71922** the build-in LIKE operator.  The first argument to the function is the
71923** pattern and the second argument is the string.  So, the SQL statements:
71924**
71925**       A LIKE B
71926**
71927** is implemented as like(B,A).
71928**
71929** This same function (with a different compareInfo structure) computes
71930** the GLOB operator.
71931*/
71932static void likeFunc(
71933  sqlite3_context *context,
71934  int argc,
71935  sqlite3_value **argv
71936){
71937  const unsigned char *zA, *zB;
71938  int escape = 0;
71939  int nPat;
71940  sqlite3 *db = sqlite3_context_db_handle(context);
71941
71942  zB = sqlite3_value_text(argv[0]);
71943  zA = sqlite3_value_text(argv[1]);
71944
71945  /* Limit the length of the LIKE or GLOB pattern to avoid problems
71946  ** of deep recursion and N*N behavior in patternCompare().
71947  */
71948  nPat = sqlite3_value_bytes(argv[0]);
71949  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
71950  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
71951  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
71952    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
71953    return;
71954  }
71955  assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
71956
71957  if( argc==3 ){
71958    /* The escape character string must consist of a single UTF-8 character.
71959    ** Otherwise, return an error.
71960    */
71961    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
71962    if( zEsc==0 ) return;
71963    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
71964      sqlite3_result_error(context,
71965          "ESCAPE expression must be a single character", -1);
71966      return;
71967    }
71968    escape = sqlite3Utf8Read(zEsc, &zEsc);
71969  }
71970  if( zA && zB ){
71971    struct compareInfo *pInfo = sqlite3_user_data(context);
71972#ifdef SQLITE_TEST
71973    sqlite3_like_count++;
71974#endif
71975
71976    sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
71977  }
71978}
71979
71980/*
71981** Implementation of the NULLIF(x,y) function.  The result is the first
71982** argument if the arguments are different.  The result is NULL if the
71983** arguments are equal to each other.
71984*/
71985static void nullifFunc(
71986  sqlite3_context *context,
71987  int NotUsed,
71988  sqlite3_value **argv
71989){
71990  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
71991  UNUSED_PARAMETER(NotUsed);
71992  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
71993    sqlite3_result_value(context, argv[0]);
71994  }
71995}
71996
71997/*
71998** Implementation of the sqlite_version() function.  The result is the version
71999** of the SQLite library that is running.
72000*/
72001static void versionFunc(
72002  sqlite3_context *context,
72003  int NotUsed,
72004  sqlite3_value **NotUsed2
72005){
72006  UNUSED_PARAMETER2(NotUsed, NotUsed2);
72007  sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
72008}
72009
72010/*
72011** Implementation of the sqlite_source_id() function. The result is a string
72012** that identifies the particular version of the source code used to build
72013** SQLite.
72014*/
72015static void sourceidFunc(
72016  sqlite3_context *context,
72017  int NotUsed,
72018  sqlite3_value **NotUsed2
72019){
72020  UNUSED_PARAMETER2(NotUsed, NotUsed2);
72021  sqlite3_result_text(context, SQLITE_SOURCE_ID, -1, SQLITE_STATIC);
72022}
72023
72024/* Array for converting from half-bytes (nybbles) into ASCII hex
72025** digits. */
72026static const char hexdigits[] = {
72027  '0', '1', '2', '3', '4', '5', '6', '7',
72028  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
72029};
72030
72031/*
72032** EXPERIMENTAL - This is not an official function.  The interface may
72033** change.  This function may disappear.  Do not write code that depends
72034** on this function.
72035**
72036** Implementation of the QUOTE() function.  This function takes a single
72037** argument.  If the argument is numeric, the return value is the same as
72038** the argument.  If the argument is NULL, the return value is the string
72039** "NULL".  Otherwise, the argument is enclosed in single quotes with
72040** single-quote escapes.
72041*/
72042static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
72043  assert( argc==1 );
72044  UNUSED_PARAMETER(argc);
72045  switch( sqlite3_value_type(argv[0]) ){
72046    case SQLITE_INTEGER:
72047    case SQLITE_FLOAT: {
72048      sqlite3_result_value(context, argv[0]);
72049      break;
72050    }
72051    case SQLITE_BLOB: {
72052      char *zText = 0;
72053      char const *zBlob = sqlite3_value_blob(argv[0]);
72054      int nBlob = sqlite3_value_bytes(argv[0]);
72055      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
72056      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
72057      if( zText ){
72058        int i;
72059        for(i=0; i<nBlob; i++){
72060          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
72061          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
72062        }
72063        zText[(nBlob*2)+2] = '\'';
72064        zText[(nBlob*2)+3] = '\0';
72065        zText[0] = 'X';
72066        zText[1] = '\'';
72067        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
72068        sqlite3_free(zText);
72069      }
72070      break;
72071    }
72072    case SQLITE_TEXT: {
72073      int i,j;
72074      u64 n;
72075      const unsigned char *zArg = sqlite3_value_text(argv[0]);
72076      char *z;
72077
72078      if( zArg==0 ) return;
72079      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
72080      z = contextMalloc(context, ((i64)i)+((i64)n)+3);
72081      if( z ){
72082        z[0] = '\'';
72083        for(i=0, j=1; zArg[i]; i++){
72084          z[j++] = zArg[i];
72085          if( zArg[i]=='\'' ){
72086            z[j++] = '\'';
72087          }
72088        }
72089        z[j++] = '\'';
72090        z[j] = 0;
72091        sqlite3_result_text(context, z, j, sqlite3_free);
72092      }
72093      break;
72094    }
72095    default: {
72096      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
72097      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
72098      break;
72099    }
72100  }
72101}
72102
72103/*
72104** The hex() function.  Interpret the argument as a blob.  Return
72105** a hexadecimal rendering as text.
72106*/
72107static void hexFunc(
72108  sqlite3_context *context,
72109  int argc,
72110  sqlite3_value **argv
72111){
72112  int i, n;
72113  const unsigned char *pBlob;
72114  char *zHex, *z;
72115  assert( argc==1 );
72116  UNUSED_PARAMETER(argc);
72117  pBlob = sqlite3_value_blob(argv[0]);
72118  n = sqlite3_value_bytes(argv[0]);
72119  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
72120  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
72121  if( zHex ){
72122    for(i=0; i<n; i++, pBlob++){
72123      unsigned char c = *pBlob;
72124      *(z++) = hexdigits[(c>>4)&0xf];
72125      *(z++) = hexdigits[c&0xf];
72126    }
72127    *z = 0;
72128    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
72129  }
72130}
72131
72132/*
72133** The zeroblob(N) function returns a zero-filled blob of size N bytes.
72134*/
72135static void zeroblobFunc(
72136  sqlite3_context *context,
72137  int argc,
72138  sqlite3_value **argv
72139){
72140  i64 n;
72141  sqlite3 *db = sqlite3_context_db_handle(context);
72142  assert( argc==1 );
72143  UNUSED_PARAMETER(argc);
72144  n = sqlite3_value_int64(argv[0]);
72145  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
72146  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
72147  if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
72148    sqlite3_result_error_toobig(context);
72149  }else{
72150    sqlite3_result_zeroblob(context, (int)n);
72151  }
72152}
72153
72154/*
72155** The replace() function.  Three arguments are all strings: call
72156** them A, B, and C. The result is also a string which is derived
72157** from A by replacing every occurance of B with C.  The match
72158** must be exact.  Collating sequences are not used.
72159*/
72160static void replaceFunc(
72161  sqlite3_context *context,
72162  int argc,
72163  sqlite3_value **argv
72164){
72165  const unsigned char *zStr;        /* The input string A */
72166  const unsigned char *zPattern;    /* The pattern string B */
72167  const unsigned char *zRep;        /* The replacement string C */
72168  unsigned char *zOut;              /* The output */
72169  int nStr;                /* Size of zStr */
72170  int nPattern;            /* Size of zPattern */
72171  int nRep;                /* Size of zRep */
72172  i64 nOut;                /* Maximum size of zOut */
72173  int loopLimit;           /* Last zStr[] that might match zPattern[] */
72174  int i, j;                /* Loop counters */
72175
72176  assert( argc==3 );
72177  UNUSED_PARAMETER(argc);
72178  zStr = sqlite3_value_text(argv[0]);
72179  if( zStr==0 ) return;
72180  nStr = sqlite3_value_bytes(argv[0]);
72181  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
72182  zPattern = sqlite3_value_text(argv[1]);
72183  if( zPattern==0 ){
72184    assert( sqlite3_value_type(argv[1])==SQLITE_NULL
72185            || sqlite3_context_db_handle(context)->mallocFailed );
72186    return;
72187  }
72188  if( zPattern[0]==0 ){
72189    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
72190    sqlite3_result_value(context, argv[0]);
72191    return;
72192  }
72193  nPattern = sqlite3_value_bytes(argv[1]);
72194  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
72195  zRep = sqlite3_value_text(argv[2]);
72196  if( zRep==0 ) return;
72197  nRep = sqlite3_value_bytes(argv[2]);
72198  assert( zRep==sqlite3_value_text(argv[2]) );
72199  nOut = nStr + 1;
72200  assert( nOut<SQLITE_MAX_LENGTH );
72201  zOut = contextMalloc(context, (i64)nOut);
72202  if( zOut==0 ){
72203    return;
72204  }
72205  loopLimit = nStr - nPattern;
72206  for(i=j=0; i<=loopLimit; i++){
72207    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
72208      zOut[j++] = zStr[i];
72209    }else{
72210      u8 *zOld;
72211      sqlite3 *db = sqlite3_context_db_handle(context);
72212      nOut += nRep - nPattern;
72213      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
72214      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
72215      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
72216        sqlite3_result_error_toobig(context);
72217        sqlite3DbFree(db, zOut);
72218        return;
72219      }
72220      zOld = zOut;
72221      zOut = sqlite3_realloc(zOut, (int)nOut);
72222      if( zOut==0 ){
72223        sqlite3_result_error_nomem(context);
72224        sqlite3DbFree(db, zOld);
72225        return;
72226      }
72227      memcpy(&zOut[j], zRep, nRep);
72228      j += nRep;
72229      i += nPattern-1;
72230    }
72231  }
72232  assert( j+nStr-i+1==nOut );
72233  memcpy(&zOut[j], &zStr[i], nStr-i);
72234  j += nStr - i;
72235  assert( j<=nOut );
72236  zOut[j] = 0;
72237  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
72238}
72239
72240/*
72241** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
72242** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
72243*/
72244static void trimFunc(
72245  sqlite3_context *context,
72246  int argc,
72247  sqlite3_value **argv
72248){
72249  const unsigned char *zIn;         /* Input string */
72250  const unsigned char *zCharSet;    /* Set of characters to trim */
72251  int nIn;                          /* Number of bytes in input */
72252  int flags;                        /* 1: trimleft  2: trimright  3: trim */
72253  int i;                            /* Loop counter */
72254  unsigned char *aLen = 0;          /* Length of each character in zCharSet */
72255  unsigned char **azChar = 0;       /* Individual characters in zCharSet */
72256  int nChar;                        /* Number of characters in zCharSet */
72257
72258  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
72259    return;
72260  }
72261  zIn = sqlite3_value_text(argv[0]);
72262  if( zIn==0 ) return;
72263  nIn = sqlite3_value_bytes(argv[0]);
72264  assert( zIn==sqlite3_value_text(argv[0]) );
72265  if( argc==1 ){
72266    static const unsigned char lenOne[] = { 1 };
72267    static unsigned char * const azOne[] = { (u8*)" " };
72268    nChar = 1;
72269    aLen = (u8*)lenOne;
72270    azChar = (unsigned char **)azOne;
72271    zCharSet = 0;
72272  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
72273    return;
72274  }else{
72275    const unsigned char *z;
72276    for(z=zCharSet, nChar=0; *z; nChar++){
72277      SQLITE_SKIP_UTF8(z);
72278    }
72279    if( nChar>0 ){
72280      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
72281      if( azChar==0 ){
72282        return;
72283      }
72284      aLen = (unsigned char*)&azChar[nChar];
72285      for(z=zCharSet, nChar=0; *z; nChar++){
72286        azChar[nChar] = (unsigned char *)z;
72287        SQLITE_SKIP_UTF8(z);
72288        aLen[nChar] = (u8)(z - azChar[nChar]);
72289      }
72290    }
72291  }
72292  if( nChar>0 ){
72293    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
72294    if( flags & 1 ){
72295      while( nIn>0 ){
72296        int len = 0;
72297        for(i=0; i<nChar; i++){
72298          len = aLen[i];
72299          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
72300        }
72301        if( i>=nChar ) break;
72302        zIn += len;
72303        nIn -= len;
72304      }
72305    }
72306    if( flags & 2 ){
72307      while( nIn>0 ){
72308        int len = 0;
72309        for(i=0; i<nChar; i++){
72310          len = aLen[i];
72311          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
72312        }
72313        if( i>=nChar ) break;
72314        nIn -= len;
72315      }
72316    }
72317    if( zCharSet ){
72318      sqlite3_free(azChar);
72319    }
72320  }
72321  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
72322}
72323
72324
72325/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
72326** is only available if the SQLITE_SOUNDEX compile-time option is used
72327** when SQLite is built.
72328*/
72329#ifdef SQLITE_SOUNDEX
72330/*
72331** Compute the soundex encoding of a word.
72332**
72333** IMP: R-59782-00072 The soundex(X) function returns a string that is the
72334** soundex encoding of the string X.
72335*/
72336static void soundexFunc(
72337  sqlite3_context *context,
72338  int argc,
72339  sqlite3_value **argv
72340){
72341  char zResult[8];
72342  const u8 *zIn;
72343  int i, j;
72344  static const unsigned char iCode[] = {
72345    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72346    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72347    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72348    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72349    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
72350    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
72351    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
72352    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
72353  };
72354  assert( argc==1 );
72355  zIn = (u8*)sqlite3_value_text(argv[0]);
72356  if( zIn==0 ) zIn = (u8*)"";
72357  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
72358  if( zIn[i] ){
72359    u8 prevcode = iCode[zIn[i]&0x7f];
72360    zResult[0] = sqlite3Toupper(zIn[i]);
72361    for(j=1; j<4 && zIn[i]; i++){
72362      int code = iCode[zIn[i]&0x7f];
72363      if( code>0 ){
72364        if( code!=prevcode ){
72365          prevcode = code;
72366          zResult[j++] = code + '0';
72367        }
72368      }else{
72369        prevcode = 0;
72370      }
72371    }
72372    while( j<4 ){
72373      zResult[j++] = '0';
72374    }
72375    zResult[j] = 0;
72376    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
72377  }else{
72378    /* IMP: R-64894-50321 The string "?000" is returned if the argument
72379    ** is NULL or contains no ASCII alphabetic characters. */
72380    sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
72381  }
72382}
72383#endif /* SQLITE_SOUNDEX */
72384
72385#ifndef SQLITE_OMIT_LOAD_EXTENSION
72386/*
72387** A function that loads a shared-library extension then returns NULL.
72388*/
72389static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
72390  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
72391  const char *zProc;
72392  sqlite3 *db = sqlite3_context_db_handle(context);
72393  char *zErrMsg = 0;
72394
72395  if( argc==2 ){
72396    zProc = (const char *)sqlite3_value_text(argv[1]);
72397  }else{
72398    zProc = 0;
72399  }
72400  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
72401    sqlite3_result_error(context, zErrMsg, -1);
72402    sqlite3_free(zErrMsg);
72403  }
72404}
72405#endif
72406
72407
72408/*
72409** An instance of the following structure holds the context of a
72410** sum() or avg() aggregate computation.
72411*/
72412typedef struct SumCtx SumCtx;
72413struct SumCtx {
72414  double rSum;      /* Floating point sum */
72415  i64 iSum;         /* Integer sum */
72416  i64 cnt;          /* Number of elements summed */
72417  u8 overflow;      /* True if integer overflow seen */
72418  u8 approx;        /* True if non-integer value was input to the sum */
72419};
72420
72421/*
72422** Routines used to compute the sum, average, and total.
72423**
72424** The SUM() function follows the (broken) SQL standard which means
72425** that it returns NULL if it sums over no inputs.  TOTAL returns
72426** 0.0 in that case.  In addition, TOTAL always returns a float where
72427** SUM might return an integer if it never encounters a floating point
72428** value.  TOTAL never fails, but SUM might through an exception if
72429** it overflows an integer.
72430*/
72431static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
72432  SumCtx *p;
72433  int type;
72434  assert( argc==1 );
72435  UNUSED_PARAMETER(argc);
72436  p = sqlite3_aggregate_context(context, sizeof(*p));
72437  type = sqlite3_value_numeric_type(argv[0]);
72438  if( p && type!=SQLITE_NULL ){
72439    p->cnt++;
72440    if( type==SQLITE_INTEGER ){
72441      i64 v = sqlite3_value_int64(argv[0]);
72442      p->rSum += v;
72443      if( (p->approx|p->overflow)==0 ){
72444        i64 iNewSum = p->iSum + v;
72445        int s1 = (int)(p->iSum >> (sizeof(i64)*8-1));
72446        int s2 = (int)(v       >> (sizeof(i64)*8-1));
72447        int s3 = (int)(iNewSum >> (sizeof(i64)*8-1));
72448        p->overflow = ((s1&s2&~s3) | (~s1&~s2&s3))?1:0;
72449        p->iSum = iNewSum;
72450      }
72451    }else{
72452      p->rSum += sqlite3_value_double(argv[0]);
72453      p->approx = 1;
72454    }
72455  }
72456}
72457static void sumFinalize(sqlite3_context *context){
72458  SumCtx *p;
72459  p = sqlite3_aggregate_context(context, 0);
72460  if( p && p->cnt>0 ){
72461    if( p->overflow ){
72462      sqlite3_result_error(context,"integer overflow",-1);
72463    }else if( p->approx ){
72464      sqlite3_result_double(context, p->rSum);
72465    }else{
72466      sqlite3_result_int64(context, p->iSum);
72467    }
72468  }
72469}
72470static void avgFinalize(sqlite3_context *context){
72471  SumCtx *p;
72472  p = sqlite3_aggregate_context(context, 0);
72473  if( p && p->cnt>0 ){
72474    sqlite3_result_double(context, p->rSum/(double)p->cnt);
72475  }
72476}
72477static void totalFinalize(sqlite3_context *context){
72478  SumCtx *p;
72479  p = sqlite3_aggregate_context(context, 0);
72480  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
72481  sqlite3_result_double(context, p ? p->rSum : (double)0);
72482}
72483
72484/*
72485** The following structure keeps track of state information for the
72486** count() aggregate function.
72487*/
72488typedef struct CountCtx CountCtx;
72489struct CountCtx {
72490  i64 n;
72491};
72492
72493/*
72494** Routines to implement the count() aggregate function.
72495*/
72496static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
72497  CountCtx *p;
72498  p = sqlite3_aggregate_context(context, sizeof(*p));
72499  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
72500    p->n++;
72501  }
72502
72503#ifndef SQLITE_OMIT_DEPRECATED
72504  /* The sqlite3_aggregate_count() function is deprecated.  But just to make
72505  ** sure it still operates correctly, verify that its count agrees with our
72506  ** internal count when using count(*) and when the total count can be
72507  ** expressed as a 32-bit integer. */
72508  assert( argc==1 || p==0 || p->n>0x7fffffff
72509          || p->n==sqlite3_aggregate_count(context) );
72510#endif
72511}
72512static void countFinalize(sqlite3_context *context){
72513  CountCtx *p;
72514  p = sqlite3_aggregate_context(context, 0);
72515  sqlite3_result_int64(context, p ? p->n : 0);
72516}
72517
72518/*
72519** Routines to implement min() and max() aggregate functions.
72520*/
72521static void minmaxStep(
72522  sqlite3_context *context,
72523  int NotUsed,
72524  sqlite3_value **argv
72525){
72526  Mem *pArg  = (Mem *)argv[0];
72527  Mem *pBest;
72528  UNUSED_PARAMETER(NotUsed);
72529
72530  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
72531  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
72532  if( !pBest ) return;
72533
72534  if( pBest->flags ){
72535    int max;
72536    int cmp;
72537    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
72538    /* This step function is used for both the min() and max() aggregates,
72539    ** the only difference between the two being that the sense of the
72540    ** comparison is inverted. For the max() aggregate, the
72541    ** sqlite3_user_data() function returns (void *)-1. For min() it
72542    ** returns (void *)db, where db is the sqlite3* database pointer.
72543    ** Therefore the next statement sets variable 'max' to 1 for the max()
72544    ** aggregate, or 0 for min().
72545    */
72546    max = sqlite3_user_data(context)!=0;
72547    cmp = sqlite3MemCompare(pBest, pArg, pColl);
72548    if( (max && cmp<0) || (!max && cmp>0) ){
72549      sqlite3VdbeMemCopy(pBest, pArg);
72550    }
72551  }else{
72552    sqlite3VdbeMemCopy(pBest, pArg);
72553  }
72554}
72555static void minMaxFinalize(sqlite3_context *context){
72556  sqlite3_value *pRes;
72557  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
72558  if( pRes ){
72559    if( ALWAYS(pRes->flags) ){
72560      sqlite3_result_value(context, pRes);
72561    }
72562    sqlite3VdbeMemRelease(pRes);
72563  }
72564}
72565
72566/*
72567** group_concat(EXPR, ?SEPARATOR?)
72568*/
72569static void groupConcatStep(
72570  sqlite3_context *context,
72571  int argc,
72572  sqlite3_value **argv
72573){
72574  const char *zVal;
72575  StrAccum *pAccum;
72576  const char *zSep;
72577  int nVal, nSep;
72578  assert( argc==1 || argc==2 );
72579  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
72580  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
72581
72582  if( pAccum ){
72583    sqlite3 *db = sqlite3_context_db_handle(context);
72584    int firstTerm = pAccum->useMalloc==0;
72585    pAccum->useMalloc = 1;
72586    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
72587    if( !firstTerm ){
72588      if( argc==2 ){
72589        zSep = (char*)sqlite3_value_text(argv[1]);
72590        nSep = sqlite3_value_bytes(argv[1]);
72591      }else{
72592        zSep = ",";
72593        nSep = 1;
72594      }
72595      sqlite3StrAccumAppend(pAccum, zSep, nSep);
72596    }
72597    zVal = (char*)sqlite3_value_text(argv[0]);
72598    nVal = sqlite3_value_bytes(argv[0]);
72599    sqlite3StrAccumAppend(pAccum, zVal, nVal);
72600  }
72601}
72602static void groupConcatFinalize(sqlite3_context *context){
72603  StrAccum *pAccum;
72604  pAccum = sqlite3_aggregate_context(context, 0);
72605  if( pAccum ){
72606    if( pAccum->tooBig ){
72607      sqlite3_result_error_toobig(context);
72608    }else if( pAccum->mallocFailed ){
72609      sqlite3_result_error_nomem(context);
72610    }else{
72611      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
72612                          sqlite3_free);
72613    }
72614  }
72615}
72616
72617/*
72618** This function registered all of the above C functions as SQL
72619** functions.  This should be the only routine in this file with
72620** external linkage.
72621*/
72622SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
72623#ifndef SQLITE_OMIT_ALTERTABLE
72624  sqlite3AlterFunctions(db);
72625#endif
72626  if( !db->mallocFailed ){
72627    int rc = sqlite3_overload_function(db, "MATCH", 2);
72628    assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
72629    if( rc==SQLITE_NOMEM ){
72630      db->mallocFailed = 1;
72631    }
72632  }
72633}
72634
72635/*
72636** Set the LIKEOPT flag on the 2-argument function with the given name.
72637*/
72638static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
72639  FuncDef *pDef;
72640  pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
72641                             2, SQLITE_UTF8, 0);
72642  if( ALWAYS(pDef) ){
72643    pDef->flags = flagVal;
72644  }
72645}
72646
72647/*
72648** Register the built-in LIKE and GLOB functions.  The caseSensitive
72649** parameter determines whether or not the LIKE operator is case
72650** sensitive.  GLOB is always case sensitive.
72651*/
72652SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
72653  struct compareInfo *pInfo;
72654  if( caseSensitive ){
72655    pInfo = (struct compareInfo*)&likeInfoAlt;
72656  }else{
72657    pInfo = (struct compareInfo*)&likeInfoNorm;
72658  }
72659  sqlite3CreateFunc(db, "like", 2, SQLITE_ANY, pInfo, likeFunc, 0, 0);
72660  sqlite3CreateFunc(db, "like", 3, SQLITE_ANY, pInfo, likeFunc, 0, 0);
72661  sqlite3CreateFunc(db, "glob", 2, SQLITE_ANY,
72662      (struct compareInfo*)&globInfo, likeFunc, 0,0);
72663  setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
72664  setLikeOptFlag(db, "like",
72665      caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
72666}
72667
72668/*
72669** pExpr points to an expression which implements a function.  If
72670** it is appropriate to apply the LIKE optimization to that function
72671** then set aWc[0] through aWc[2] to the wildcard characters and
72672** return TRUE.  If the function is not a LIKE-style function then
72673** return FALSE.
72674*/
72675SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
72676  FuncDef *pDef;
72677  if( pExpr->op!=TK_FUNCTION
72678   || !pExpr->x.pList
72679   || pExpr->x.pList->nExpr!=2
72680  ){
72681    return 0;
72682  }
72683  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
72684  pDef = sqlite3FindFunction(db, pExpr->u.zToken,
72685                             sqlite3Strlen30(pExpr->u.zToken),
72686                             2, SQLITE_UTF8, 0);
72687  if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
72688    return 0;
72689  }
72690
72691  /* The memcpy() statement assumes that the wildcard characters are
72692  ** the first three statements in the compareInfo structure.  The
72693  ** asserts() that follow verify that assumption
72694  */
72695  memcpy(aWc, pDef->pUserData, 3);
72696  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
72697  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
72698  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
72699  *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
72700  return 1;
72701}
72702
72703/*
72704** All all of the FuncDef structures in the aBuiltinFunc[] array above
72705** to the global function hash table.  This occurs at start-time (as
72706** a consequence of calling sqlite3_initialize()).
72707**
72708** After this routine runs
72709*/
72710SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
72711  /*
72712  ** The following array holds FuncDef structures for all of the functions
72713  ** defined in this file.
72714  **
72715  ** The array cannot be constant since changes are made to the
72716  ** FuncDef.pHash elements at start-time.  The elements of this array
72717  ** are read-only after initialization is complete.
72718  */
72719  static SQLITE_WSD FuncDef aBuiltinFunc[] = {
72720    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
72721    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
72722    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
72723    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
72724    FUNCTION(trim,               1, 3, 0, trimFunc         ),
72725    FUNCTION(trim,               2, 3, 0, trimFunc         ),
72726    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
72727    FUNCTION(min,                0, 0, 1, 0                ),
72728    AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
72729    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
72730    FUNCTION(max,                0, 1, 1, 0                ),
72731    AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
72732    FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
72733    FUNCTION(length,             1, 0, 0, lengthFunc       ),
72734    FUNCTION(substr,             2, 0, 0, substrFunc       ),
72735    FUNCTION(substr,             3, 0, 0, substrFunc       ),
72736    FUNCTION(abs,                1, 0, 0, absFunc          ),
72737#ifndef SQLITE_OMIT_FLOATING_POINT
72738    FUNCTION(round,              1, 0, 0, roundFunc        ),
72739    FUNCTION(round,              2, 0, 0, roundFunc        ),
72740#endif
72741    FUNCTION(upper,              1, 0, 0, upperFunc        ),
72742    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
72743    FUNCTION(coalesce,           1, 0, 0, 0                ),
72744    FUNCTION(coalesce,           0, 0, 0, 0                ),
72745/*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
72746    {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0},
72747    FUNCTION(hex,                1, 0, 0, hexFunc          ),
72748/*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
72749    {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0},
72750    FUNCTION(random,             0, 0, 0, randomFunc       ),
72751    FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
72752    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
72753    FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
72754    FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
72755    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
72756    FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
72757    FUNCTION(changes,            0, 0, 0, changes          ),
72758    FUNCTION(total_changes,      0, 0, 0, total_changes    ),
72759    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
72760    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
72761  #ifdef SQLITE_SOUNDEX
72762    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
72763  #endif
72764  #ifndef SQLITE_OMIT_LOAD_EXTENSION
72765    FUNCTION(load_extension,     1, 0, 0, loadExt          ),
72766    FUNCTION(load_extension,     2, 0, 0, loadExt          ),
72767  #endif
72768    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
72769    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
72770    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
72771 /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
72772    {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0},
72773    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
72774    AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
72775    AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
72776
72777    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
72778  #ifdef SQLITE_CASE_SENSITIVE_LIKE
72779    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
72780    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
72781  #else
72782    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
72783    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
72784  #endif
72785  };
72786
72787  int i;
72788  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
72789  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
72790
72791  for(i=0; i<ArraySize(aBuiltinFunc); i++){
72792    sqlite3FuncDefInsert(pHash, &aFunc[i]);
72793  }
72794  sqlite3RegisterDateTimeFunctions();
72795}
72796
72797/************** End of func.c ************************************************/
72798/************** Begin file fkey.c ********************************************/
72799/*
72800**
72801** The author disclaims copyright to this source code.  In place of
72802** a legal notice, here is a blessing:
72803**
72804**    May you do good and not evil.
72805**    May you find forgiveness for yourself and forgive others.
72806**    May you share freely, never taking more than you give.
72807**
72808*************************************************************************
72809** This file contains code used by the compiler to add foreign key
72810** support to compiled SQL statements.
72811*/
72812
72813#ifndef SQLITE_OMIT_FOREIGN_KEY
72814#ifndef SQLITE_OMIT_TRIGGER
72815
72816/*
72817** Deferred and Immediate FKs
72818** --------------------------
72819**
72820** Foreign keys in SQLite come in two flavours: deferred and immediate.
72821** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
72822** is returned and the current statement transaction rolled back. If a
72823** deferred foreign key constraint is violated, no action is taken
72824** immediately. However if the application attempts to commit the
72825** transaction before fixing the constraint violation, the attempt fails.
72826**
72827** Deferred constraints are implemented using a simple counter associated
72828** with the database handle. The counter is set to zero each time a
72829** database transaction is opened. Each time a statement is executed
72830** that causes a foreign key violation, the counter is incremented. Each
72831** time a statement is executed that removes an existing violation from
72832** the database, the counter is decremented. When the transaction is
72833** committed, the commit fails if the current value of the counter is
72834** greater than zero. This scheme has two big drawbacks:
72835**
72836**   * When a commit fails due to a deferred foreign key constraint,
72837**     there is no way to tell which foreign constraint is not satisfied,
72838**     or which row it is not satisfied for.
72839**
72840**   * If the database contains foreign key violations when the
72841**     transaction is opened, this may cause the mechanism to malfunction.
72842**
72843** Despite these problems, this approach is adopted as it seems simpler
72844** than the alternatives.
72845**
72846** INSERT operations:
72847**
72848**   I.1) For each FK for which the table is the child table, search
72849**        the parent table for a match. If none is found increment the
72850**        constraint counter.
72851**
72852**   I.2) For each FK for which the table is the parent table,
72853**        search the child table for rows that correspond to the new
72854**        row in the parent table. Decrement the counter for each row
72855**        found (as the constraint is now satisfied).
72856**
72857** DELETE operations:
72858**
72859**   D.1) For each FK for which the table is the child table,
72860**        search the parent table for a row that corresponds to the
72861**        deleted row in the child table. If such a row is not found,
72862**        decrement the counter.
72863**
72864**   D.2) For each FK for which the table is the parent table, search
72865**        the child table for rows that correspond to the deleted row
72866**        in the parent table. For each found increment the counter.
72867**
72868** UPDATE operations:
72869**
72870**   An UPDATE command requires that all 4 steps above are taken, but only
72871**   for FK constraints for which the affected columns are actually
72872**   modified (values must be compared at runtime).
72873**
72874** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
72875** This simplifies the implementation a bit.
72876**
72877** For the purposes of immediate FK constraints, the OR REPLACE conflict
72878** resolution is considered to delete rows before the new row is inserted.
72879** If a delete caused by OR REPLACE violates an FK constraint, an exception
72880** is thrown, even if the FK constraint would be satisfied after the new
72881** row is inserted.
72882**
72883** Immediate constraints are usually handled similarly. The only difference
72884** is that the counter used is stored as part of each individual statement
72885** object (struct Vdbe). If, after the statement has run, its immediate
72886** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
72887** and the statement transaction is rolled back. An exception is an INSERT
72888** statement that inserts a single row only (no triggers). In this case,
72889** instead of using a counter, an exception is thrown immediately if the
72890** INSERT violates a foreign key constraint. This is necessary as such
72891** an INSERT does not open a statement transaction.
72892**
72893** TODO: How should dropping a table be handled? How should renaming a
72894** table be handled?
72895**
72896**
72897** Query API Notes
72898** ---------------
72899**
72900** Before coding an UPDATE or DELETE row operation, the code-generator
72901** for those two operations needs to know whether or not the operation
72902** requires any FK processing and, if so, which columns of the original
72903** row are required by the FK processing VDBE code (i.e. if FKs were
72904** implemented using triggers, which of the old.* columns would be
72905** accessed). No information is required by the code-generator before
72906** coding an INSERT operation. The functions used by the UPDATE/DELETE
72907** generation code to query for this information are:
72908**
72909**   sqlite3FkRequired() - Test to see if FK processing is required.
72910**   sqlite3FkOldmask()  - Query for the set of required old.* columns.
72911**
72912**
72913** Externally accessible module functions
72914** --------------------------------------
72915**
72916**   sqlite3FkCheck()    - Check for foreign key violations.
72917**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
72918**   sqlite3FkDelete()   - Delete an FKey structure.
72919*/
72920
72921/*
72922** VDBE Calling Convention
72923** -----------------------
72924**
72925** Example:
72926**
72927**   For the following INSERT statement:
72928**
72929**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
72930**     INSERT INTO t1 VALUES(1, 2, 3.1);
72931**
72932**   Register (x):        2    (type integer)
72933**   Register (x+1):      1    (type integer)
72934**   Register (x+2):      NULL (type NULL)
72935**   Register (x+3):      3.1  (type real)
72936*/
72937
72938/*
72939** A foreign key constraint requires that the key columns in the parent
72940** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
72941** Given that pParent is the parent table for foreign key constraint pFKey,
72942** search the schema a unique index on the parent key columns.
72943**
72944** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
72945** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
72946** is set to point to the unique index.
72947**
72948** If the parent key consists of a single column (the foreign key constraint
72949** is not a composite foreign key), output variable *paiCol is set to NULL.
72950** Otherwise, it is set to point to an allocated array of size N, where
72951** N is the number of columns in the parent key. The first element of the
72952** array is the index of the child table column that is mapped by the FK
72953** constraint to the parent table column stored in the left-most column
72954** of index *ppIdx. The second element of the array is the index of the
72955** child table column that corresponds to the second left-most column of
72956** *ppIdx, and so on.
72957**
72958** If the required index cannot be found, either because:
72959**
72960**   1) The named parent key columns do not exist, or
72961**
72962**   2) The named parent key columns do exist, but are not subject to a
72963**      UNIQUE or PRIMARY KEY constraint, or
72964**
72965**   3) No parent key columns were provided explicitly as part of the
72966**      foreign key definition, and the parent table does not have a
72967**      PRIMARY KEY, or
72968**
72969**   4) No parent key columns were provided explicitly as part of the
72970**      foreign key definition, and the PRIMARY KEY of the parent table
72971**      consists of a a different number of columns to the child key in
72972**      the child table.
72973**
72974** then non-zero is returned, and a "foreign key mismatch" error loaded
72975** into pParse. If an OOM error occurs, non-zero is returned and the
72976** pParse->db->mallocFailed flag is set.
72977*/
72978static int locateFkeyIndex(
72979  Parse *pParse,                  /* Parse context to store any error in */
72980  Table *pParent,                 /* Parent table of FK constraint pFKey */
72981  FKey *pFKey,                    /* Foreign key to find index for */
72982  Index **ppIdx,                  /* OUT: Unique index on parent table */
72983  int **paiCol                    /* OUT: Map of index columns in pFKey */
72984){
72985  Index *pIdx = 0;                    /* Value to return via *ppIdx */
72986  int *aiCol = 0;                     /* Value to return via *paiCol */
72987  int nCol = pFKey->nCol;             /* Number of columns in parent key */
72988  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
72989
72990  /* The caller is responsible for zeroing output parameters. */
72991  assert( ppIdx && *ppIdx==0 );
72992  assert( !paiCol || *paiCol==0 );
72993  assert( pParse );
72994
72995  /* If this is a non-composite (single column) foreign key, check if it
72996  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
72997  ** and *paiCol set to zero and return early.
72998  **
72999  ** Otherwise, for a composite foreign key (more than one column), allocate
73000  ** space for the aiCol array (returned via output parameter *paiCol).
73001  ** Non-composite foreign keys do not require the aiCol array.
73002  */
73003  if( nCol==1 ){
73004    /* The FK maps to the IPK if any of the following are true:
73005    **
73006    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
73007    **      mapped to the primary key of table pParent, or
73008    **   2) The FK is explicitly mapped to a column declared as INTEGER
73009    **      PRIMARY KEY.
73010    */
73011    if( pParent->iPKey>=0 ){
73012      if( !zKey ) return 0;
73013      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
73014    }
73015  }else if( paiCol ){
73016    assert( nCol>1 );
73017    aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
73018    if( !aiCol ) return 1;
73019    *paiCol = aiCol;
73020  }
73021
73022  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
73023    if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
73024      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
73025      ** of columns. If each indexed column corresponds to a foreign key
73026      ** column of pFKey, then this index is a winner.  */
73027
73028      if( zKey==0 ){
73029        /* If zKey is NULL, then this foreign key is implicitly mapped to
73030        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
73031        ** identified by the test (Index.autoIndex==2).  */
73032        if( pIdx->autoIndex==2 ){
73033          if( aiCol ){
73034            int i;
73035            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
73036          }
73037          break;
73038        }
73039      }else{
73040        /* If zKey is non-NULL, then this foreign key was declared to
73041        ** map to an explicit list of columns in table pParent. Check if this
73042        ** index matches those columns. Also, check that the index uses
73043        ** the default collation sequences for each column. */
73044        int i, j;
73045        for(i=0; i<nCol; i++){
73046          int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
73047          char *zDfltColl;                  /* Def. collation for column */
73048          char *zIdxCol;                    /* Name of indexed column */
73049
73050          /* If the index uses a collation sequence that is different from
73051          ** the default collation sequence for the column, this index is
73052          ** unusable. Bail out early in this case.  */
73053          zDfltColl = pParent->aCol[iCol].zColl;
73054          if( !zDfltColl ){
73055            zDfltColl = "BINARY";
73056          }
73057          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
73058
73059          zIdxCol = pParent->aCol[iCol].zName;
73060          for(j=0; j<nCol; j++){
73061            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
73062              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
73063              break;
73064            }
73065          }
73066          if( j==nCol ) break;
73067        }
73068        if( i==nCol ) break;      /* pIdx is usable */
73069      }
73070    }
73071  }
73072
73073  if( !pIdx ){
73074    if( !pParse->disableTriggers ){
73075      sqlite3ErrorMsg(pParse, "foreign key mismatch");
73076    }
73077    sqlite3DbFree(pParse->db, aiCol);
73078    return 1;
73079  }
73080
73081  *ppIdx = pIdx;
73082  return 0;
73083}
73084
73085/*
73086** This function is called when a row is inserted into or deleted from the
73087** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
73088** on the child table of pFKey, this function is invoked twice for each row
73089** affected - once to "delete" the old row, and then again to "insert" the
73090** new row.
73091**
73092** Each time it is called, this function generates VDBE code to locate the
73093** row in the parent table that corresponds to the row being inserted into
73094** or deleted from the child table. If the parent row can be found, no
73095** special action is taken. Otherwise, if the parent row can *not* be
73096** found in the parent table:
73097**
73098**   Operation | FK type   | Action taken
73099**   --------------------------------------------------------------------------
73100**   INSERT      immediate   Increment the "immediate constraint counter".
73101**
73102**   DELETE      immediate   Decrement the "immediate constraint counter".
73103**
73104**   INSERT      deferred    Increment the "deferred constraint counter".
73105**
73106**   DELETE      deferred    Decrement the "deferred constraint counter".
73107**
73108** These operations are identified in the comment at the top of this file
73109** (fkey.c) as "I.1" and "D.1".
73110*/
73111static void fkLookupParent(
73112  Parse *pParse,        /* Parse context */
73113  int iDb,              /* Index of database housing pTab */
73114  Table *pTab,          /* Parent table of FK pFKey */
73115  Index *pIdx,          /* Unique index on parent key columns in pTab */
73116  FKey *pFKey,          /* Foreign key constraint */
73117  int *aiCol,           /* Map from parent key columns to child table columns */
73118  int regData,          /* Address of array containing child table row */
73119  int nIncr,            /* Increment constraint counter by this */
73120  int isIgnore          /* If true, pretend pTab contains all NULL values */
73121){
73122  int i;                                    /* Iterator variable */
73123  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
73124  int iCur = pParse->nTab - 1;              /* Cursor number to use */
73125  int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
73126
73127  /* If nIncr is less than zero, then check at runtime if there are any
73128  ** outstanding constraints to resolve. If there are not, there is no need
73129  ** to check if deleting this row resolves any outstanding violations.
73130  **
73131  ** Check if any of the key columns in the child table row are NULL. If
73132  ** any are, then the constraint is considered satisfied. No need to
73133  ** search for a matching row in the parent table.  */
73134  if( nIncr<0 ){
73135    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
73136  }
73137  for(i=0; i<pFKey->nCol; i++){
73138    int iReg = aiCol[i] + regData + 1;
73139    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
73140  }
73141
73142  if( isIgnore==0 ){
73143    if( pIdx==0 ){
73144      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
73145      ** column of the parent table (table pTab).  */
73146      int iMustBeInt;               /* Address of MustBeInt instruction */
73147      int regTemp = sqlite3GetTempReg(pParse);
73148
73149      /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
73150      ** apply the affinity of the parent key). If this fails, then there
73151      ** is no matching parent key. Before using MustBeInt, make a copy of
73152      ** the value. Otherwise, the value inserted into the child key column
73153      ** will have INTEGER affinity applied to it, which may not be correct.  */
73154      sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
73155      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
73156
73157      /* If the parent table is the same as the child table, and we are about
73158      ** to increment the constraint-counter (i.e. this is an INSERT operation),
73159      ** then check if the row being inserted matches itself. If so, do not
73160      ** increment the constraint-counter.  */
73161      if( pTab==pFKey->pFrom && nIncr==1 ){
73162        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
73163      }
73164
73165      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
73166      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
73167      sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
73168      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
73169      sqlite3VdbeJumpHere(v, iMustBeInt);
73170      sqlite3ReleaseTempReg(pParse, regTemp);
73171    }else{
73172      int nCol = pFKey->nCol;
73173      int regTemp = sqlite3GetTempRange(pParse, nCol);
73174      int regRec = sqlite3GetTempReg(pParse);
73175      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
73176
73177      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
73178      sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
73179      for(i=0; i<nCol; i++){
73180        sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i);
73181      }
73182
73183      /* If the parent table is the same as the child table, and we are about
73184      ** to increment the constraint-counter (i.e. this is an INSERT operation),
73185      ** then check if the row being inserted matches itself. If so, do not
73186      ** increment the constraint-counter.  */
73187      if( pTab==pFKey->pFrom && nIncr==1 ){
73188        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
73189        for(i=0; i<nCol; i++){
73190          int iChild = aiCol[i]+1+regData;
73191          int iParent = pIdx->aiColumn[i]+1+regData;
73192          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
73193        }
73194        sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
73195      }
73196
73197      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
73198      sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
73199      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
73200
73201      sqlite3ReleaseTempReg(pParse, regRec);
73202      sqlite3ReleaseTempRange(pParse, regTemp, nCol);
73203    }
73204  }
73205
73206  if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
73207    /* Special case: If this is an INSERT statement that will insert exactly
73208    ** one row into the table, raise a constraint immediately instead of
73209    ** incrementing a counter. This is necessary as the VM code is being
73210    ** generated for will not open a statement transaction.  */
73211    assert( nIncr==1 );
73212    sqlite3HaltConstraint(
73213        pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
73214    );
73215  }else{
73216    if( nIncr>0 && pFKey->isDeferred==0 ){
73217      sqlite3ParseToplevel(pParse)->mayAbort = 1;
73218    }
73219    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
73220  }
73221
73222  sqlite3VdbeResolveLabel(v, iOk);
73223  sqlite3VdbeAddOp1(v, OP_Close, iCur);
73224}
73225
73226/*
73227** This function is called to generate code executed when a row is deleted
73228** from the parent table of foreign key constraint pFKey and, if pFKey is
73229** deferred, when a row is inserted into the same table. When generating
73230** code for an SQL UPDATE operation, this function may be called twice -
73231** once to "delete" the old row and once to "insert" the new row.
73232**
73233** The code generated by this function scans through the rows in the child
73234** table that correspond to the parent table row being deleted or inserted.
73235** For each child row found, one of the following actions is taken:
73236**
73237**   Operation | FK type   | Action taken
73238**   --------------------------------------------------------------------------
73239**   DELETE      immediate   Increment the "immediate constraint counter".
73240**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
73241**                           throw a "foreign key constraint failed" exception.
73242**
73243**   INSERT      immediate   Decrement the "immediate constraint counter".
73244**
73245**   DELETE      deferred    Increment the "deferred constraint counter".
73246**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
73247**                           throw a "foreign key constraint failed" exception.
73248**
73249**   INSERT      deferred    Decrement the "deferred constraint counter".
73250**
73251** These operations are identified in the comment at the top of this file
73252** (fkey.c) as "I.2" and "D.2".
73253*/
73254static void fkScanChildren(
73255  Parse *pParse,                  /* Parse context */
73256  SrcList *pSrc,                  /* SrcList containing the table to scan */
73257  Table *pTab,
73258  Index *pIdx,                    /* Foreign key index */
73259  FKey *pFKey,                    /* Foreign key relationship */
73260  int *aiCol,                     /* Map from pIdx cols to child table cols */
73261  int regData,                    /* Referenced table data starts here */
73262  int nIncr                       /* Amount to increment deferred counter by */
73263){
73264  sqlite3 *db = pParse->db;       /* Database handle */
73265  int i;                          /* Iterator variable */
73266  Expr *pWhere = 0;               /* WHERE clause to scan with */
73267  NameContext sNameContext;       /* Context used to resolve WHERE clause */
73268  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
73269  int iFkIfZero = 0;              /* Address of OP_FkIfZero */
73270  Vdbe *v = sqlite3GetVdbe(pParse);
73271
73272  assert( !pIdx || pIdx->pTable==pTab );
73273
73274  if( nIncr<0 ){
73275    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
73276  }
73277
73278  /* Create an Expr object representing an SQL expression like:
73279  **
73280  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
73281  **
73282  ** The collation sequence used for the comparison should be that of
73283  ** the parent key columns. The affinity of the parent key column should
73284  ** be applied to each child key value before the comparison takes place.
73285  */
73286  for(i=0; i<pFKey->nCol; i++){
73287    Expr *pLeft;                  /* Value from parent table row */
73288    Expr *pRight;                 /* Column ref to child table */
73289    Expr *pEq;                    /* Expression (pLeft = pRight) */
73290    int iCol;                     /* Index of column in child table */
73291    const char *zCol;             /* Name of column in child table */
73292
73293    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
73294    if( pLeft ){
73295      /* Set the collation sequence and affinity of the LHS of each TK_EQ
73296      ** expression to the parent key column defaults.  */
73297      if( pIdx ){
73298        Column *pCol;
73299        iCol = pIdx->aiColumn[i];
73300        pCol = &pIdx->pTable->aCol[iCol];
73301        pLeft->iTable = regData+iCol+1;
73302        pLeft->affinity = pCol->affinity;
73303        pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
73304      }else{
73305        pLeft->iTable = regData;
73306        pLeft->affinity = SQLITE_AFF_INTEGER;
73307      }
73308    }
73309    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
73310    assert( iCol>=0 );
73311    zCol = pFKey->pFrom->aCol[iCol].zName;
73312    pRight = sqlite3Expr(db, TK_ID, zCol);
73313    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
73314    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
73315  }
73316
73317  /* If the child table is the same as the parent table, and this scan
73318  ** is taking place as part of a DELETE operation (operation D.2), omit the
73319  ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
73320  ** clause, where $rowid is the rowid of the row being deleted.  */
73321  if( pTab==pFKey->pFrom && nIncr>0 ){
73322    Expr *pEq;                    /* Expression (pLeft = pRight) */
73323    Expr *pLeft;                  /* Value from parent table row */
73324    Expr *pRight;                 /* Column ref to child table */
73325    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
73326    pRight = sqlite3Expr(db, TK_COLUMN, 0);
73327    if( pLeft && pRight ){
73328      pLeft->iTable = regData;
73329      pLeft->affinity = SQLITE_AFF_INTEGER;
73330      pRight->iTable = pSrc->a[0].iCursor;
73331      pRight->iColumn = -1;
73332    }
73333    pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
73334    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
73335  }
73336
73337  /* Resolve the references in the WHERE clause. */
73338  memset(&sNameContext, 0, sizeof(NameContext));
73339  sNameContext.pSrcList = pSrc;
73340  sNameContext.pParse = pParse;
73341  sqlite3ResolveExprNames(&sNameContext, pWhere);
73342
73343  /* Create VDBE to loop through the entries in pSrc that match the WHERE
73344  ** clause. If the constraint is not deferred, throw an exception for
73345  ** each row found. Otherwise, for deferred constraints, increment the
73346  ** deferred constraint counter by nIncr for each row selected.  */
73347  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
73348  if( nIncr>0 && pFKey->isDeferred==0 ){
73349    sqlite3ParseToplevel(pParse)->mayAbort = 1;
73350  }
73351  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
73352  if( pWInfo ){
73353    sqlite3WhereEnd(pWInfo);
73354  }
73355
73356  /* Clean up the WHERE clause constructed above. */
73357  sqlite3ExprDelete(db, pWhere);
73358  if( iFkIfZero ){
73359    sqlite3VdbeJumpHere(v, iFkIfZero);
73360  }
73361}
73362
73363/*
73364** This function returns a pointer to the head of a linked list of FK
73365** constraints for which table pTab is the parent table. For example,
73366** given the following schema:
73367**
73368**   CREATE TABLE t1(a PRIMARY KEY);
73369**   CREATE TABLE t2(b REFERENCES t1(a);
73370**
73371** Calling this function with table "t1" as an argument returns a pointer
73372** to the FKey structure representing the foreign key constraint on table
73373** "t2". Calling this function with "t2" as the argument would return a
73374** NULL pointer (as there are no FK constraints for which t2 is the parent
73375** table).
73376*/
73377SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
73378  int nName = sqlite3Strlen30(pTab->zName);
73379  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
73380}
73381
73382/*
73383** The second argument is a Trigger structure allocated by the
73384** fkActionTrigger() routine. This function deletes the Trigger structure
73385** and all of its sub-components.
73386**
73387** The Trigger structure or any of its sub-components may be allocated from
73388** the lookaside buffer belonging to database handle dbMem.
73389*/
73390static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
73391  if( p ){
73392    TriggerStep *pStep = p->step_list;
73393    sqlite3ExprDelete(dbMem, pStep->pWhere);
73394    sqlite3ExprListDelete(dbMem, pStep->pExprList);
73395    sqlite3SelectDelete(dbMem, pStep->pSelect);
73396    sqlite3ExprDelete(dbMem, p->pWhen);
73397    sqlite3DbFree(dbMem, p);
73398  }
73399}
73400
73401/*
73402** This function is called to generate code that runs when table pTab is
73403** being dropped from the database. The SrcList passed as the second argument
73404** to this function contains a single entry guaranteed to resolve to
73405** table pTab.
73406**
73407** Normally, no code is required. However, if either
73408**
73409**   (a) The table is the parent table of a FK constraint, or
73410**   (b) The table is the child table of a deferred FK constraint and it is
73411**       determined at runtime that there are outstanding deferred FK
73412**       constraint violations in the database,
73413**
73414** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
73415** the table from the database. Triggers are disabled while running this
73416** DELETE, but foreign key actions are not.
73417*/
73418SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
73419  sqlite3 *db = pParse->db;
73420  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
73421    int iSkip = 0;
73422    Vdbe *v = sqlite3GetVdbe(pParse);
73423
73424    assert( v );                  /* VDBE has already been allocated */
73425    if( sqlite3FkReferences(pTab)==0 ){
73426      /* Search for a deferred foreign key constraint for which this table
73427      ** is the child table. If one cannot be found, return without
73428      ** generating any VDBE code. If one can be found, then jump over
73429      ** the entire DELETE if there are no outstanding deferred constraints
73430      ** when this statement is run.  */
73431      FKey *p;
73432      for(p=pTab->pFKey; p; p=p->pNextFrom){
73433        if( p->isDeferred ) break;
73434      }
73435      if( !p ) return;
73436      iSkip = sqlite3VdbeMakeLabel(v);
73437      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
73438    }
73439
73440    pParse->disableTriggers = 1;
73441    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
73442    pParse->disableTriggers = 0;
73443
73444    /* If the DELETE has generated immediate foreign key constraint
73445    ** violations, halt the VDBE and return an error at this point, before
73446    ** any modifications to the schema are made. This is because statement
73447    ** transactions are not able to rollback schema changes.  */
73448    sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
73449    sqlite3HaltConstraint(
73450        pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
73451    );
73452
73453    if( iSkip ){
73454      sqlite3VdbeResolveLabel(v, iSkip);
73455    }
73456  }
73457}
73458
73459/*
73460** This function is called when inserting, deleting or updating a row of
73461** table pTab to generate VDBE code to perform foreign key constraint
73462** processing for the operation.
73463**
73464** For a DELETE operation, parameter regOld is passed the index of the
73465** first register in an array of (pTab->nCol+1) registers containing the
73466** rowid of the row being deleted, followed by each of the column values
73467** of the row being deleted, from left to right. Parameter regNew is passed
73468** zero in this case.
73469**
73470** For an INSERT operation, regOld is passed zero and regNew is passed the
73471** first register of an array of (pTab->nCol+1) registers containing the new
73472** row data.
73473**
73474** For an UPDATE operation, this function is called twice. Once before
73475** the original record is deleted from the table using the calling convention
73476** described for DELETE. Then again after the original record is deleted
73477** but before the new record is inserted using the INSERT convention.
73478*/
73479SQLITE_PRIVATE void sqlite3FkCheck(
73480  Parse *pParse,                  /* Parse context */
73481  Table *pTab,                    /* Row is being deleted from this table */
73482  int regOld,                     /* Previous row data is stored here */
73483  int regNew                      /* New row data is stored here */
73484){
73485  sqlite3 *db = pParse->db;       /* Database handle */
73486  Vdbe *v;                        /* VM to write code to */
73487  FKey *pFKey;                    /* Used to iterate through FKs */
73488  int iDb;                        /* Index of database containing pTab */
73489  const char *zDb;                /* Name of database containing pTab */
73490  int isIgnoreErrors = pParse->disableTriggers;
73491
73492  /* Exactly one of regOld and regNew should be non-zero. */
73493  assert( (regOld==0)!=(regNew==0) );
73494
73495  /* If foreign-keys are disabled, this function is a no-op. */
73496  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
73497
73498  v = sqlite3GetVdbe(pParse);
73499  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
73500  zDb = db->aDb[iDb].zName;
73501
73502  /* Loop through all the foreign key constraints for which pTab is the
73503  ** child table (the table that the foreign key definition is part of).  */
73504  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
73505    Table *pTo;                   /* Parent table of foreign key pFKey */
73506    Index *pIdx = 0;              /* Index on key columns in pTo */
73507    int *aiFree = 0;
73508    int *aiCol;
73509    int iCol;
73510    int i;
73511    int isIgnore = 0;
73512
73513    /* Find the parent table of this foreign key. Also find a unique index
73514    ** on the parent key columns in the parent table. If either of these
73515    ** schema items cannot be located, set an error in pParse and return
73516    ** early.  */
73517    if( pParse->disableTriggers ){
73518      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
73519    }else{
73520      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
73521    }
73522    if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
73523      if( !isIgnoreErrors || db->mallocFailed ) return;
73524      continue;
73525    }
73526    assert( pFKey->nCol==1 || (aiFree && pIdx) );
73527
73528    if( aiFree ){
73529      aiCol = aiFree;
73530    }else{
73531      iCol = pFKey->aCol[0].iFrom;
73532      aiCol = &iCol;
73533    }
73534    for(i=0; i<pFKey->nCol; i++){
73535      if( aiCol[i]==pTab->iPKey ){
73536        aiCol[i] = -1;
73537      }
73538#ifndef SQLITE_OMIT_AUTHORIZATION
73539      /* Request permission to read the parent key columns. If the
73540      ** authorization callback returns SQLITE_IGNORE, behave as if any
73541      ** values read from the parent table are NULL. */
73542      if( db->xAuth ){
73543        int rcauth;
73544        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
73545        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
73546        isIgnore = (rcauth==SQLITE_IGNORE);
73547      }
73548#endif
73549    }
73550
73551    /* Take a shared-cache advisory read-lock on the parent table. Allocate
73552    ** a cursor to use to search the unique index on the parent key columns
73553    ** in the parent table.  */
73554    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
73555    pParse->nTab++;
73556
73557    if( regOld!=0 ){
73558      /* A row is being removed from the child table. Search for the parent.
73559      ** If the parent does not exist, removing the child row resolves an
73560      ** outstanding foreign key constraint violation. */
73561      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
73562    }
73563    if( regNew!=0 ){
73564      /* A row is being added to the child table. If a parent row cannot
73565      ** be found, adding the child row has violated the FK constraint. */
73566      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
73567    }
73568
73569    sqlite3DbFree(db, aiFree);
73570  }
73571
73572  /* Loop through all the foreign key constraints that refer to this table */
73573  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
73574    Index *pIdx = 0;              /* Foreign key index for pFKey */
73575    SrcList *pSrc;
73576    int *aiCol = 0;
73577
73578    if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
73579      assert( regOld==0 && regNew!=0 );
73580      /* Inserting a single row into a parent table cannot cause an immediate
73581      ** foreign key violation. So do nothing in this case.  */
73582      continue;
73583    }
73584
73585    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
73586      if( !isIgnoreErrors || db->mallocFailed ) return;
73587      continue;
73588    }
73589    assert( aiCol || pFKey->nCol==1 );
73590
73591    /* Create a SrcList structure containing a single table (the table
73592    ** the foreign key that refers to this table is attached to). This
73593    ** is required for the sqlite3WhereXXX() interface.  */
73594    pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
73595    if( pSrc ){
73596      struct SrcList_item *pItem = pSrc->a;
73597      pItem->pTab = pFKey->pFrom;
73598      pItem->zName = pFKey->pFrom->zName;
73599      pItem->pTab->nRef++;
73600      pItem->iCursor = pParse->nTab++;
73601
73602      if( regNew!=0 ){
73603        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
73604      }
73605      if( regOld!=0 ){
73606        /* If there is a RESTRICT action configured for the current operation
73607        ** on the parent table of this FK, then throw an exception
73608        ** immediately if the FK constraint is violated, even if this is a
73609        ** deferred trigger. That's what RESTRICT means. To defer checking
73610        ** the constraint, the FK should specify NO ACTION (represented
73611        ** using OE_None). NO ACTION is the default.  */
73612        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
73613      }
73614      pItem->zName = 0;
73615      sqlite3SrcListDelete(db, pSrc);
73616    }
73617    sqlite3DbFree(db, aiCol);
73618  }
73619}
73620
73621#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
73622
73623/*
73624** This function is called before generating code to update or delete a
73625** row contained in table pTab.
73626*/
73627SQLITE_PRIVATE u32 sqlite3FkOldmask(
73628  Parse *pParse,                  /* Parse context */
73629  Table *pTab                     /* Table being modified */
73630){
73631  u32 mask = 0;
73632  if( pParse->db->flags&SQLITE_ForeignKeys ){
73633    FKey *p;
73634    int i;
73635    for(p=pTab->pFKey; p; p=p->pNextFrom){
73636      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
73637    }
73638    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
73639      Index *pIdx = 0;
73640      locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
73641      if( pIdx ){
73642        for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
73643      }
73644    }
73645  }
73646  return mask;
73647}
73648
73649/*
73650** This function is called before generating code to update or delete a
73651** row contained in table pTab. If the operation is a DELETE, then
73652** parameter aChange is passed a NULL value. For an UPDATE, aChange points
73653** to an array of size N, where N is the number of columns in table pTab.
73654** If the i'th column is not modified by the UPDATE, then the corresponding
73655** entry in the aChange[] array is set to -1. If the column is modified,
73656** the value is 0 or greater. Parameter chngRowid is set to true if the
73657** UPDATE statement modifies the rowid fields of the table.
73658**
73659** If any foreign key processing will be required, this function returns
73660** true. If there is no foreign key related processing, this function
73661** returns false.
73662*/
73663SQLITE_PRIVATE int sqlite3FkRequired(
73664  Parse *pParse,                  /* Parse context */
73665  Table *pTab,                    /* Table being modified */
73666  int *aChange,                   /* Non-NULL for UPDATE operations */
73667  int chngRowid                   /* True for UPDATE that affects rowid */
73668){
73669  if( pParse->db->flags&SQLITE_ForeignKeys ){
73670    if( !aChange ){
73671      /* A DELETE operation. Foreign key processing is required if the
73672      ** table in question is either the child or parent table for any
73673      ** foreign key constraint.  */
73674      return (sqlite3FkReferences(pTab) || pTab->pFKey);
73675    }else{
73676      /* This is an UPDATE. Foreign key processing is only required if the
73677      ** operation modifies one or more child or parent key columns. */
73678      int i;
73679      FKey *p;
73680
73681      /* Check if any child key columns are being modified. */
73682      for(p=pTab->pFKey; p; p=p->pNextFrom){
73683        for(i=0; i<p->nCol; i++){
73684          int iChildKey = p->aCol[i].iFrom;
73685          if( aChange[iChildKey]>=0 ) return 1;
73686          if( iChildKey==pTab->iPKey && chngRowid ) return 1;
73687        }
73688      }
73689
73690      /* Check if any parent key columns are being modified. */
73691      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
73692        for(i=0; i<p->nCol; i++){
73693          char *zKey = p->aCol[i].zCol;
73694          int iKey;
73695          for(iKey=0; iKey<pTab->nCol; iKey++){
73696            Column *pCol = &pTab->aCol[iKey];
73697            if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
73698              if( aChange[iKey]>=0 ) return 1;
73699              if( iKey==pTab->iPKey && chngRowid ) return 1;
73700            }
73701          }
73702        }
73703      }
73704    }
73705  }
73706  return 0;
73707}
73708
73709/*
73710** This function is called when an UPDATE or DELETE operation is being
73711** compiled on table pTab, which is the parent table of foreign-key pFKey.
73712** If the current operation is an UPDATE, then the pChanges parameter is
73713** passed a pointer to the list of columns being modified. If it is a
73714** DELETE, pChanges is passed a NULL pointer.
73715**
73716** It returns a pointer to a Trigger structure containing a trigger
73717** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
73718** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
73719** returned (these actions require no special handling by the triggers
73720** sub-system, code for them is created by fkScanChildren()).
73721**
73722** For example, if pFKey is the foreign key and pTab is table "p" in
73723** the following schema:
73724**
73725**   CREATE TABLE p(pk PRIMARY KEY);
73726**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
73727**
73728** then the returned trigger structure is equivalent to:
73729**
73730**   CREATE TRIGGER ... DELETE ON p BEGIN
73731**     DELETE FROM c WHERE ck = old.pk;
73732**   END;
73733**
73734** The returned pointer is cached as part of the foreign key object. It
73735** is eventually freed along with the rest of the foreign key object by
73736** sqlite3FkDelete().
73737*/
73738static Trigger *fkActionTrigger(
73739  Parse *pParse,                  /* Parse context */
73740  Table *pTab,                    /* Table being updated or deleted from */
73741  FKey *pFKey,                    /* Foreign key to get action for */
73742  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
73743){
73744  sqlite3 *db = pParse->db;       /* Database handle */
73745  int action;                     /* One of OE_None, OE_Cascade etc. */
73746  Trigger *pTrigger;              /* Trigger definition to return */
73747  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
73748
73749  action = pFKey->aAction[iAction];
73750  pTrigger = pFKey->apTrigger[iAction];
73751
73752  if( action!=OE_None && !pTrigger ){
73753    u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
73754    char const *zFrom;            /* Name of child table */
73755    int nFrom;                    /* Length in bytes of zFrom */
73756    Index *pIdx = 0;              /* Parent key index for this FK */
73757    int *aiCol = 0;               /* child table cols -> parent key cols */
73758    TriggerStep *pStep = 0;        /* First (only) step of trigger program */
73759    Expr *pWhere = 0;             /* WHERE clause of trigger step */
73760    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
73761    Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
73762    int i;                        /* Iterator variable */
73763    Expr *pWhen = 0;              /* WHEN clause for the trigger */
73764
73765    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
73766    assert( aiCol || pFKey->nCol==1 );
73767
73768    for(i=0; i<pFKey->nCol; i++){
73769      Token tOld = { "old", 3 };  /* Literal "old" token */
73770      Token tNew = { "new", 3 };  /* Literal "new" token */
73771      Token tFromCol;             /* Name of column in child table */
73772      Token tToCol;               /* Name of column in parent table */
73773      int iFromCol;               /* Idx of column in child table */
73774      Expr *pEq;                  /* tFromCol = OLD.tToCol */
73775
73776      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
73777      assert( iFromCol>=0 );
73778      tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
73779      tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
73780
73781      tToCol.n = sqlite3Strlen30(tToCol.z);
73782      tFromCol.n = sqlite3Strlen30(tFromCol.z);
73783
73784      /* Create the expression "OLD.zToCol = zFromCol". It is important
73785      ** that the "OLD.zToCol" term is on the LHS of the = operator, so
73786      ** that the affinity and collation sequence associated with the
73787      ** parent table are used for the comparison. */
73788      pEq = sqlite3PExpr(pParse, TK_EQ,
73789          sqlite3PExpr(pParse, TK_DOT,
73790            sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
73791            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
73792          , 0),
73793          sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
73794      , 0);
73795      pWhere = sqlite3ExprAnd(db, pWhere, pEq);
73796
73797      /* For ON UPDATE, construct the next term of the WHEN clause.
73798      ** The final WHEN clause will be like this:
73799      **
73800      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
73801      */
73802      if( pChanges ){
73803        pEq = sqlite3PExpr(pParse, TK_IS,
73804            sqlite3PExpr(pParse, TK_DOT,
73805              sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
73806              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
73807              0),
73808            sqlite3PExpr(pParse, TK_DOT,
73809              sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
73810              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
73811              0),
73812            0);
73813        pWhen = sqlite3ExprAnd(db, pWhen, pEq);
73814      }
73815
73816      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
73817        Expr *pNew;
73818        if( action==OE_Cascade ){
73819          pNew = sqlite3PExpr(pParse, TK_DOT,
73820            sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
73821            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
73822          , 0);
73823        }else if( action==OE_SetDflt ){
73824          Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
73825          if( pDflt ){
73826            pNew = sqlite3ExprDup(db, pDflt, 0);
73827          }else{
73828            pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
73829          }
73830        }else{
73831          pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
73832        }
73833        pList = sqlite3ExprListAppend(pParse, pList, pNew);
73834        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
73835      }
73836    }
73837    sqlite3DbFree(db, aiCol);
73838
73839    zFrom = pFKey->pFrom->zName;
73840    nFrom = sqlite3Strlen30(zFrom);
73841
73842    if( action==OE_Restrict ){
73843      Token tFrom;
73844      Expr *pRaise;
73845
73846      tFrom.z = zFrom;
73847      tFrom.n = nFrom;
73848      pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
73849      if( pRaise ){
73850        pRaise->affinity = OE_Abort;
73851      }
73852      pSelect = sqlite3SelectNew(pParse,
73853          sqlite3ExprListAppend(pParse, 0, pRaise),
73854          sqlite3SrcListAppend(db, 0, &tFrom, 0),
73855          pWhere,
73856          0, 0, 0, 0, 0, 0
73857      );
73858      pWhere = 0;
73859    }
73860
73861    /* In the current implementation, pTab->dbMem==0 for all tables except
73862    ** for temporary tables used to describe subqueries.  And temporary
73863    ** tables do not have foreign key constraints.  Hence, pTab->dbMem
73864    ** should always be 0 there.
73865    */
73866    enableLookaside = db->lookaside.bEnabled;
73867    db->lookaside.bEnabled = 0;
73868
73869    pTrigger = (Trigger *)sqlite3DbMallocZero(db,
73870        sizeof(Trigger) +         /* struct Trigger */
73871        sizeof(TriggerStep) +     /* Single step in trigger program */
73872        nFrom + 1                 /* Space for pStep->target.z */
73873    );
73874    if( pTrigger ){
73875      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
73876      pStep->target.z = (char *)&pStep[1];
73877      pStep->target.n = nFrom;
73878      memcpy((char *)pStep->target.z, zFrom, nFrom);
73879
73880      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
73881      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
73882      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
73883      if( pWhen ){
73884        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
73885        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
73886      }
73887    }
73888
73889    /* Re-enable the lookaside buffer, if it was disabled earlier. */
73890    db->lookaside.bEnabled = enableLookaside;
73891
73892    sqlite3ExprDelete(db, pWhere);
73893    sqlite3ExprDelete(db, pWhen);
73894    sqlite3ExprListDelete(db, pList);
73895    sqlite3SelectDelete(db, pSelect);
73896    if( db->mallocFailed==1 ){
73897      fkTriggerDelete(db, pTrigger);
73898      return 0;
73899    }
73900
73901    switch( action ){
73902      case OE_Restrict:
73903        pStep->op = TK_SELECT;
73904        break;
73905      case OE_Cascade:
73906        if( !pChanges ){
73907          pStep->op = TK_DELETE;
73908          break;
73909        }
73910      default:
73911        pStep->op = TK_UPDATE;
73912    }
73913    pStep->pTrig = pTrigger;
73914    pTrigger->pSchema = pTab->pSchema;
73915    pTrigger->pTabSchema = pTab->pSchema;
73916    pFKey->apTrigger[iAction] = pTrigger;
73917    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
73918  }
73919
73920  return pTrigger;
73921}
73922
73923/*
73924** This function is called when deleting or updating a row to implement
73925** any required CASCADE, SET NULL or SET DEFAULT actions.
73926*/
73927SQLITE_PRIVATE void sqlite3FkActions(
73928  Parse *pParse,                  /* Parse context */
73929  Table *pTab,                    /* Table being updated or deleted from */
73930  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
73931  int regOld                      /* Address of array containing old row */
73932){
73933  /* If foreign-key support is enabled, iterate through all FKs that
73934  ** refer to table pTab. If there is an action associated with the FK
73935  ** for this operation (either update or delete), invoke the associated
73936  ** trigger sub-program.  */
73937  if( pParse->db->flags&SQLITE_ForeignKeys ){
73938    FKey *pFKey;                  /* Iterator variable */
73939    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
73940      Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
73941      if( pAction ){
73942        sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
73943      }
73944    }
73945  }
73946}
73947
73948#endif /* ifndef SQLITE_OMIT_TRIGGER */
73949
73950/*
73951** Free all memory associated with foreign key definitions attached to
73952** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
73953** hash table.
73954*/
73955SQLITE_PRIVATE void sqlite3FkDelete(Table *pTab){
73956  FKey *pFKey;                    /* Iterator variable */
73957  FKey *pNext;                    /* Copy of pFKey->pNextFrom */
73958
73959  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
73960
73961    /* Remove the FK from the fkeyHash hash table. */
73962    if( pFKey->pPrevTo ){
73963      pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
73964    }else{
73965      void *data = (void *)pFKey->pNextTo;
73966      const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo);
73967      sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data);
73968    }
73969    if( pFKey->pNextTo ){
73970      pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
73971    }
73972
73973    /* Delete any triggers created to implement actions for this FK. */
73974#ifndef SQLITE_OMIT_TRIGGER
73975    fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[0]);
73976    fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[1]);
73977#endif
73978
73979    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
73980    ** classified as either immediate or deferred.
73981    */
73982    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
73983
73984    pNext = pFKey->pNextFrom;
73985    sqlite3DbFree(pTab->dbMem, pFKey);
73986  }
73987}
73988#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
73989
73990/************** End of fkey.c ************************************************/
73991/************** Begin file insert.c ******************************************/
73992/*
73993** 2001 September 15
73994**
73995** The author disclaims copyright to this source code.  In place of
73996** a legal notice, here is a blessing:
73997**
73998**    May you do good and not evil.
73999**    May you find forgiveness for yourself and forgive others.
74000**    May you share freely, never taking more than you give.
74001**
74002*************************************************************************
74003** This file contains C code routines that are called by the parser
74004** to handle INSERT statements in SQLite.
74005*/
74006
74007/*
74008** Generate code that will open a table for reading.
74009*/
74010SQLITE_PRIVATE void sqlite3OpenTable(
74011  Parse *p,       /* Generate code into this VDBE */
74012  int iCur,       /* The cursor number of the table */
74013  int iDb,        /* The database index in sqlite3.aDb[] */
74014  Table *pTab,    /* The table to be opened */
74015  int opcode      /* OP_OpenRead or OP_OpenWrite */
74016){
74017  Vdbe *v;
74018  if( IsVirtual(pTab) ) return;
74019  v = sqlite3GetVdbe(p);
74020  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
74021  sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
74022  sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
74023  sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
74024  VdbeComment((v, "%s", pTab->zName));
74025}
74026
74027/*
74028** Return a pointer to the column affinity string associated with index
74029** pIdx. A column affinity string has one character for each column in
74030** the table, according to the affinity of the column:
74031**
74032**  Character      Column affinity
74033**  ------------------------------
74034**  'a'            TEXT
74035**  'b'            NONE
74036**  'c'            NUMERIC
74037**  'd'            INTEGER
74038**  'e'            REAL
74039**
74040** An extra 'b' is appended to the end of the string to cover the
74041** rowid that appears as the last column in every index.
74042**
74043** Memory for the buffer containing the column index affinity string
74044** is managed along with the rest of the Index structure. It will be
74045** released when sqlite3DeleteIndex() is called.
74046*/
74047SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
74048  if( !pIdx->zColAff ){
74049    /* The first time a column affinity string for a particular index is
74050    ** required, it is allocated and populated here. It is then stored as
74051    ** a member of the Index structure for subsequent use.
74052    **
74053    ** The column affinity string will eventually be deleted by
74054    ** sqliteDeleteIndex() when the Index structure itself is cleaned
74055    ** up.
74056    */
74057    int n;
74058    Table *pTab = pIdx->pTable;
74059    sqlite3 *db = sqlite3VdbeDb(v);
74060    pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
74061    if( !pIdx->zColAff ){
74062      db->mallocFailed = 1;
74063      return 0;
74064    }
74065    for(n=0; n<pIdx->nColumn; n++){
74066      pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
74067    }
74068    pIdx->zColAff[n++] = SQLITE_AFF_NONE;
74069    pIdx->zColAff[n] = 0;
74070  }
74071
74072  return pIdx->zColAff;
74073}
74074
74075/*
74076** Set P4 of the most recently inserted opcode to a column affinity
74077** string for table pTab. A column affinity string has one character
74078** for each column indexed by the index, according to the affinity of the
74079** column:
74080**
74081**  Character      Column affinity
74082**  ------------------------------
74083**  'a'            TEXT
74084**  'b'            NONE
74085**  'c'            NUMERIC
74086**  'd'            INTEGER
74087**  'e'            REAL
74088*/
74089SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
74090  /* The first time a column affinity string for a particular table
74091  ** is required, it is allocated and populated here. It is then
74092  ** stored as a member of the Table structure for subsequent use.
74093  **
74094  ** The column affinity string will eventually be deleted by
74095  ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
74096  */
74097  if( !pTab->zColAff ){
74098    char *zColAff;
74099    int i;
74100    sqlite3 *db = sqlite3VdbeDb(v);
74101
74102    zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
74103    if( !zColAff ){
74104      db->mallocFailed = 1;
74105      return;
74106    }
74107
74108    for(i=0; i<pTab->nCol; i++){
74109      zColAff[i] = pTab->aCol[i].affinity;
74110    }
74111    zColAff[pTab->nCol] = '\0';
74112
74113    pTab->zColAff = zColAff;
74114  }
74115
74116  sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
74117}
74118
74119/*
74120** Return non-zero if the table pTab in database iDb or any of its indices
74121** have been opened at any point in the VDBE program beginning at location
74122** iStartAddr throught the end of the program.  This is used to see if
74123** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
74124** run without using temporary table for the results of the SELECT.
74125*/
74126static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
74127  Vdbe *v = sqlite3GetVdbe(p);
74128  int i;
74129  int iEnd = sqlite3VdbeCurrentAddr(v);
74130#ifndef SQLITE_OMIT_VIRTUALTABLE
74131  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
74132#endif
74133
74134  for(i=iStartAddr; i<iEnd; i++){
74135    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
74136    assert( pOp!=0 );
74137    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
74138      Index *pIndex;
74139      int tnum = pOp->p2;
74140      if( tnum==pTab->tnum ){
74141        return 1;
74142      }
74143      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
74144        if( tnum==pIndex->tnum ){
74145          return 1;
74146        }
74147      }
74148    }
74149#ifndef SQLITE_OMIT_VIRTUALTABLE
74150    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
74151      assert( pOp->p4.pVtab!=0 );
74152      assert( pOp->p4type==P4_VTAB );
74153      return 1;
74154    }
74155#endif
74156  }
74157  return 0;
74158}
74159
74160#ifndef SQLITE_OMIT_AUTOINCREMENT
74161/*
74162** Locate or create an AutoincInfo structure associated with table pTab
74163** which is in database iDb.  Return the register number for the register
74164** that holds the maximum rowid.
74165**
74166** There is at most one AutoincInfo structure per table even if the
74167** same table is autoincremented multiple times due to inserts within
74168** triggers.  A new AutoincInfo structure is created if this is the
74169** first use of table pTab.  On 2nd and subsequent uses, the original
74170** AutoincInfo structure is used.
74171**
74172** Three memory locations are allocated:
74173**
74174**   (1)  Register to hold the name of the pTab table.
74175**   (2)  Register to hold the maximum ROWID of pTab.
74176**   (3)  Register to hold the rowid in sqlite_sequence of pTab
74177**
74178** The 2nd register is the one that is returned.  That is all the
74179** insert routine needs to know about.
74180*/
74181static int autoIncBegin(
74182  Parse *pParse,      /* Parsing context */
74183  int iDb,            /* Index of the database holding pTab */
74184  Table *pTab         /* The table we are writing to */
74185){
74186  int memId = 0;      /* Register holding maximum rowid */
74187  if( pTab->tabFlags & TF_Autoincrement ){
74188    Parse *pToplevel = sqlite3ParseToplevel(pParse);
74189    AutoincInfo *pInfo;
74190
74191    pInfo = pToplevel->pAinc;
74192    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
74193    if( pInfo==0 ){
74194      pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
74195      if( pInfo==0 ) return 0;
74196      pInfo->pNext = pToplevel->pAinc;
74197      pToplevel->pAinc = pInfo;
74198      pInfo->pTab = pTab;
74199      pInfo->iDb = iDb;
74200      pToplevel->nMem++;                  /* Register to hold name of table */
74201      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
74202      pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
74203    }
74204    memId = pInfo->regCtr;
74205  }
74206  return memId;
74207}
74208
74209/*
74210** This routine generates code that will initialize all of the
74211** register used by the autoincrement tracker.
74212*/
74213SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
74214  AutoincInfo *p;            /* Information about an AUTOINCREMENT */
74215  sqlite3 *db = pParse->db;  /* The database connection */
74216  Db *pDb;                   /* Database only autoinc table */
74217  int memId;                 /* Register holding max rowid */
74218  int addr;                  /* A VDBE address */
74219  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
74220
74221  /* This routine is never called during trigger-generation.  It is
74222  ** only called from the top-level */
74223  assert( pParse->pTriggerTab==0 );
74224  assert( pParse==sqlite3ParseToplevel(pParse) );
74225
74226  assert( v );   /* We failed long ago if this is not so */
74227  for(p = pParse->pAinc; p; p = p->pNext){
74228    pDb = &db->aDb[p->iDb];
74229    memId = p->regCtr;
74230    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
74231    addr = sqlite3VdbeCurrentAddr(v);
74232    sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
74233    sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
74234    sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
74235    sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
74236    sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
74237    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
74238    sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
74239    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
74240    sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
74241    sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
74242    sqlite3VdbeAddOp0(v, OP_Close);
74243  }
74244}
74245
74246/*
74247** Update the maximum rowid for an autoincrement calculation.
74248**
74249** This routine should be called when the top of the stack holds a
74250** new rowid that is about to be inserted.  If that new rowid is
74251** larger than the maximum rowid in the memId memory cell, then the
74252** memory cell is updated.  The stack is unchanged.
74253*/
74254static void autoIncStep(Parse *pParse, int memId, int regRowid){
74255  if( memId>0 ){
74256    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
74257  }
74258}
74259
74260/*
74261** This routine generates the code needed to write autoincrement
74262** maximum rowid values back into the sqlite_sequence register.
74263** Every statement that might do an INSERT into an autoincrement
74264** table (either directly or through triggers) needs to call this
74265** routine just before the "exit" code.
74266*/
74267SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
74268  AutoincInfo *p;
74269  Vdbe *v = pParse->pVdbe;
74270  sqlite3 *db = pParse->db;
74271
74272  assert( v );
74273  for(p = pParse->pAinc; p; p = p->pNext){
74274    Db *pDb = &db->aDb[p->iDb];
74275    int j1, j2, j3, j4, j5;
74276    int iRec;
74277    int memId = p->regCtr;
74278
74279    iRec = sqlite3GetTempReg(pParse);
74280    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
74281    j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
74282    j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
74283    j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
74284    j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
74285    sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
74286    sqlite3VdbeJumpHere(v, j2);
74287    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
74288    j5 = sqlite3VdbeAddOp0(v, OP_Goto);
74289    sqlite3VdbeJumpHere(v, j4);
74290    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
74291    sqlite3VdbeJumpHere(v, j1);
74292    sqlite3VdbeJumpHere(v, j5);
74293    sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
74294    sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
74295    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
74296    sqlite3VdbeAddOp0(v, OP_Close);
74297    sqlite3ReleaseTempReg(pParse, iRec);
74298  }
74299}
74300#else
74301/*
74302** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
74303** above are all no-ops
74304*/
74305# define autoIncBegin(A,B,C) (0)
74306# define autoIncStep(A,B,C)
74307#endif /* SQLITE_OMIT_AUTOINCREMENT */
74308
74309
74310/* Forward declaration */
74311static int xferOptimization(
74312  Parse *pParse,        /* Parser context */
74313  Table *pDest,         /* The table we are inserting into */
74314  Select *pSelect,      /* A SELECT statement to use as the data source */
74315  int onError,          /* How to handle constraint errors */
74316  int iDbDest           /* The database of pDest */
74317);
74318
74319/*
74320** This routine is call to handle SQL of the following forms:
74321**
74322**    insert into TABLE (IDLIST) values(EXPRLIST)
74323**    insert into TABLE (IDLIST) select
74324**
74325** The IDLIST following the table name is always optional.  If omitted,
74326** then a list of all columns for the table is substituted.  The IDLIST
74327** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
74328**
74329** The pList parameter holds EXPRLIST in the first form of the INSERT
74330** statement above, and pSelect is NULL.  For the second form, pList is
74331** NULL and pSelect is a pointer to the select statement used to generate
74332** data for the insert.
74333**
74334** The code generated follows one of four templates.  For a simple
74335** select with data coming from a VALUES clause, the code executes
74336** once straight down through.  Pseudo-code follows (we call this
74337** the "1st template"):
74338**
74339**         open write cursor to <table> and its indices
74340**         puts VALUES clause expressions onto the stack
74341**         write the resulting record into <table>
74342**         cleanup
74343**
74344** The three remaining templates assume the statement is of the form
74345**
74346**   INSERT INTO <table> SELECT ...
74347**
74348** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
74349** in other words if the SELECT pulls all columns from a single table
74350** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
74351** if <table2> and <table1> are distinct tables but have identical
74352** schemas, including all the same indices, then a special optimization
74353** is invoked that copies raw records from <table2> over to <table1>.
74354** See the xferOptimization() function for the implementation of this
74355** template.  This is the 2nd template.
74356**
74357**         open a write cursor to <table>
74358**         open read cursor on <table2>
74359**         transfer all records in <table2> over to <table>
74360**         close cursors
74361**         foreach index on <table>
74362**           open a write cursor on the <table> index
74363**           open a read cursor on the corresponding <table2> index
74364**           transfer all records from the read to the write cursors
74365**           close cursors
74366**         end foreach
74367**
74368** The 3rd template is for when the second template does not apply
74369** and the SELECT clause does not read from <table> at any time.
74370** The generated code follows this template:
74371**
74372**         EOF <- 0
74373**         X <- A
74374**         goto B
74375**      A: setup for the SELECT
74376**         loop over the rows in the SELECT
74377**           load values into registers R..R+n
74378**           yield X
74379**         end loop
74380**         cleanup after the SELECT
74381**         EOF <- 1
74382**         yield X
74383**         goto A
74384**      B: open write cursor to <table> and its indices
74385**      C: yield X
74386**         if EOF goto D
74387**         insert the select result into <table> from R..R+n
74388**         goto C
74389**      D: cleanup
74390**
74391** The 4th template is used if the insert statement takes its
74392** values from a SELECT but the data is being inserted into a table
74393** that is also read as part of the SELECT.  In the third form,
74394** we have to use a intermediate table to store the results of
74395** the select.  The template is like this:
74396**
74397**         EOF <- 0
74398**         X <- A
74399**         goto B
74400**      A: setup for the SELECT
74401**         loop over the tables in the SELECT
74402**           load value into register R..R+n
74403**           yield X
74404**         end loop
74405**         cleanup after the SELECT
74406**         EOF <- 1
74407**         yield X
74408**         halt-error
74409**      B: open temp table
74410**      L: yield X
74411**         if EOF goto M
74412**         insert row from R..R+n into temp table
74413**         goto L
74414**      M: open write cursor to <table> and its indices
74415**         rewind temp table
74416**      C: loop over rows of intermediate table
74417**           transfer values form intermediate table into <table>
74418**         end loop
74419**      D: cleanup
74420*/
74421SQLITE_PRIVATE void sqlite3Insert(
74422  Parse *pParse,        /* Parser context */
74423  SrcList *pTabList,    /* Name of table into which we are inserting */
74424  ExprList *pList,      /* List of values to be inserted */
74425  Select *pSelect,      /* A SELECT statement to use as the data source */
74426  IdList *pColumn,      /* Column names corresponding to IDLIST. */
74427  int onError           /* How to handle constraint errors */
74428){
74429  sqlite3 *db;          /* The main database structure */
74430  Table *pTab;          /* The table to insert into.  aka TABLE */
74431  char *zTab;           /* Name of the table into which we are inserting */
74432  const char *zDb;      /* Name of the database holding this table */
74433  int i, j, idx;        /* Loop counters */
74434  Vdbe *v;              /* Generate code into this virtual machine */
74435  Index *pIdx;          /* For looping over indices of the table */
74436  int nColumn;          /* Number of columns in the data */
74437  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
74438  int baseCur = 0;      /* VDBE Cursor number for pTab */
74439  int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
74440  int endOfLoop;        /* Label for the end of the insertion loop */
74441  int useTempTable = 0; /* Store SELECT results in intermediate table */
74442  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
74443  int addrInsTop = 0;   /* Jump to label "D" */
74444  int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
74445  int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
74446  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
74447  int iDb;              /* Index of database holding TABLE */
74448  Db *pDb;              /* The database containing table being inserted into */
74449  int appendFlag = 0;   /* True if the insert is likely to be an append */
74450
74451  /* Register allocations */
74452  int regFromSelect = 0;/* Base register for data coming from SELECT */
74453  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
74454  int regRowCount = 0;  /* Memory cell used for the row counter */
74455  int regIns;           /* Block of regs holding rowid+data being inserted */
74456  int regRowid;         /* registers holding insert rowid */
74457  int regData;          /* register holding first column to insert */
74458  int regRecord;        /* Holds the assemblied row record */
74459  int regEof = 0;       /* Register recording end of SELECT data */
74460  int *aRegIdx = 0;     /* One register allocated to each index */
74461
74462#ifndef SQLITE_OMIT_TRIGGER
74463  int isView;                 /* True if attempting to insert into a view */
74464  Trigger *pTrigger;          /* List of triggers on pTab, if required */
74465  int tmask;                  /* Mask of trigger times */
74466#endif
74467
74468  db = pParse->db;
74469  memset(&dest, 0, sizeof(dest));
74470  if( pParse->nErr || db->mallocFailed ){
74471    goto insert_cleanup;
74472  }
74473
74474  /* Locate the table into which we will be inserting new information.
74475  */
74476  assert( pTabList->nSrc==1 );
74477  zTab = pTabList->a[0].zName;
74478  if( NEVER(zTab==0) ) goto insert_cleanup;
74479  pTab = sqlite3SrcListLookup(pParse, pTabList);
74480  if( pTab==0 ){
74481    goto insert_cleanup;
74482  }
74483  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
74484  assert( iDb<db->nDb );
74485  pDb = &db->aDb[iDb];
74486  zDb = pDb->zName;
74487  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
74488    goto insert_cleanup;
74489  }
74490
74491  /* Figure out if we have any triggers and if the table being
74492  ** inserted into is a view
74493  */
74494#ifndef SQLITE_OMIT_TRIGGER
74495  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
74496  isView = pTab->pSelect!=0;
74497#else
74498# define pTrigger 0
74499# define tmask 0
74500# define isView 0
74501#endif
74502#ifdef SQLITE_OMIT_VIEW
74503# undef isView
74504# define isView 0
74505#endif
74506  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
74507
74508  /* If pTab is really a view, make sure it has been initialized.
74509  ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
74510  ** module table).
74511  */
74512  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
74513    goto insert_cleanup;
74514  }
74515
74516  /* Ensure that:
74517  *  (a) the table is not read-only,
74518  *  (b) that if it is a view then ON INSERT triggers exist
74519  */
74520  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
74521    goto insert_cleanup;
74522  }
74523
74524  /* Allocate a VDBE
74525  */
74526  v = sqlite3GetVdbe(pParse);
74527  if( v==0 ) goto insert_cleanup;
74528  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
74529  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
74530
74531#ifndef SQLITE_OMIT_XFER_OPT
74532  /* If the statement is of the form
74533  **
74534  **       INSERT INTO <table1> SELECT * FROM <table2>;
74535  **
74536  ** Then special optimizations can be applied that make the transfer
74537  ** very fast and which reduce fragmentation of indices.
74538  **
74539  ** This is the 2nd template.
74540  */
74541  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
74542    assert( !pTrigger );
74543    assert( pList==0 );
74544    goto insert_end;
74545  }
74546#endif /* SQLITE_OMIT_XFER_OPT */
74547
74548  /* If this is an AUTOINCREMENT table, look up the sequence number in the
74549  ** sqlite_sequence table and store it in memory cell regAutoinc.
74550  */
74551  regAutoinc = autoIncBegin(pParse, iDb, pTab);
74552
74553  /* Figure out how many columns of data are supplied.  If the data
74554  ** is coming from a SELECT statement, then generate a co-routine that
74555  ** produces a single row of the SELECT on each invocation.  The
74556  ** co-routine is the common header to the 3rd and 4th templates.
74557  */
74558  if( pSelect ){
74559    /* Data is coming from a SELECT.  Generate code to implement that SELECT
74560    ** as a co-routine.  The code is common to both the 3rd and 4th
74561    ** templates:
74562    **
74563    **         EOF <- 0
74564    **         X <- A
74565    **         goto B
74566    **      A: setup for the SELECT
74567    **         loop over the tables in the SELECT
74568    **           load value into register R..R+n
74569    **           yield X
74570    **         end loop
74571    **         cleanup after the SELECT
74572    **         EOF <- 1
74573    **         yield X
74574    **         halt-error
74575    **
74576    ** On each invocation of the co-routine, it puts a single row of the
74577    ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
74578    ** (These output registers are allocated by sqlite3Select().)  When
74579    ** the SELECT completes, it sets the EOF flag stored in regEof.
74580    */
74581    int rc, j1;
74582
74583    regEof = ++pParse->nMem;
74584    sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
74585    VdbeComment((v, "SELECT eof flag"));
74586    sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
74587    addrSelect = sqlite3VdbeCurrentAddr(v)+2;
74588    sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
74589    j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
74590    VdbeComment((v, "Jump over SELECT coroutine"));
74591
74592    /* Resolve the expressions in the SELECT statement and execute it. */
74593    rc = sqlite3Select(pParse, pSelect, &dest);
74594    assert( pParse->nErr==0 || rc );
74595    if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
74596      goto insert_cleanup;
74597    }
74598    sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
74599    sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
74600    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
74601    VdbeComment((v, "End of SELECT coroutine"));
74602    sqlite3VdbeJumpHere(v, j1);                          /* label B: */
74603
74604    regFromSelect = dest.iMem;
74605    assert( pSelect->pEList );
74606    nColumn = pSelect->pEList->nExpr;
74607    assert( dest.nMem==nColumn );
74608
74609    /* Set useTempTable to TRUE if the result of the SELECT statement
74610    ** should be written into a temporary table (template 4).  Set to
74611    ** FALSE if each* row of the SELECT can be written directly into
74612    ** the destination table (template 3).
74613    **
74614    ** A temp table must be used if the table being updated is also one
74615    ** of the tables being read by the SELECT statement.  Also use a
74616    ** temp table in the case of row triggers.
74617    */
74618    if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
74619      useTempTable = 1;
74620    }
74621
74622    if( useTempTable ){
74623      /* Invoke the coroutine to extract information from the SELECT
74624      ** and add it to a transient table srcTab.  The code generated
74625      ** here is from the 4th template:
74626      **
74627      **      B: open temp table
74628      **      L: yield X
74629      **         if EOF goto M
74630      **         insert row from R..R+n into temp table
74631      **         goto L
74632      **      M: ...
74633      */
74634      int regRec;          /* Register to hold packed record */
74635      int regTempRowid;    /* Register to hold temp table ROWID */
74636      int addrTop;         /* Label "L" */
74637      int addrIf;          /* Address of jump to M */
74638
74639      srcTab = pParse->nTab++;
74640      regRec = sqlite3GetTempReg(pParse);
74641      regTempRowid = sqlite3GetTempReg(pParse);
74642      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
74643      addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
74644      addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
74645      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
74646      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
74647      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
74648      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
74649      sqlite3VdbeJumpHere(v, addrIf);
74650      sqlite3ReleaseTempReg(pParse, regRec);
74651      sqlite3ReleaseTempReg(pParse, regTempRowid);
74652    }
74653  }else{
74654    /* This is the case if the data for the INSERT is coming from a VALUES
74655    ** clause
74656    */
74657    NameContext sNC;
74658    memset(&sNC, 0, sizeof(sNC));
74659    sNC.pParse = pParse;
74660    srcTab = -1;
74661    assert( useTempTable==0 );
74662    nColumn = pList ? pList->nExpr : 0;
74663    for(i=0; i<nColumn; i++){
74664      if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
74665        goto insert_cleanup;
74666      }
74667    }
74668  }
74669
74670  /* Make sure the number of columns in the source data matches the number
74671  ** of columns to be inserted into the table.
74672  */
74673  if( IsVirtual(pTab) ){
74674    for(i=0; i<pTab->nCol; i++){
74675      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
74676    }
74677  }
74678  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
74679    sqlite3ErrorMsg(pParse,
74680       "table %S has %d columns but %d values were supplied",
74681       pTabList, 0, pTab->nCol-nHidden, nColumn);
74682    goto insert_cleanup;
74683  }
74684  if( pColumn!=0 && nColumn!=pColumn->nId ){
74685    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
74686    goto insert_cleanup;
74687  }
74688
74689  /* If the INSERT statement included an IDLIST term, then make sure
74690  ** all elements of the IDLIST really are columns of the table and
74691  ** remember the column indices.
74692  **
74693  ** If the table has an INTEGER PRIMARY KEY column and that column
74694  ** is named in the IDLIST, then record in the keyColumn variable
74695  ** the index into IDLIST of the primary key column.  keyColumn is
74696  ** the index of the primary key as it appears in IDLIST, not as
74697  ** is appears in the original table.  (The index of the primary
74698  ** key in the original table is pTab->iPKey.)
74699  */
74700  if( pColumn ){
74701    for(i=0; i<pColumn->nId; i++){
74702      pColumn->a[i].idx = -1;
74703    }
74704    for(i=0; i<pColumn->nId; i++){
74705      for(j=0; j<pTab->nCol; j++){
74706        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
74707          pColumn->a[i].idx = j;
74708          if( j==pTab->iPKey ){
74709            keyColumn = i;
74710          }
74711          break;
74712        }
74713      }
74714      if( j>=pTab->nCol ){
74715        if( sqlite3IsRowid(pColumn->a[i].zName) ){
74716          keyColumn = i;
74717        }else{
74718          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
74719              pTabList, 0, pColumn->a[i].zName);
74720          pParse->nErr++;
74721          goto insert_cleanup;
74722        }
74723      }
74724    }
74725  }
74726
74727  /* If there is no IDLIST term but the table has an integer primary
74728  ** key, the set the keyColumn variable to the primary key column index
74729  ** in the original table definition.
74730  */
74731  if( pColumn==0 && nColumn>0 ){
74732    keyColumn = pTab->iPKey;
74733  }
74734
74735  /* Initialize the count of rows to be inserted
74736  */
74737  if( db->flags & SQLITE_CountRows ){
74738    regRowCount = ++pParse->nMem;
74739    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
74740  }
74741
74742  /* If this is not a view, open the table and and all indices */
74743  if( !isView ){
74744    int nIdx;
74745
74746    baseCur = pParse->nTab;
74747    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
74748    aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
74749    if( aRegIdx==0 ){
74750      goto insert_cleanup;
74751    }
74752    for(i=0; i<nIdx; i++){
74753      aRegIdx[i] = ++pParse->nMem;
74754    }
74755  }
74756
74757  /* This is the top of the main insertion loop */
74758  if( useTempTable ){
74759    /* This block codes the top of loop only.  The complete loop is the
74760    ** following pseudocode (template 4):
74761    **
74762    **         rewind temp table
74763    **      C: loop over rows of intermediate table
74764    **           transfer values form intermediate table into <table>
74765    **         end loop
74766    **      D: ...
74767    */
74768    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
74769    addrCont = sqlite3VdbeCurrentAddr(v);
74770  }else if( pSelect ){
74771    /* This block codes the top of loop only.  The complete loop is the
74772    ** following pseudocode (template 3):
74773    **
74774    **      C: yield X
74775    **         if EOF goto D
74776    **         insert the select result into <table> from R..R+n
74777    **         goto C
74778    **      D: ...
74779    */
74780    addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
74781    addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
74782  }
74783
74784  /* Allocate registers for holding the rowid of the new row,
74785  ** the content of the new row, and the assemblied row record.
74786  */
74787  regRecord = ++pParse->nMem;
74788  regRowid = regIns = pParse->nMem+1;
74789  pParse->nMem += pTab->nCol + 1;
74790  if( IsVirtual(pTab) ){
74791    regRowid++;
74792    pParse->nMem++;
74793  }
74794  regData = regRowid+1;
74795
74796  /* Run the BEFORE and INSTEAD OF triggers, if there are any
74797  */
74798  endOfLoop = sqlite3VdbeMakeLabel(v);
74799  if( tmask & TRIGGER_BEFORE ){
74800    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
74801
74802    /* build the NEW.* reference row.  Note that if there is an INTEGER
74803    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
74804    ** translated into a unique ID for the row.  But on a BEFORE trigger,
74805    ** we do not know what the unique ID will be (because the insert has
74806    ** not happened yet) so we substitute a rowid of -1
74807    */
74808    if( keyColumn<0 ){
74809      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
74810    }else{
74811      int j1;
74812      if( useTempTable ){
74813        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
74814      }else{
74815        assert( pSelect==0 );  /* Otherwise useTempTable is true */
74816        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
74817      }
74818      j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
74819      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
74820      sqlite3VdbeJumpHere(v, j1);
74821      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
74822    }
74823
74824    /* Cannot have triggers on a virtual table. If it were possible,
74825    ** this block would have to account for hidden column.
74826    */
74827    assert( !IsVirtual(pTab) );
74828
74829    /* Create the new column data
74830    */
74831    for(i=0; i<pTab->nCol; i++){
74832      if( pColumn==0 ){
74833        j = i;
74834      }else{
74835        for(j=0; j<pColumn->nId; j++){
74836          if( pColumn->a[j].idx==i ) break;
74837        }
74838      }
74839      if( pColumn && j>=pColumn->nId ){
74840        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
74841      }else if( useTempTable ){
74842        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
74843      }else{
74844        assert( pSelect==0 ); /* Otherwise useTempTable is true */
74845        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
74846      }
74847    }
74848
74849    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
74850    ** do not attempt any conversions before assembling the record.
74851    ** If this is a real table, attempt conversions as required by the
74852    ** table column affinities.
74853    */
74854    if( !isView ){
74855      sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
74856      sqlite3TableAffinityStr(v, pTab);
74857    }
74858
74859    /* Fire BEFORE or INSTEAD OF triggers */
74860    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
74861        pTab, regCols-pTab->nCol-1, onError, endOfLoop);
74862
74863    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
74864  }
74865
74866  /* Push the record number for the new entry onto the stack.  The
74867  ** record number is a randomly generate integer created by NewRowid
74868  ** except when the table has an INTEGER PRIMARY KEY column, in which
74869  ** case the record number is the same as that column.
74870  */
74871  if( !isView ){
74872    if( IsVirtual(pTab) ){
74873      /* The row that the VUpdate opcode will delete: none */
74874      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
74875    }
74876    if( keyColumn>=0 ){
74877      if( useTempTable ){
74878        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
74879      }else if( pSelect ){
74880        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
74881      }else{
74882        VdbeOp *pOp;
74883        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
74884        pOp = sqlite3VdbeGetOp(v, -1);
74885        if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
74886          appendFlag = 1;
74887          pOp->opcode = OP_NewRowid;
74888          pOp->p1 = baseCur;
74889          pOp->p2 = regRowid;
74890          pOp->p3 = regAutoinc;
74891        }
74892      }
74893      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
74894      ** to generate a unique primary key value.
74895      */
74896      if( !appendFlag ){
74897        int j1;
74898        if( !IsVirtual(pTab) ){
74899          j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
74900          sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
74901          sqlite3VdbeJumpHere(v, j1);
74902        }else{
74903          j1 = sqlite3VdbeCurrentAddr(v);
74904          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
74905        }
74906        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
74907      }
74908    }else if( IsVirtual(pTab) ){
74909      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
74910    }else{
74911      sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
74912      appendFlag = 1;
74913    }
74914    autoIncStep(pParse, regAutoinc, regRowid);
74915
74916    /* Push onto the stack, data for all columns of the new entry, beginning
74917    ** with the first column.
74918    */
74919    nHidden = 0;
74920    for(i=0; i<pTab->nCol; i++){
74921      int iRegStore = regRowid+1+i;
74922      if( i==pTab->iPKey ){
74923        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
74924        ** Whenever this column is read, the record number will be substituted
74925        ** in its place.  So will fill this column with a NULL to avoid
74926        ** taking up data space with information that will never be used. */
74927        sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
74928        continue;
74929      }
74930      if( pColumn==0 ){
74931        if( IsHiddenColumn(&pTab->aCol[i]) ){
74932          assert( IsVirtual(pTab) );
74933          j = -1;
74934          nHidden++;
74935        }else{
74936          j = i - nHidden;
74937        }
74938      }else{
74939        for(j=0; j<pColumn->nId; j++){
74940          if( pColumn->a[j].idx==i ) break;
74941        }
74942      }
74943      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
74944        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
74945      }else if( useTempTable ){
74946        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
74947      }else if( pSelect ){
74948        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
74949      }else{
74950        sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
74951      }
74952    }
74953
74954    /* Generate code to check constraints and generate index keys and
74955    ** do the insertion.
74956    */
74957#ifndef SQLITE_OMIT_VIRTUALTABLE
74958    if( IsVirtual(pTab) ){
74959      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
74960      sqlite3VtabMakeWritable(pParse, pTab);
74961      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
74962      sqlite3MayAbort(pParse);
74963    }else
74964#endif
74965    {
74966      int isReplace;    /* Set to true if constraints may cause a replace */
74967      sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
74968          keyColumn>=0, 0, onError, endOfLoop, &isReplace
74969      );
74970      sqlite3FkCheck(pParse, pTab, 0, regIns);
74971      sqlite3CompleteInsertion(
74972          pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
74973      );
74974    }
74975  }
74976
74977  /* Update the count of rows that are inserted
74978  */
74979  if( (db->flags & SQLITE_CountRows)!=0 ){
74980    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
74981  }
74982
74983  if( pTrigger ){
74984    /* Code AFTER triggers */
74985    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
74986        pTab, regData-2-pTab->nCol, onError, endOfLoop);
74987  }
74988
74989  /* The bottom of the main insertion loop, if the data source
74990  ** is a SELECT statement.
74991  */
74992  sqlite3VdbeResolveLabel(v, endOfLoop);
74993  if( useTempTable ){
74994    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
74995    sqlite3VdbeJumpHere(v, addrInsTop);
74996    sqlite3VdbeAddOp1(v, OP_Close, srcTab);
74997  }else if( pSelect ){
74998    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
74999    sqlite3VdbeJumpHere(v, addrInsTop);
75000  }
75001
75002  if( !IsVirtual(pTab) && !isView ){
75003    /* Close all tables opened */
75004    sqlite3VdbeAddOp1(v, OP_Close, baseCur);
75005    for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
75006      sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
75007    }
75008  }
75009
75010insert_end:
75011  /* Update the sqlite_sequence table by storing the content of the
75012  ** maximum rowid counter values recorded while inserting into
75013  ** autoincrement tables.
75014  */
75015  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
75016    sqlite3AutoincrementEnd(pParse);
75017  }
75018
75019  /*
75020  ** Return the number of rows inserted. If this routine is
75021  ** generating code because of a call to sqlite3NestedParse(), do not
75022  ** invoke the callback function.
75023  */
75024  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
75025    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
75026    sqlite3VdbeSetNumCols(v, 1);
75027    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
75028  }
75029
75030insert_cleanup:
75031  sqlite3SrcListDelete(db, pTabList);
75032  sqlite3ExprListDelete(db, pList);
75033  sqlite3SelectDelete(db, pSelect);
75034  sqlite3IdListDelete(db, pColumn);
75035  sqlite3DbFree(db, aRegIdx);
75036}
75037
75038/* Make sure "isView" and other macros defined above are undefined. Otherwise
75039** thely may interfere with compilation of other functions in this file
75040** (or in another file, if this file becomes part of the amalgamation).  */
75041#ifdef isView
75042 #undef isView
75043#endif
75044#ifdef pTrigger
75045 #undef pTrigger
75046#endif
75047#ifdef tmask
75048 #undef tmask
75049#endif
75050
75051
75052/*
75053** Generate code to do constraint checks prior to an INSERT or an UPDATE.
75054**
75055** The input is a range of consecutive registers as follows:
75056**
75057**    1.  The rowid of the row after the update.
75058**
75059**    2.  The data in the first column of the entry after the update.
75060**
75061**    i.  Data from middle columns...
75062**
75063**    N.  The data in the last column of the entry after the update.
75064**
75065** The regRowid parameter is the index of the register containing (1).
75066**
75067** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
75068** the address of a register containing the rowid before the update takes
75069** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
75070** is false, indicating an INSERT statement, then a non-zero rowidChng
75071** indicates that the rowid was explicitly specified as part of the
75072** INSERT statement. If rowidChng is false, it means that  the rowid is
75073** computed automatically in an insert or that the rowid value is not
75074** modified by an update.
75075**
75076** The code generated by this routine store new index entries into
75077** registers identified by aRegIdx[].  No index entry is created for
75078** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
75079** the same as the order of indices on the linked list of indices
75080** attached to the table.
75081**
75082** This routine also generates code to check constraints.  NOT NULL,
75083** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
75084** then the appropriate action is performed.  There are five possible
75085** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
75086**
75087**  Constraint type  Action       What Happens
75088**  ---------------  ----------   ----------------------------------------
75089**  any              ROLLBACK     The current transaction is rolled back and
75090**                                sqlite3_exec() returns immediately with a
75091**                                return code of SQLITE_CONSTRAINT.
75092**
75093**  any              ABORT        Back out changes from the current command
75094**                                only (do not do a complete rollback) then
75095**                                cause sqlite3_exec() to return immediately
75096**                                with SQLITE_CONSTRAINT.
75097**
75098**  any              FAIL         Sqlite_exec() returns immediately with a
75099**                                return code of SQLITE_CONSTRAINT.  The
75100**                                transaction is not rolled back and any
75101**                                prior changes are retained.
75102**
75103**  any              IGNORE       The record number and data is popped from
75104**                                the stack and there is an immediate jump
75105**                                to label ignoreDest.
75106**
75107**  NOT NULL         REPLACE      The NULL value is replace by the default
75108**                                value for that column.  If the default value
75109**                                is NULL, the action is the same as ABORT.
75110**
75111**  UNIQUE           REPLACE      The other row that conflicts with the row
75112**                                being inserted is removed.
75113**
75114**  CHECK            REPLACE      Illegal.  The results in an exception.
75115**
75116** Which action to take is determined by the overrideError parameter.
75117** Or if overrideError==OE_Default, then the pParse->onError parameter
75118** is used.  Or if pParse->onError==OE_Default then the onError value
75119** for the constraint is used.
75120**
75121** The calling routine must open a read/write cursor for pTab with
75122** cursor number "baseCur".  All indices of pTab must also have open
75123** read/write cursors with cursor number baseCur+i for the i-th cursor.
75124** Except, if there is no possibility of a REPLACE action then
75125** cursors do not need to be open for indices where aRegIdx[i]==0.
75126*/
75127SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
75128  Parse *pParse,      /* The parser context */
75129  Table *pTab,        /* the table into which we are inserting */
75130  int baseCur,        /* Index of a read/write cursor pointing at pTab */
75131  int regRowid,       /* Index of the range of input registers */
75132  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
75133  int rowidChng,      /* True if the rowid might collide with existing entry */
75134  int isUpdate,       /* True for UPDATE, False for INSERT */
75135  int overrideError,  /* Override onError to this if not OE_Default */
75136  int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
75137  int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
75138){
75139  int i;              /* loop counter */
75140  Vdbe *v;            /* VDBE under constrution */
75141  int nCol;           /* Number of columns */
75142  int onError;        /* Conflict resolution strategy */
75143  int j1;             /* Addresss of jump instruction */
75144  int j2 = 0, j3;     /* Addresses of jump instructions */
75145  int regData;        /* Register containing first data column */
75146  int iCur;           /* Table cursor number */
75147  Index *pIdx;         /* Pointer to one of the indices */
75148  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
75149  int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
75150
75151  v = sqlite3GetVdbe(pParse);
75152  assert( v!=0 );
75153  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
75154  nCol = pTab->nCol;
75155  regData = regRowid + 1;
75156
75157  /* Test all NOT NULL constraints.
75158  */
75159  for(i=0; i<nCol; i++){
75160    if( i==pTab->iPKey ){
75161      continue;
75162    }
75163    onError = pTab->aCol[i].notNull;
75164    if( onError==OE_None ) continue;
75165    if( overrideError!=OE_Default ){
75166      onError = overrideError;
75167    }else if( onError==OE_Default ){
75168      onError = OE_Abort;
75169    }
75170    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
75171      onError = OE_Abort;
75172    }
75173    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
75174        || onError==OE_Ignore || onError==OE_Replace );
75175    switch( onError ){
75176      case OE_Abort:
75177        sqlite3MayAbort(pParse);
75178      case OE_Rollback:
75179      case OE_Fail: {
75180        char *zMsg;
75181        j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
75182                                  SQLITE_CONSTRAINT, onError, regData+i);
75183        zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
75184                              pTab->zName, pTab->aCol[i].zName);
75185        sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
75186        break;
75187      }
75188      case OE_Ignore: {
75189        sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
75190        break;
75191      }
75192      default: {
75193        assert( onError==OE_Replace );
75194        j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
75195        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
75196        sqlite3VdbeJumpHere(v, j1);
75197        break;
75198      }
75199    }
75200  }
75201
75202  /* Test all CHECK constraints
75203  */
75204#ifndef SQLITE_OMIT_CHECK
75205  if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
75206    int allOk = sqlite3VdbeMakeLabel(v);
75207    pParse->ckBase = regData;
75208    sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
75209    onError = overrideError!=OE_Default ? overrideError : OE_Abort;
75210    if( onError==OE_Ignore ){
75211      sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
75212    }else{
75213      sqlite3HaltConstraint(pParse, onError, 0, 0);
75214    }
75215    sqlite3VdbeResolveLabel(v, allOk);
75216  }
75217#endif /* !defined(SQLITE_OMIT_CHECK) */
75218
75219  /* If we have an INTEGER PRIMARY KEY, make sure the primary key
75220  ** of the new record does not previously exist.  Except, if this
75221  ** is an UPDATE and the primary key is not changing, that is OK.
75222  */
75223  if( rowidChng ){
75224    onError = pTab->keyConf;
75225    if( overrideError!=OE_Default ){
75226      onError = overrideError;
75227    }else if( onError==OE_Default ){
75228      onError = OE_Abort;
75229    }
75230
75231    if( isUpdate ){
75232      j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
75233    }
75234    j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
75235    switch( onError ){
75236      default: {
75237        onError = OE_Abort;
75238        /* Fall thru into the next case */
75239      }
75240      case OE_Rollback:
75241      case OE_Abort:
75242      case OE_Fail: {
75243        sqlite3HaltConstraint(
75244          pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
75245        break;
75246      }
75247      case OE_Replace: {
75248        /* If there are DELETE triggers on this table and the
75249        ** recursive-triggers flag is set, call GenerateRowDelete() to
75250        ** remove the conflicting row from the the table. This will fire
75251        ** the triggers and remove both the table and index b-tree entries.
75252        **
75253        ** Otherwise, if there are no triggers or the recursive-triggers
75254        ** flag is not set, call GenerateRowIndexDelete(). This removes
75255        ** the index b-tree entries only. The table b-tree entry will be
75256        ** replaced by the new entry when it is inserted.  */
75257        Trigger *pTrigger = 0;
75258        if( pParse->db->flags&SQLITE_RecTriggers ){
75259          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
75260        }
75261        sqlite3MultiWrite(pParse);
75262        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
75263          sqlite3GenerateRowDelete(
75264              pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
75265          );
75266        }else{
75267          sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
75268        }
75269        seenReplace = 1;
75270        break;
75271      }
75272      case OE_Ignore: {
75273        assert( seenReplace==0 );
75274        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
75275        break;
75276      }
75277    }
75278    sqlite3VdbeJumpHere(v, j3);
75279    if( isUpdate ){
75280      sqlite3VdbeJumpHere(v, j2);
75281    }
75282  }
75283
75284  /* Test all UNIQUE constraints by creating entries for each UNIQUE
75285  ** index and making sure that duplicate entries do not already exist.
75286  ** Add the new records to the indices as we go.
75287  */
75288  for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
75289    int regIdx;
75290    int regR;
75291
75292    if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
75293
75294    /* Create a key for accessing the index entry */
75295    regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
75296    for(i=0; i<pIdx->nColumn; i++){
75297      int idx = pIdx->aiColumn[i];
75298      if( idx==pTab->iPKey ){
75299        sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
75300      }else{
75301        sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
75302      }
75303    }
75304    sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
75305    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
75306    sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
75307    sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
75308
75309    /* Find out what action to take in case there is an indexing conflict */
75310    onError = pIdx->onError;
75311    if( onError==OE_None ){
75312      sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
75313      continue;  /* pIdx is not a UNIQUE index */
75314    }
75315    if( overrideError!=OE_Default ){
75316      onError = overrideError;
75317    }else if( onError==OE_Default ){
75318      onError = OE_Abort;
75319    }
75320    if( seenReplace ){
75321      if( onError==OE_Ignore ) onError = OE_Replace;
75322      else if( onError==OE_Fail ) onError = OE_Abort;
75323    }
75324
75325    /* Check to see if the new index entry will be unique */
75326    regR = sqlite3GetTempReg(pParse);
75327    sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
75328    j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
75329                           regR, SQLITE_INT_TO_PTR(regIdx),
75330                           P4_INT32);
75331    sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
75332
75333    /* Generate code that executes if the new index entry is not unique */
75334    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
75335        || onError==OE_Ignore || onError==OE_Replace );
75336    switch( onError ){
75337      case OE_Rollback:
75338      case OE_Abort:
75339      case OE_Fail: {
75340        int j;
75341        StrAccum errMsg;
75342        const char *zSep;
75343        char *zErr;
75344
75345        sqlite3StrAccumInit(&errMsg, 0, 0, 200);
75346        errMsg.db = pParse->db;
75347        zSep = pIdx->nColumn>1 ? "columns " : "column ";
75348        for(j=0; j<pIdx->nColumn; j++){
75349          char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
75350          sqlite3StrAccumAppend(&errMsg, zSep, -1);
75351          zSep = ", ";
75352          sqlite3StrAccumAppend(&errMsg, zCol, -1);
75353        }
75354        sqlite3StrAccumAppend(&errMsg,
75355            pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
75356        zErr = sqlite3StrAccumFinish(&errMsg);
75357        sqlite3HaltConstraint(pParse, onError, zErr, 0);
75358        sqlite3DbFree(errMsg.db, zErr);
75359        break;
75360      }
75361      case OE_Ignore: {
75362        assert( seenReplace==0 );
75363        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
75364        break;
75365      }
75366      default: {
75367        Trigger *pTrigger = 0;
75368        assert( onError==OE_Replace );
75369        sqlite3MultiWrite(pParse);
75370        if( pParse->db->flags&SQLITE_RecTriggers ){
75371          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
75372        }
75373        sqlite3GenerateRowDelete(
75374            pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
75375        );
75376        seenReplace = 1;
75377        break;
75378      }
75379    }
75380    sqlite3VdbeJumpHere(v, j3);
75381    sqlite3ReleaseTempReg(pParse, regR);
75382  }
75383
75384  if( pbMayReplace ){
75385    *pbMayReplace = seenReplace;
75386  }
75387}
75388
75389/*
75390** This routine generates code to finish the INSERT or UPDATE operation
75391** that was started by a prior call to sqlite3GenerateConstraintChecks.
75392** A consecutive range of registers starting at regRowid contains the
75393** rowid and the content to be inserted.
75394**
75395** The arguments to this routine should be the same as the first six
75396** arguments to sqlite3GenerateConstraintChecks.
75397*/
75398SQLITE_PRIVATE void sqlite3CompleteInsertion(
75399  Parse *pParse,      /* The parser context */
75400  Table *pTab,        /* the table into which we are inserting */
75401  int baseCur,        /* Index of a read/write cursor pointing at pTab */
75402  int regRowid,       /* Range of content */
75403  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
75404  int isUpdate,       /* True for UPDATE, False for INSERT */
75405  int appendBias,     /* True if this is likely to be an append */
75406  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
75407){
75408  int i;
75409  Vdbe *v;
75410  int nIdx;
75411  Index *pIdx;
75412  u8 pik_flags;
75413  int regData;
75414  int regRec;
75415
75416  v = sqlite3GetVdbe(pParse);
75417  assert( v!=0 );
75418  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
75419  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
75420  for(i=nIdx-1; i>=0; i--){
75421    if( aRegIdx[i]==0 ) continue;
75422    sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
75423    if( useSeekResult ){
75424      sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
75425    }
75426  }
75427  regData = regRowid + 1;
75428  regRec = sqlite3GetTempReg(pParse);
75429  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
75430  sqlite3TableAffinityStr(v, pTab);
75431  sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
75432  if( pParse->nested ){
75433    pik_flags = 0;
75434  }else{
75435    pik_flags = OPFLAG_NCHANGE;
75436    pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
75437  }
75438  if( appendBias ){
75439    pik_flags |= OPFLAG_APPEND;
75440  }
75441  if( useSeekResult ){
75442    pik_flags |= OPFLAG_USESEEKRESULT;
75443  }
75444  sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
75445  if( !pParse->nested ){
75446    sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
75447  }
75448  sqlite3VdbeChangeP5(v, pik_flags);
75449}
75450
75451/*
75452** Generate code that will open cursors for a table and for all
75453** indices of that table.  The "baseCur" parameter is the cursor number used
75454** for the table.  Indices are opened on subsequent cursors.
75455**
75456** Return the number of indices on the table.
75457*/
75458SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
75459  Parse *pParse,   /* Parsing context */
75460  Table *pTab,     /* Table to be opened */
75461  int baseCur,     /* Cursor number assigned to the table */
75462  int op           /* OP_OpenRead or OP_OpenWrite */
75463){
75464  int i;
75465  int iDb;
75466  Index *pIdx;
75467  Vdbe *v;
75468
75469  if( IsVirtual(pTab) ) return 0;
75470  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
75471  v = sqlite3GetVdbe(pParse);
75472  assert( v!=0 );
75473  sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
75474  for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
75475    KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
75476    assert( pIdx->pSchema==pTab->pSchema );
75477    sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
75478                      (char*)pKey, P4_KEYINFO_HANDOFF);
75479    VdbeComment((v, "%s", pIdx->zName));
75480  }
75481  if( pParse->nTab<baseCur+i ){
75482    pParse->nTab = baseCur+i;
75483  }
75484  return i-1;
75485}
75486
75487
75488#ifdef SQLITE_TEST
75489/*
75490** The following global variable is incremented whenever the
75491** transfer optimization is used.  This is used for testing
75492** purposes only - to make sure the transfer optimization really
75493** is happening when it is suppose to.
75494*/
75495SQLITE_API int sqlite3_xferopt_count;
75496#endif /* SQLITE_TEST */
75497
75498
75499#ifndef SQLITE_OMIT_XFER_OPT
75500/*
75501** Check to collation names to see if they are compatible.
75502*/
75503static int xferCompatibleCollation(const char *z1, const char *z2){
75504  if( z1==0 ){
75505    return z2==0;
75506  }
75507  if( z2==0 ){
75508    return 0;
75509  }
75510  return sqlite3StrICmp(z1, z2)==0;
75511}
75512
75513
75514/*
75515** Check to see if index pSrc is compatible as a source of data
75516** for index pDest in an insert transfer optimization.  The rules
75517** for a compatible index:
75518**
75519**    *   The index is over the same set of columns
75520**    *   The same DESC and ASC markings occurs on all columns
75521**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
75522**    *   The same collating sequence on each column
75523*/
75524static int xferCompatibleIndex(Index *pDest, Index *pSrc){
75525  int i;
75526  assert( pDest && pSrc );
75527  assert( pDest->pTable!=pSrc->pTable );
75528  if( pDest->nColumn!=pSrc->nColumn ){
75529    return 0;   /* Different number of columns */
75530  }
75531  if( pDest->onError!=pSrc->onError ){
75532    return 0;   /* Different conflict resolution strategies */
75533  }
75534  for(i=0; i<pSrc->nColumn; i++){
75535    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
75536      return 0;   /* Different columns indexed */
75537    }
75538    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
75539      return 0;   /* Different sort orders */
75540    }
75541    if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
75542      return 0;   /* Different collating sequences */
75543    }
75544  }
75545
75546  /* If no test above fails then the indices must be compatible */
75547  return 1;
75548}
75549
75550/*
75551** Attempt the transfer optimization on INSERTs of the form
75552**
75553**     INSERT INTO tab1 SELECT * FROM tab2;
75554**
75555** This optimization is only attempted if
75556**
75557**    (1)  tab1 and tab2 have identical schemas including all the
75558**         same indices and constraints
75559**
75560**    (2)  tab1 and tab2 are different tables
75561**
75562**    (3)  There must be no triggers on tab1
75563**
75564**    (4)  The result set of the SELECT statement is "*"
75565**
75566**    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
75567**         or LIMIT clause.
75568**
75569**    (6)  The SELECT statement is a simple (not a compound) select that
75570**         contains only tab2 in its FROM clause
75571**
75572** This method for implementing the INSERT transfers raw records from
75573** tab2 over to tab1.  The columns are not decoded.  Raw records from
75574** the indices of tab2 are transfered to tab1 as well.  In so doing,
75575** the resulting tab1 has much less fragmentation.
75576**
75577** This routine returns TRUE if the optimization is attempted.  If any
75578** of the conditions above fail so that the optimization should not
75579** be attempted, then this routine returns FALSE.
75580*/
75581static int xferOptimization(
75582  Parse *pParse,        /* Parser context */
75583  Table *pDest,         /* The table we are inserting into */
75584  Select *pSelect,      /* A SELECT statement to use as the data source */
75585  int onError,          /* How to handle constraint errors */
75586  int iDbDest           /* The database of pDest */
75587){
75588  ExprList *pEList;                /* The result set of the SELECT */
75589  Table *pSrc;                     /* The table in the FROM clause of SELECT */
75590  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
75591  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
75592  int i;                           /* Loop counter */
75593  int iDbSrc;                      /* The database of pSrc */
75594  int iSrc, iDest;                 /* Cursors from source and destination */
75595  int addr1, addr2;                /* Loop addresses */
75596  int emptyDestTest;               /* Address of test for empty pDest */
75597  int emptySrcTest;                /* Address of test for empty pSrc */
75598  Vdbe *v;                         /* The VDBE we are building */
75599  KeyInfo *pKey;                   /* Key information for an index */
75600  int regAutoinc;                  /* Memory register used by AUTOINC */
75601  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
75602  int regData, regRowid;           /* Registers holding data and rowid */
75603
75604  if( pSelect==0 ){
75605    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
75606  }
75607  if( sqlite3TriggerList(pParse, pDest) ){
75608    return 0;   /* tab1 must not have triggers */
75609  }
75610#ifndef SQLITE_OMIT_VIRTUALTABLE
75611  if( pDest->tabFlags & TF_Virtual ){
75612    return 0;   /* tab1 must not be a virtual table */
75613  }
75614#endif
75615  if( onError==OE_Default ){
75616    onError = OE_Abort;
75617  }
75618  if( onError!=OE_Abort && onError!=OE_Rollback ){
75619    return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
75620  }
75621  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
75622  if( pSelect->pSrc->nSrc!=1 ){
75623    return 0;   /* FROM clause must have exactly one term */
75624  }
75625  if( pSelect->pSrc->a[0].pSelect ){
75626    return 0;   /* FROM clause cannot contain a subquery */
75627  }
75628  if( pSelect->pWhere ){
75629    return 0;   /* SELECT may not have a WHERE clause */
75630  }
75631  if( pSelect->pOrderBy ){
75632    return 0;   /* SELECT may not have an ORDER BY clause */
75633  }
75634  /* Do not need to test for a HAVING clause.  If HAVING is present but
75635  ** there is no ORDER BY, we will get an error. */
75636  if( pSelect->pGroupBy ){
75637    return 0;   /* SELECT may not have a GROUP BY clause */
75638  }
75639  if( pSelect->pLimit ){
75640    return 0;   /* SELECT may not have a LIMIT clause */
75641  }
75642  assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
75643  if( pSelect->pPrior ){
75644    return 0;   /* SELECT may not be a compound query */
75645  }
75646  if( pSelect->selFlags & SF_Distinct ){
75647    return 0;   /* SELECT may not be DISTINCT */
75648  }
75649  pEList = pSelect->pEList;
75650  assert( pEList!=0 );
75651  if( pEList->nExpr!=1 ){
75652    return 0;   /* The result set must have exactly one column */
75653  }
75654  assert( pEList->a[0].pExpr );
75655  if( pEList->a[0].pExpr->op!=TK_ALL ){
75656    return 0;   /* The result set must be the special operator "*" */
75657  }
75658
75659  /* At this point we have established that the statement is of the
75660  ** correct syntactic form to participate in this optimization.  Now
75661  ** we have to check the semantics.
75662  */
75663  pItem = pSelect->pSrc->a;
75664  pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
75665  if( pSrc==0 ){
75666    return 0;   /* FROM clause does not contain a real table */
75667  }
75668  if( pSrc==pDest ){
75669    return 0;   /* tab1 and tab2 may not be the same table */
75670  }
75671#ifndef SQLITE_OMIT_VIRTUALTABLE
75672  if( pSrc->tabFlags & TF_Virtual ){
75673    return 0;   /* tab2 must not be a virtual table */
75674  }
75675#endif
75676  if( pSrc->pSelect ){
75677    return 0;   /* tab2 may not be a view */
75678  }
75679  if( pDest->nCol!=pSrc->nCol ){
75680    return 0;   /* Number of columns must be the same in tab1 and tab2 */
75681  }
75682  if( pDest->iPKey!=pSrc->iPKey ){
75683    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
75684  }
75685  for(i=0; i<pDest->nCol; i++){
75686    if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
75687      return 0;    /* Affinity must be the same on all columns */
75688    }
75689    if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
75690      return 0;    /* Collating sequence must be the same on all columns */
75691    }
75692    if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
75693      return 0;    /* tab2 must be NOT NULL if tab1 is */
75694    }
75695  }
75696  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
75697    if( pDestIdx->onError!=OE_None ){
75698      destHasUniqueIdx = 1;
75699    }
75700    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
75701      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
75702    }
75703    if( pSrcIdx==0 ){
75704      return 0;    /* pDestIdx has no corresponding index in pSrc */
75705    }
75706  }
75707#ifndef SQLITE_OMIT_CHECK
75708  if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
75709    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
75710  }
75711#endif
75712
75713  /* If we get this far, it means either:
75714  **
75715  **    *   We can always do the transfer if the table contains an
75716  **        an integer primary key
75717  **
75718  **    *   We can conditionally do the transfer if the destination
75719  **        table is empty.
75720  */
75721#ifdef SQLITE_TEST
75722  sqlite3_xferopt_count++;
75723#endif
75724  iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
75725  v = sqlite3GetVdbe(pParse);
75726  sqlite3CodeVerifySchema(pParse, iDbSrc);
75727  iSrc = pParse->nTab++;
75728  iDest = pParse->nTab++;
75729  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
75730  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
75731  if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
75732    /* If tables do not have an INTEGER PRIMARY KEY and there
75733    ** are indices to be copied and the destination is not empty,
75734    ** we have to disallow the transfer optimization because the
75735    ** the rowids might change which will mess up indexing.
75736    **
75737    ** Or if the destination has a UNIQUE index and is not empty,
75738    ** we also disallow the transfer optimization because we cannot
75739    ** insure that all entries in the union of DEST and SRC will be
75740    ** unique.
75741    */
75742    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
75743    emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
75744    sqlite3VdbeJumpHere(v, addr1);
75745  }else{
75746    emptyDestTest = 0;
75747  }
75748  sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
75749  emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
75750  regData = sqlite3GetTempReg(pParse);
75751  regRowid = sqlite3GetTempReg(pParse);
75752  if( pDest->iPKey>=0 ){
75753    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
75754    addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
75755    sqlite3HaltConstraint(
75756        pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
75757    sqlite3VdbeJumpHere(v, addr2);
75758    autoIncStep(pParse, regAutoinc, regRowid);
75759  }else if( pDest->pIndex==0 ){
75760    addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
75761  }else{
75762    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
75763    assert( (pDest->tabFlags & TF_Autoincrement)==0 );
75764  }
75765  sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
75766  sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
75767  sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
75768  sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
75769  sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
75770  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
75771    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
75772      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
75773    }
75774    assert( pSrcIdx );
75775    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
75776    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
75777    pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
75778    sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
75779                      (char*)pKey, P4_KEYINFO_HANDOFF);
75780    VdbeComment((v, "%s", pSrcIdx->zName));
75781    pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
75782    sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
75783                      (char*)pKey, P4_KEYINFO_HANDOFF);
75784    VdbeComment((v, "%s", pDestIdx->zName));
75785    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
75786    sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
75787    sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
75788    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
75789    sqlite3VdbeJumpHere(v, addr1);
75790  }
75791  sqlite3VdbeJumpHere(v, emptySrcTest);
75792  sqlite3ReleaseTempReg(pParse, regRowid);
75793  sqlite3ReleaseTempReg(pParse, regData);
75794  sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
75795  sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
75796  if( emptyDestTest ){
75797    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
75798    sqlite3VdbeJumpHere(v, emptyDestTest);
75799    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
75800    return 0;
75801  }else{
75802    return 1;
75803  }
75804}
75805#endif /* SQLITE_OMIT_XFER_OPT */
75806
75807/************** End of insert.c **********************************************/
75808/************** Begin file legacy.c ******************************************/
75809/*
75810** 2001 September 15
75811**
75812** The author disclaims copyright to this source code.  In place of
75813** a legal notice, here is a blessing:
75814**
75815**    May you do good and not evil.
75816**    May you find forgiveness for yourself and forgive others.
75817**    May you share freely, never taking more than you give.
75818**
75819*************************************************************************
75820** Main file for the SQLite library.  The routines in this file
75821** implement the programmer interface to the library.  Routines in
75822** other files are for internal use by SQLite and should not be
75823** accessed by users of the library.
75824*/
75825
75826
75827/*
75828** Execute SQL code.  Return one of the SQLITE_ success/failure
75829** codes.  Also write an error message into memory obtained from
75830** malloc() and make *pzErrMsg point to that message.
75831**
75832** If the SQL is a query, then for each row in the query result
75833** the xCallback() function is called.  pArg becomes the first
75834** argument to xCallback().  If xCallback=NULL then no callback
75835** is invoked, even for queries.
75836*/
75837SQLITE_API int sqlite3_exec(
75838  sqlite3 *db,                /* The database on which the SQL executes */
75839  const char *zSql,           /* The SQL to be executed */
75840  sqlite3_callback xCallback, /* Invoke this callback routine */
75841  void *pArg,                 /* First argument to xCallback() */
75842  char **pzErrMsg             /* Write error messages here */
75843){
75844  int rc = SQLITE_OK;         /* Return code */
75845  const char *zLeftover;      /* Tail of unprocessed SQL */
75846  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
75847  char **azCols = 0;          /* Names of result columns */
75848  int nRetry = 0;             /* Number of retry attempts */
75849  int callbackIsInit;         /* True if callback data is initialized */
75850
75851  if( zSql==0 ) zSql = "";
75852
75853  sqlite3_mutex_enter(db->mutex);
75854  sqlite3Error(db, SQLITE_OK, 0);
75855  while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
75856    int nCol;
75857    char **azVals = 0;
75858
75859    pStmt = 0;
75860    rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
75861    assert( rc==SQLITE_OK || pStmt==0 );
75862    if( rc!=SQLITE_OK ){
75863      continue;
75864    }
75865    if( !pStmt ){
75866      /* this happens for a comment or white-space */
75867      zSql = zLeftover;
75868      continue;
75869    }
75870
75871    callbackIsInit = 0;
75872    nCol = sqlite3_column_count(pStmt);
75873
75874    while( 1 ){
75875      int i;
75876      rc = sqlite3_step(pStmt);
75877
75878      /* Invoke the callback function if required */
75879      if( xCallback && (SQLITE_ROW==rc ||
75880          (SQLITE_DONE==rc && !callbackIsInit
75881                           && db->flags&SQLITE_NullCallback)) ){
75882        if( !callbackIsInit ){
75883          azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
75884          if( azCols==0 ){
75885            goto exec_out;
75886          }
75887          for(i=0; i<nCol; i++){
75888            azCols[i] = (char *)sqlite3_column_name(pStmt, i);
75889            /* sqlite3VdbeSetColName() installs column names as UTF8
75890            ** strings so there is no way for sqlite3_column_name() to fail. */
75891            assert( azCols[i]!=0 );
75892          }
75893          callbackIsInit = 1;
75894        }
75895        if( rc==SQLITE_ROW ){
75896          azVals = &azCols[nCol];
75897          for(i=0; i<nCol; i++){
75898            azVals[i] = (char *)sqlite3_column_text(pStmt, i);
75899            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
75900              db->mallocFailed = 1;
75901              goto exec_out;
75902            }
75903          }
75904        }
75905        if( xCallback(pArg, nCol, azVals, azCols) ){
75906          rc = SQLITE_ABORT;
75907          sqlite3VdbeFinalize((Vdbe *)pStmt);
75908          pStmt = 0;
75909          sqlite3Error(db, SQLITE_ABORT, 0);
75910          goto exec_out;
75911        }
75912      }
75913
75914      if( rc!=SQLITE_ROW ){
75915        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
75916        pStmt = 0;
75917        if( rc!=SQLITE_SCHEMA ){
75918          nRetry = 0;
75919          zSql = zLeftover;
75920          while( sqlite3Isspace(zSql[0]) ) zSql++;
75921        }
75922        break;
75923      }
75924    }
75925
75926    sqlite3DbFree(db, azCols);
75927    azCols = 0;
75928  }
75929
75930exec_out:
75931  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
75932  sqlite3DbFree(db, azCols);
75933
75934  rc = sqlite3ApiExit(db, rc);
75935  if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
75936    int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
75937    *pzErrMsg = sqlite3Malloc(nErrMsg);
75938    if( *pzErrMsg ){
75939      memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
75940    }else{
75941      rc = SQLITE_NOMEM;
75942      sqlite3Error(db, SQLITE_NOMEM, 0);
75943    }
75944  }else if( pzErrMsg ){
75945    *pzErrMsg = 0;
75946  }
75947
75948  assert( (rc&db->errMask)==rc );
75949  sqlite3_mutex_leave(db->mutex);
75950  return rc;
75951}
75952
75953/************** End of legacy.c **********************************************/
75954/************** Begin file loadext.c *****************************************/
75955/*
75956** 2006 June 7
75957**
75958** The author disclaims copyright to this source code.  In place of
75959** a legal notice, here is a blessing:
75960**
75961**    May you do good and not evil.
75962**    May you find forgiveness for yourself and forgive others.
75963**    May you share freely, never taking more than you give.
75964**
75965*************************************************************************
75966** This file contains code used to dynamically load extensions into
75967** the SQLite library.
75968*/
75969
75970#ifndef SQLITE_CORE
75971  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
75972#endif
75973/************** Include sqlite3ext.h in the middle of loadext.c **************/
75974/************** Begin file sqlite3ext.h **************************************/
75975/*
75976** 2006 June 7
75977**
75978** The author disclaims copyright to this source code.  In place of
75979** a legal notice, here is a blessing:
75980**
75981**    May you do good and not evil.
75982**    May you find forgiveness for yourself and forgive others.
75983**    May you share freely, never taking more than you give.
75984**
75985*************************************************************************
75986** This header file defines the SQLite interface for use by
75987** shared libraries that want to be imported as extensions into
75988** an SQLite instance.  Shared libraries that intend to be loaded
75989** as extensions by SQLite should #include this file instead of
75990** sqlite3.h.
75991*/
75992#ifndef _SQLITE3EXT_H_
75993#define _SQLITE3EXT_H_
75994
75995typedef struct sqlite3_api_routines sqlite3_api_routines;
75996
75997/*
75998** The following structure holds pointers to all of the SQLite API
75999** routines.
76000**
76001** WARNING:  In order to maintain backwards compatibility, add new
76002** interfaces to the end of this structure only.  If you insert new
76003** interfaces in the middle of this structure, then older different
76004** versions of SQLite will not be able to load each others' shared
76005** libraries!
76006*/
76007struct sqlite3_api_routines {
76008  void * (*aggregate_context)(sqlite3_context*,int nBytes);
76009  int  (*aggregate_count)(sqlite3_context*);
76010  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
76011  int  (*bind_double)(sqlite3_stmt*,int,double);
76012  int  (*bind_int)(sqlite3_stmt*,int,int);
76013  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
76014  int  (*bind_null)(sqlite3_stmt*,int);
76015  int  (*bind_parameter_count)(sqlite3_stmt*);
76016  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
76017  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
76018  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
76019  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
76020  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
76021  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
76022  int  (*busy_timeout)(sqlite3*,int ms);
76023  int  (*changes)(sqlite3*);
76024  int  (*close)(sqlite3*);
76025  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
76026  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
76027  const void * (*column_blob)(sqlite3_stmt*,int iCol);
76028  int  (*column_bytes)(sqlite3_stmt*,int iCol);
76029  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
76030  int  (*column_count)(sqlite3_stmt*pStmt);
76031  const char * (*column_database_name)(sqlite3_stmt*,int);
76032  const void * (*column_database_name16)(sqlite3_stmt*,int);
76033  const char * (*column_decltype)(sqlite3_stmt*,int i);
76034  const void * (*column_decltype16)(sqlite3_stmt*,int);
76035  double  (*column_double)(sqlite3_stmt*,int iCol);
76036  int  (*column_int)(sqlite3_stmt*,int iCol);
76037  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
76038  const char * (*column_name)(sqlite3_stmt*,int);
76039  const void * (*column_name16)(sqlite3_stmt*,int);
76040  const char * (*column_origin_name)(sqlite3_stmt*,int);
76041  const void * (*column_origin_name16)(sqlite3_stmt*,int);
76042  const char * (*column_table_name)(sqlite3_stmt*,int);
76043  const void * (*column_table_name16)(sqlite3_stmt*,int);
76044  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
76045  const void * (*column_text16)(sqlite3_stmt*,int iCol);
76046  int  (*column_type)(sqlite3_stmt*,int iCol);
76047  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
76048  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
76049  int  (*complete)(const char*sql);
76050  int  (*complete16)(const void*sql);
76051  int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
76052  int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
76053  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*));
76054  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*));
76055  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
76056  int  (*data_count)(sqlite3_stmt*pStmt);
76057  sqlite3 * (*db_handle)(sqlite3_stmt*);
76058  int (*declare_vtab)(sqlite3*,const char*);
76059  int  (*enable_shared_cache)(int);
76060  int  (*errcode)(sqlite3*db);
76061  const char * (*errmsg)(sqlite3*);
76062  const void * (*errmsg16)(sqlite3*);
76063  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
76064  int  (*expired)(sqlite3_stmt*);
76065  int  (*finalize)(sqlite3_stmt*pStmt);
76066  void  (*free)(void*);
76067  void  (*free_table)(char**result);
76068  int  (*get_autocommit)(sqlite3*);
76069  void * (*get_auxdata)(sqlite3_context*,int);
76070  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
76071  int  (*global_recover)(void);
76072  void  (*interruptx)(sqlite3*);
76073  sqlite_int64  (*last_insert_rowid)(sqlite3*);
76074  const char * (*libversion)(void);
76075  int  (*libversion_number)(void);
76076  void *(*malloc)(int);
76077  char * (*mprintf)(const char*,...);
76078  int  (*open)(const char*,sqlite3**);
76079  int  (*open16)(const void*,sqlite3**);
76080  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
76081  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
76082  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
76083  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
76084  void *(*realloc)(void*,int);
76085  int  (*reset)(sqlite3_stmt*pStmt);
76086  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
76087  void  (*result_double)(sqlite3_context*,double);
76088  void  (*result_error)(sqlite3_context*,const char*,int);
76089  void  (*result_error16)(sqlite3_context*,const void*,int);
76090  void  (*result_int)(sqlite3_context*,int);
76091  void  (*result_int64)(sqlite3_context*,sqlite_int64);
76092  void  (*result_null)(sqlite3_context*);
76093  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
76094  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
76095  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
76096  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
76097  void  (*result_value)(sqlite3_context*,sqlite3_value*);
76098  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
76099  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
76100  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
76101  char * (*snprintf)(int,char*,const char*,...);
76102  int  (*step)(sqlite3_stmt*);
76103  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
76104  void  (*thread_cleanup)(void);
76105  int  (*total_changes)(sqlite3*);
76106  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
76107  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
76108  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
76109  void * (*user_data)(sqlite3_context*);
76110  const void * (*value_blob)(sqlite3_value*);
76111  int  (*value_bytes)(sqlite3_value*);
76112  int  (*value_bytes16)(sqlite3_value*);
76113  double  (*value_double)(sqlite3_value*);
76114  int  (*value_int)(sqlite3_value*);
76115  sqlite_int64  (*value_int64)(sqlite3_value*);
76116  int  (*value_numeric_type)(sqlite3_value*);
76117  const unsigned char * (*value_text)(sqlite3_value*);
76118  const void * (*value_text16)(sqlite3_value*);
76119  const void * (*value_text16be)(sqlite3_value*);
76120  const void * (*value_text16le)(sqlite3_value*);
76121  int  (*value_type)(sqlite3_value*);
76122  char *(*vmprintf)(const char*,va_list);
76123  /* Added ??? */
76124  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
76125  /* Added by 3.3.13 */
76126  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
76127  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
76128  int (*clear_bindings)(sqlite3_stmt*);
76129  /* Added by 3.4.1 */
76130  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
76131  /* Added by 3.5.0 */
76132  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
76133  int (*blob_bytes)(sqlite3_blob*);
76134  int (*blob_close)(sqlite3_blob*);
76135  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
76136  int (*blob_read)(sqlite3_blob*,void*,int,int);
76137  int (*blob_write)(sqlite3_blob*,const void*,int,int);
76138  int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
76139  int (*file_control)(sqlite3*,const char*,int,void*);
76140  sqlite3_int64 (*memory_highwater)(int);
76141  sqlite3_int64 (*memory_used)(void);
76142  sqlite3_mutex *(*mutex_alloc)(int);
76143  void (*mutex_enter)(sqlite3_mutex*);
76144  void (*mutex_free)(sqlite3_mutex*);
76145  void (*mutex_leave)(sqlite3_mutex*);
76146  int (*mutex_try)(sqlite3_mutex*);
76147  int (*open_v2)(const char*,sqlite3**,int,const char*);
76148  int (*release_memory)(int);
76149  void (*result_error_nomem)(sqlite3_context*);
76150  void (*result_error_toobig)(sqlite3_context*);
76151  int (*sleep)(int);
76152  void (*soft_heap_limit)(int);
76153  sqlite3_vfs *(*vfs_find)(const char*);
76154  int (*vfs_register)(sqlite3_vfs*,int);
76155  int (*vfs_unregister)(sqlite3_vfs*);
76156  int (*xthreadsafe)(void);
76157  void (*result_zeroblob)(sqlite3_context*,int);
76158  void (*result_error_code)(sqlite3_context*,int);
76159  int (*test_control)(int, ...);
76160  void (*randomness)(int,void*);
76161  sqlite3 *(*context_db_handle)(sqlite3_context*);
76162  int (*extended_result_codes)(sqlite3*,int);
76163  int (*limit)(sqlite3*,int,int);
76164  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
76165  const char *(*sql)(sqlite3_stmt*);
76166  int (*status)(int,int*,int*,int);
76167};
76168
76169/*
76170** The following macros redefine the API routines so that they are
76171** redirected throught the global sqlite3_api structure.
76172**
76173** This header file is also used by the loadext.c source file
76174** (part of the main SQLite library - not an extension) so that
76175** it can get access to the sqlite3_api_routines structure
76176** definition.  But the main library does not want to redefine
76177** the API.  So the redefinition macros are only valid if the
76178** SQLITE_CORE macros is undefined.
76179*/
76180#ifndef SQLITE_CORE
76181#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
76182#ifndef SQLITE_OMIT_DEPRECATED
76183#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
76184#endif
76185#define sqlite3_bind_blob              sqlite3_api->bind_blob
76186#define sqlite3_bind_double            sqlite3_api->bind_double
76187#define sqlite3_bind_int               sqlite3_api->bind_int
76188#define sqlite3_bind_int64             sqlite3_api->bind_int64
76189#define sqlite3_bind_null              sqlite3_api->bind_null
76190#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
76191#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
76192#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
76193#define sqlite3_bind_text              sqlite3_api->bind_text
76194#define sqlite3_bind_text16            sqlite3_api->bind_text16
76195#define sqlite3_bind_value             sqlite3_api->bind_value
76196#define sqlite3_busy_handler           sqlite3_api->busy_handler
76197#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
76198#define sqlite3_changes                sqlite3_api->changes
76199#define sqlite3_close                  sqlite3_api->close
76200#define sqlite3_collation_needed       sqlite3_api->collation_needed
76201#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
76202#define sqlite3_column_blob            sqlite3_api->column_blob
76203#define sqlite3_column_bytes           sqlite3_api->column_bytes
76204#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
76205#define sqlite3_column_count           sqlite3_api->column_count
76206#define sqlite3_column_database_name   sqlite3_api->column_database_name
76207#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
76208#define sqlite3_column_decltype        sqlite3_api->column_decltype
76209#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
76210#define sqlite3_column_double          sqlite3_api->column_double
76211#define sqlite3_column_int             sqlite3_api->column_int
76212#define sqlite3_column_int64           sqlite3_api->column_int64
76213#define sqlite3_column_name            sqlite3_api->column_name
76214#define sqlite3_column_name16          sqlite3_api->column_name16
76215#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
76216#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
76217#define sqlite3_column_table_name      sqlite3_api->column_table_name
76218#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
76219#define sqlite3_column_text            sqlite3_api->column_text
76220#define sqlite3_column_text16          sqlite3_api->column_text16
76221#define sqlite3_column_type            sqlite3_api->column_type
76222#define sqlite3_column_value           sqlite3_api->column_value
76223#define sqlite3_commit_hook            sqlite3_api->commit_hook
76224#define sqlite3_complete               sqlite3_api->complete
76225#define sqlite3_complete16             sqlite3_api->complete16
76226#define sqlite3_create_collation       sqlite3_api->create_collation
76227#define sqlite3_create_collation16     sqlite3_api->create_collation16
76228#define sqlite3_create_function        sqlite3_api->create_function
76229#define sqlite3_create_function16      sqlite3_api->create_function16
76230#define sqlite3_create_module          sqlite3_api->create_module
76231#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
76232#define sqlite3_data_count             sqlite3_api->data_count
76233#define sqlite3_db_handle              sqlite3_api->db_handle
76234#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
76235#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
76236#define sqlite3_errcode                sqlite3_api->errcode
76237#define sqlite3_errmsg                 sqlite3_api->errmsg
76238#define sqlite3_errmsg16               sqlite3_api->errmsg16
76239#define sqlite3_exec                   sqlite3_api->exec
76240#ifndef SQLITE_OMIT_DEPRECATED
76241#define sqlite3_expired                sqlite3_api->expired
76242#endif
76243#define sqlite3_finalize               sqlite3_api->finalize
76244#define sqlite3_free                   sqlite3_api->free
76245#define sqlite3_free_table             sqlite3_api->free_table
76246#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
76247#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
76248#define sqlite3_get_table              sqlite3_api->get_table
76249#ifndef SQLITE_OMIT_DEPRECATED
76250#define sqlite3_global_recover         sqlite3_api->global_recover
76251#endif
76252#define sqlite3_interrupt              sqlite3_api->interruptx
76253#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
76254#define sqlite3_libversion             sqlite3_api->libversion
76255#define sqlite3_libversion_number      sqlite3_api->libversion_number
76256#define sqlite3_malloc                 sqlite3_api->malloc
76257#define sqlite3_mprintf                sqlite3_api->mprintf
76258#define sqlite3_open                   sqlite3_api->open
76259#define sqlite3_open16                 sqlite3_api->open16
76260#define sqlite3_prepare                sqlite3_api->prepare
76261#define sqlite3_prepare16              sqlite3_api->prepare16
76262#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
76263#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
76264#define sqlite3_profile                sqlite3_api->profile
76265#define sqlite3_progress_handler       sqlite3_api->progress_handler
76266#define sqlite3_realloc                sqlite3_api->realloc
76267#define sqlite3_reset                  sqlite3_api->reset
76268#define sqlite3_result_blob            sqlite3_api->result_blob
76269#define sqlite3_result_double          sqlite3_api->result_double
76270#define sqlite3_result_error           sqlite3_api->result_error
76271#define sqlite3_result_error16         sqlite3_api->result_error16
76272#define sqlite3_result_int             sqlite3_api->result_int
76273#define sqlite3_result_int64           sqlite3_api->result_int64
76274#define sqlite3_result_null            sqlite3_api->result_null
76275#define sqlite3_result_text            sqlite3_api->result_text
76276#define sqlite3_result_text16          sqlite3_api->result_text16
76277#define sqlite3_result_text16be        sqlite3_api->result_text16be
76278#define sqlite3_result_text16le        sqlite3_api->result_text16le
76279#define sqlite3_result_value           sqlite3_api->result_value
76280#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
76281#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
76282#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
76283#define sqlite3_snprintf               sqlite3_api->snprintf
76284#define sqlite3_step                   sqlite3_api->step
76285#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
76286#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
76287#define sqlite3_total_changes          sqlite3_api->total_changes
76288#define sqlite3_trace                  sqlite3_api->trace
76289#ifndef SQLITE_OMIT_DEPRECATED
76290#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
76291#endif
76292#define sqlite3_update_hook            sqlite3_api->update_hook
76293#define sqlite3_user_data              sqlite3_api->user_data
76294#define sqlite3_value_blob             sqlite3_api->value_blob
76295#define sqlite3_value_bytes            sqlite3_api->value_bytes
76296#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
76297#define sqlite3_value_double           sqlite3_api->value_double
76298#define sqlite3_value_int              sqlite3_api->value_int
76299#define sqlite3_value_int64            sqlite3_api->value_int64
76300#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
76301#define sqlite3_value_text             sqlite3_api->value_text
76302#define sqlite3_value_text16           sqlite3_api->value_text16
76303#define sqlite3_value_text16be         sqlite3_api->value_text16be
76304#define sqlite3_value_text16le         sqlite3_api->value_text16le
76305#define sqlite3_value_type             sqlite3_api->value_type
76306#define sqlite3_vmprintf               sqlite3_api->vmprintf
76307#define sqlite3_overload_function      sqlite3_api->overload_function
76308#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
76309#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
76310#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
76311#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
76312#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
76313#define sqlite3_blob_close             sqlite3_api->blob_close
76314#define sqlite3_blob_open              sqlite3_api->blob_open
76315#define sqlite3_blob_read              sqlite3_api->blob_read
76316#define sqlite3_blob_write             sqlite3_api->blob_write
76317#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
76318#define sqlite3_file_control           sqlite3_api->file_control
76319#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
76320#define sqlite3_memory_used            sqlite3_api->memory_used
76321#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
76322#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
76323#define sqlite3_mutex_free             sqlite3_api->mutex_free
76324#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
76325#define sqlite3_mutex_try              sqlite3_api->mutex_try
76326#define sqlite3_open_v2                sqlite3_api->open_v2
76327#define sqlite3_release_memory         sqlite3_api->release_memory
76328#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
76329#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
76330#define sqlite3_sleep                  sqlite3_api->sleep
76331#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
76332#define sqlite3_vfs_find               sqlite3_api->vfs_find
76333#define sqlite3_vfs_register           sqlite3_api->vfs_register
76334#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
76335#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
76336#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
76337#define sqlite3_result_error_code      sqlite3_api->result_error_code
76338#define sqlite3_test_control           sqlite3_api->test_control
76339#define sqlite3_randomness             sqlite3_api->randomness
76340#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
76341#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
76342#define sqlite3_limit                  sqlite3_api->limit
76343#define sqlite3_next_stmt              sqlite3_api->next_stmt
76344#define sqlite3_sql                    sqlite3_api->sql
76345#define sqlite3_status                 sqlite3_api->status
76346#endif /* SQLITE_CORE */
76347
76348#define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
76349#define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
76350
76351#endif /* _SQLITE3EXT_H_ */
76352
76353/************** End of sqlite3ext.h ******************************************/
76354/************** Continuing where we left off in loadext.c ********************/
76355
76356#ifndef SQLITE_OMIT_LOAD_EXTENSION
76357
76358/*
76359** Some API routines are omitted when various features are
76360** excluded from a build of SQLite.  Substitute a NULL pointer
76361** for any missing APIs.
76362*/
76363#ifndef SQLITE_ENABLE_COLUMN_METADATA
76364# define sqlite3_column_database_name   0
76365# define sqlite3_column_database_name16 0
76366# define sqlite3_column_table_name      0
76367# define sqlite3_column_table_name16    0
76368# define sqlite3_column_origin_name     0
76369# define sqlite3_column_origin_name16   0
76370# define sqlite3_table_column_metadata  0
76371#endif
76372
76373#ifdef SQLITE_OMIT_AUTHORIZATION
76374# define sqlite3_set_authorizer         0
76375#endif
76376
76377#ifdef SQLITE_OMIT_UTF16
76378# define sqlite3_bind_text16            0
76379# define sqlite3_collation_needed16     0
76380# define sqlite3_column_decltype16      0
76381# define sqlite3_column_name16          0
76382# define sqlite3_column_text16          0
76383# define sqlite3_complete16             0
76384# define sqlite3_create_collation16     0
76385# define sqlite3_create_function16      0
76386# define sqlite3_errmsg16               0
76387# define sqlite3_open16                 0
76388# define sqlite3_prepare16              0
76389# define sqlite3_prepare16_v2           0
76390# define sqlite3_result_error16         0
76391# define sqlite3_result_text16          0
76392# define sqlite3_result_text16be        0
76393# define sqlite3_result_text16le        0
76394# define sqlite3_value_text16           0
76395# define sqlite3_value_text16be         0
76396# define sqlite3_value_text16le         0
76397# define sqlite3_column_database_name16 0
76398# define sqlite3_column_table_name16    0
76399# define sqlite3_column_origin_name16   0
76400#endif
76401
76402#ifdef SQLITE_OMIT_COMPLETE
76403# define sqlite3_complete 0
76404# define sqlite3_complete16 0
76405#endif
76406
76407#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
76408# define sqlite3_progress_handler 0
76409#endif
76410
76411#ifdef SQLITE_OMIT_VIRTUALTABLE
76412# define sqlite3_create_module 0
76413# define sqlite3_create_module_v2 0
76414# define sqlite3_declare_vtab 0
76415#endif
76416
76417#ifdef SQLITE_OMIT_SHARED_CACHE
76418# define sqlite3_enable_shared_cache 0
76419#endif
76420
76421#ifdef SQLITE_OMIT_TRACE
76422# define sqlite3_profile       0
76423# define sqlite3_trace         0
76424#endif
76425
76426#ifdef SQLITE_OMIT_GET_TABLE
76427# define sqlite3_free_table    0
76428# define sqlite3_get_table     0
76429#endif
76430
76431#ifdef SQLITE_OMIT_INCRBLOB
76432#define sqlite3_bind_zeroblob  0
76433#define sqlite3_blob_bytes     0
76434#define sqlite3_blob_close     0
76435#define sqlite3_blob_open      0
76436#define sqlite3_blob_read      0
76437#define sqlite3_blob_write     0
76438#endif
76439
76440/*
76441** The following structure contains pointers to all SQLite API routines.
76442** A pointer to this structure is passed into extensions when they are
76443** loaded so that the extension can make calls back into the SQLite
76444** library.
76445**
76446** When adding new APIs, add them to the bottom of this structure
76447** in order to preserve backwards compatibility.
76448**
76449** Extensions that use newer APIs should first call the
76450** sqlite3_libversion_number() to make sure that the API they
76451** intend to use is supported by the library.  Extensions should
76452** also check to make sure that the pointer to the function is
76453** not NULL before calling it.
76454*/
76455static const sqlite3_api_routines sqlite3Apis = {
76456  sqlite3_aggregate_context,
76457#ifndef SQLITE_OMIT_DEPRECATED
76458  sqlite3_aggregate_count,
76459#else
76460  0,
76461#endif
76462  sqlite3_bind_blob,
76463  sqlite3_bind_double,
76464  sqlite3_bind_int,
76465  sqlite3_bind_int64,
76466  sqlite3_bind_null,
76467  sqlite3_bind_parameter_count,
76468  sqlite3_bind_parameter_index,
76469  sqlite3_bind_parameter_name,
76470  sqlite3_bind_text,
76471  sqlite3_bind_text16,
76472  sqlite3_bind_value,
76473  sqlite3_busy_handler,
76474  sqlite3_busy_timeout,
76475  sqlite3_changes,
76476  sqlite3_close,
76477  sqlite3_collation_needed,
76478  sqlite3_collation_needed16,
76479  sqlite3_column_blob,
76480  sqlite3_column_bytes,
76481  sqlite3_column_bytes16,
76482  sqlite3_column_count,
76483  sqlite3_column_database_name,
76484  sqlite3_column_database_name16,
76485  sqlite3_column_decltype,
76486  sqlite3_column_decltype16,
76487  sqlite3_column_double,
76488  sqlite3_column_int,
76489  sqlite3_column_int64,
76490  sqlite3_column_name,
76491  sqlite3_column_name16,
76492  sqlite3_column_origin_name,
76493  sqlite3_column_origin_name16,
76494  sqlite3_column_table_name,
76495  sqlite3_column_table_name16,
76496  sqlite3_column_text,
76497  sqlite3_column_text16,
76498  sqlite3_column_type,
76499  sqlite3_column_value,
76500  sqlite3_commit_hook,
76501  sqlite3_complete,
76502  sqlite3_complete16,
76503  sqlite3_create_collation,
76504  sqlite3_create_collation16,
76505  sqlite3_create_function,
76506  sqlite3_create_function16,
76507  sqlite3_create_module,
76508  sqlite3_data_count,
76509  sqlite3_db_handle,
76510  sqlite3_declare_vtab,
76511  sqlite3_enable_shared_cache,
76512  sqlite3_errcode,
76513  sqlite3_errmsg,
76514  sqlite3_errmsg16,
76515  sqlite3_exec,
76516#ifndef SQLITE_OMIT_DEPRECATED
76517  sqlite3_expired,
76518#else
76519  0,
76520#endif
76521  sqlite3_finalize,
76522  sqlite3_free,
76523  sqlite3_free_table,
76524  sqlite3_get_autocommit,
76525  sqlite3_get_auxdata,
76526  sqlite3_get_table,
76527  0,     /* Was sqlite3_global_recover(), but that function is deprecated */
76528  sqlite3_interrupt,
76529  sqlite3_last_insert_rowid,
76530  sqlite3_libversion,
76531  sqlite3_libversion_number,
76532  sqlite3_malloc,
76533  sqlite3_mprintf,
76534  sqlite3_open,
76535  sqlite3_open16,
76536  sqlite3_prepare,
76537  sqlite3_prepare16,
76538  sqlite3_profile,
76539  sqlite3_progress_handler,
76540  sqlite3_realloc,
76541  sqlite3_reset,
76542  sqlite3_result_blob,
76543  sqlite3_result_double,
76544  sqlite3_result_error,
76545  sqlite3_result_error16,
76546  sqlite3_result_int,
76547  sqlite3_result_int64,
76548  sqlite3_result_null,
76549  sqlite3_result_text,
76550  sqlite3_result_text16,
76551  sqlite3_result_text16be,
76552  sqlite3_result_text16le,
76553  sqlite3_result_value,
76554  sqlite3_rollback_hook,
76555  sqlite3_set_authorizer,
76556  sqlite3_set_auxdata,
76557  sqlite3_snprintf,
76558  sqlite3_step,
76559  sqlite3_table_column_metadata,
76560#ifndef SQLITE_OMIT_DEPRECATED
76561  sqlite3_thread_cleanup,
76562#else
76563  0,
76564#endif
76565  sqlite3_total_changes,
76566  sqlite3_trace,
76567#ifndef SQLITE_OMIT_DEPRECATED
76568  sqlite3_transfer_bindings,
76569#else
76570  0,
76571#endif
76572  sqlite3_update_hook,
76573  sqlite3_user_data,
76574  sqlite3_value_blob,
76575  sqlite3_value_bytes,
76576  sqlite3_value_bytes16,
76577  sqlite3_value_double,
76578  sqlite3_value_int,
76579  sqlite3_value_int64,
76580  sqlite3_value_numeric_type,
76581  sqlite3_value_text,
76582  sqlite3_value_text16,
76583  sqlite3_value_text16be,
76584  sqlite3_value_text16le,
76585  sqlite3_value_type,
76586  sqlite3_vmprintf,
76587  /*
76588  ** The original API set ends here.  All extensions can call any
76589  ** of the APIs above provided that the pointer is not NULL.  But
76590  ** before calling APIs that follow, extension should check the
76591  ** sqlite3_libversion_number() to make sure they are dealing with
76592  ** a library that is new enough to support that API.
76593  *************************************************************************
76594  */
76595  sqlite3_overload_function,
76596
76597  /*
76598  ** Added after 3.3.13
76599  */
76600  sqlite3_prepare_v2,
76601  sqlite3_prepare16_v2,
76602  sqlite3_clear_bindings,
76603
76604  /*
76605  ** Added for 3.4.1
76606  */
76607  sqlite3_create_module_v2,
76608
76609  /*
76610  ** Added for 3.5.0
76611  */
76612  sqlite3_bind_zeroblob,
76613  sqlite3_blob_bytes,
76614  sqlite3_blob_close,
76615  sqlite3_blob_open,
76616  sqlite3_blob_read,
76617  sqlite3_blob_write,
76618  sqlite3_create_collation_v2,
76619  sqlite3_file_control,
76620  sqlite3_memory_highwater,
76621  sqlite3_memory_used,
76622#ifdef SQLITE_MUTEX_OMIT
76623  0,
76624  0,
76625  0,
76626  0,
76627  0,
76628#else
76629  sqlite3_mutex_alloc,
76630  sqlite3_mutex_enter,
76631  sqlite3_mutex_free,
76632  sqlite3_mutex_leave,
76633  sqlite3_mutex_try,
76634#endif
76635  sqlite3_open_v2,
76636  sqlite3_release_memory,
76637  sqlite3_result_error_nomem,
76638  sqlite3_result_error_toobig,
76639  sqlite3_sleep,
76640  sqlite3_soft_heap_limit,
76641  sqlite3_vfs_find,
76642  sqlite3_vfs_register,
76643  sqlite3_vfs_unregister,
76644
76645  /*
76646  ** Added for 3.5.8
76647  */
76648  sqlite3_threadsafe,
76649  sqlite3_result_zeroblob,
76650  sqlite3_result_error_code,
76651  sqlite3_test_control,
76652  sqlite3_randomness,
76653  sqlite3_context_db_handle,
76654
76655  /*
76656  ** Added for 3.6.0
76657  */
76658  sqlite3_extended_result_codes,
76659  sqlite3_limit,
76660  sqlite3_next_stmt,
76661  sqlite3_sql,
76662  sqlite3_status,
76663};
76664
76665/*
76666** Attempt to load an SQLite extension library contained in the file
76667** zFile.  The entry point is zProc.  zProc may be 0 in which case a
76668** default entry point name (sqlite3_extension_init) is used.  Use
76669** of the default name is recommended.
76670**
76671** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
76672**
76673** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
76674** error message text.  The calling function should free this memory
76675** by calling sqlite3DbFree(db, ).
76676*/
76677static int sqlite3LoadExtension(
76678  sqlite3 *db,          /* Load the extension into this database connection */
76679  const char *zFile,    /* Name of the shared library containing extension */
76680  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
76681  char **pzErrMsg       /* Put error message here if not 0 */
76682){
76683  sqlite3_vfs *pVfs = db->pVfs;
76684  void *handle;
76685  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
76686  char *zErrmsg = 0;
76687  void **aHandle;
76688  const int nMsg = 300;
76689
76690  if( pzErrMsg ) *pzErrMsg = 0;
76691
76692  /* Ticket #1863.  To avoid a creating security problems for older
76693  ** applications that relink against newer versions of SQLite, the
76694  ** ability to run load_extension is turned off by default.  One
76695  ** must call sqlite3_enable_load_extension() to turn on extension
76696  ** loading.  Otherwise you get the following error.
76697  */
76698  if( (db->flags & SQLITE_LoadExtension)==0 ){
76699    if( pzErrMsg ){
76700      *pzErrMsg = sqlite3_mprintf("not authorized");
76701    }
76702    return SQLITE_ERROR;
76703  }
76704
76705  if( zProc==0 ){
76706    zProc = "sqlite3_extension_init";
76707  }
76708
76709  handle = sqlite3OsDlOpen(pVfs, zFile);
76710  if( handle==0 ){
76711    if( pzErrMsg ){
76712      zErrmsg = sqlite3StackAllocZero(db, nMsg);
76713      if( zErrmsg ){
76714        sqlite3_snprintf(nMsg, zErrmsg,
76715            "unable to open shared library [%s]", zFile);
76716        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
76717        *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
76718        sqlite3StackFree(db, zErrmsg);
76719      }
76720    }
76721    return SQLITE_ERROR;
76722  }
76723  xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
76724                   sqlite3OsDlSym(pVfs, handle, zProc);
76725  if( xInit==0 ){
76726    if( pzErrMsg ){
76727      zErrmsg = sqlite3StackAllocZero(db, nMsg);
76728      if( zErrmsg ){
76729        sqlite3_snprintf(nMsg, zErrmsg,
76730            "no entry point [%s] in shared library [%s]", zProc,zFile);
76731        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
76732        *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
76733        sqlite3StackFree(db, zErrmsg);
76734      }
76735      sqlite3OsDlClose(pVfs, handle);
76736    }
76737    return SQLITE_ERROR;
76738  }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
76739    if( pzErrMsg ){
76740      *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
76741    }
76742    sqlite3_free(zErrmsg);
76743    sqlite3OsDlClose(pVfs, handle);
76744    return SQLITE_ERROR;
76745  }
76746
76747  /* Append the new shared library handle to the db->aExtension array. */
76748  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
76749  if( aHandle==0 ){
76750    return SQLITE_NOMEM;
76751  }
76752  if( db->nExtension>0 ){
76753    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
76754  }
76755  sqlite3DbFree(db, db->aExtension);
76756  db->aExtension = aHandle;
76757
76758  db->aExtension[db->nExtension++] = handle;
76759  return SQLITE_OK;
76760}
76761SQLITE_API int sqlite3_load_extension(
76762  sqlite3 *db,          /* Load the extension into this database connection */
76763  const char *zFile,    /* Name of the shared library containing extension */
76764  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
76765  char **pzErrMsg       /* Put error message here if not 0 */
76766){
76767  int rc;
76768  sqlite3_mutex_enter(db->mutex);
76769  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
76770  rc = sqlite3ApiExit(db, rc);
76771  sqlite3_mutex_leave(db->mutex);
76772  return rc;
76773}
76774
76775/*
76776** Call this routine when the database connection is closing in order
76777** to clean up loaded extensions
76778*/
76779SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
76780  int i;
76781  assert( sqlite3_mutex_held(db->mutex) );
76782  for(i=0; i<db->nExtension; i++){
76783    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
76784  }
76785  sqlite3DbFree(db, db->aExtension);
76786}
76787
76788/*
76789** Enable or disable extension loading.  Extension loading is disabled by
76790** default so as not to open security holes in older applications.
76791*/
76792SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
76793  sqlite3_mutex_enter(db->mutex);
76794  if( onoff ){
76795    db->flags |= SQLITE_LoadExtension;
76796  }else{
76797    db->flags &= ~SQLITE_LoadExtension;
76798  }
76799  sqlite3_mutex_leave(db->mutex);
76800  return SQLITE_OK;
76801}
76802
76803#endif /* SQLITE_OMIT_LOAD_EXTENSION */
76804
76805/*
76806** The auto-extension code added regardless of whether or not extension
76807** loading is supported.  We need a dummy sqlite3Apis pointer for that
76808** code if regular extension loading is not available.  This is that
76809** dummy pointer.
76810*/
76811#ifdef SQLITE_OMIT_LOAD_EXTENSION
76812static const sqlite3_api_routines sqlite3Apis = { 0 };
76813#endif
76814
76815
76816/*
76817** The following object holds the list of automatically loaded
76818** extensions.
76819**
76820** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
76821** mutex must be held while accessing this list.
76822*/
76823typedef struct sqlite3AutoExtList sqlite3AutoExtList;
76824static SQLITE_WSD struct sqlite3AutoExtList {
76825  int nExt;              /* Number of entries in aExt[] */
76826  void (**aExt)(void);   /* Pointers to the extension init functions */
76827} sqlite3Autoext = { 0, 0 };
76828
76829/* The "wsdAutoext" macro will resolve to the autoextension
76830** state vector.  If writable static data is unsupported on the target,
76831** we have to locate the state vector at run-time.  In the more common
76832** case where writable static data is supported, wsdStat can refer directly
76833** to the "sqlite3Autoext" state vector declared above.
76834*/
76835#ifdef SQLITE_OMIT_WSD
76836# define wsdAutoextInit \
76837  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
76838# define wsdAutoext x[0]
76839#else
76840# define wsdAutoextInit
76841# define wsdAutoext sqlite3Autoext
76842#endif
76843
76844
76845/*
76846** Register a statically linked extension that is automatically
76847** loaded by every new database connection.
76848*/
76849SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
76850  int rc = SQLITE_OK;
76851#ifndef SQLITE_OMIT_AUTOINIT
76852  rc = sqlite3_initialize();
76853  if( rc ){
76854    return rc;
76855  }else
76856#endif
76857  {
76858    int i;
76859#if SQLITE_THREADSAFE
76860    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
76861#endif
76862    wsdAutoextInit;
76863    sqlite3_mutex_enter(mutex);
76864    for(i=0; i<wsdAutoext.nExt; i++){
76865      if( wsdAutoext.aExt[i]==xInit ) break;
76866    }
76867    if( i==wsdAutoext.nExt ){
76868      int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
76869      void (**aNew)(void);
76870      aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
76871      if( aNew==0 ){
76872        rc = SQLITE_NOMEM;
76873      }else{
76874        wsdAutoext.aExt = aNew;
76875        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
76876        wsdAutoext.nExt++;
76877      }
76878    }
76879    sqlite3_mutex_leave(mutex);
76880    assert( (rc&0xff)==rc );
76881    return rc;
76882  }
76883}
76884
76885/*
76886** Reset the automatic extension loading mechanism.
76887*/
76888SQLITE_API void sqlite3_reset_auto_extension(void){
76889#ifndef SQLITE_OMIT_AUTOINIT
76890  if( sqlite3_initialize()==SQLITE_OK )
76891#endif
76892  {
76893#if SQLITE_THREADSAFE
76894    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
76895#endif
76896    wsdAutoextInit;
76897    sqlite3_mutex_enter(mutex);
76898    sqlite3_free(wsdAutoext.aExt);
76899    wsdAutoext.aExt = 0;
76900    wsdAutoext.nExt = 0;
76901    sqlite3_mutex_leave(mutex);
76902  }
76903}
76904
76905/*
76906** Load all automatic extensions.
76907**
76908** If anything goes wrong, set an error in the database connection.
76909*/
76910SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
76911  int i;
76912  int go = 1;
76913  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
76914
76915  wsdAutoextInit;
76916  if( wsdAutoext.nExt==0 ){
76917    /* Common case: early out without every having to acquire a mutex */
76918    return;
76919  }
76920  for(i=0; go; i++){
76921    char *zErrmsg;
76922#if SQLITE_THREADSAFE
76923    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
76924#endif
76925    sqlite3_mutex_enter(mutex);
76926    if( i>=wsdAutoext.nExt ){
76927      xInit = 0;
76928      go = 0;
76929    }else{
76930      xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
76931              wsdAutoext.aExt[i];
76932    }
76933    sqlite3_mutex_leave(mutex);
76934    zErrmsg = 0;
76935    if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
76936      sqlite3Error(db, SQLITE_ERROR,
76937            "automatic extension loading failed: %s", zErrmsg);
76938      go = 0;
76939    }
76940    sqlite3_free(zErrmsg);
76941  }
76942}
76943
76944/************** End of loadext.c *********************************************/
76945/************** Begin file pragma.c ******************************************/
76946/*
76947** 2003 April 6
76948**
76949** The author disclaims copyright to this source code.  In place of
76950** a legal notice, here is a blessing:
76951**
76952**    May you do good and not evil.
76953**    May you find forgiveness for yourself and forgive others.
76954**    May you share freely, never taking more than you give.
76955**
76956*************************************************************************
76957** This file contains code used to implement the PRAGMA command.
76958*/
76959
76960/* Ignore this whole file if pragmas are disabled
76961*/
76962#if !defined(SQLITE_OMIT_PRAGMA)
76963
76964/*
76965** Interpret the given string as a safety level.  Return 0 for OFF,
76966** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
76967** unrecognized string argument.
76968**
76969** Note that the values returned are one less that the values that
76970** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
76971** to support legacy SQL code.  The safety level used to be boolean
76972** and older scripts may have used numbers 0 for OFF and 1 for ON.
76973*/
76974static u8 getSafetyLevel(const char *z){
76975                             /* 123456789 123456789 */
76976  static const char zText[] = "onoffalseyestruefull";
76977  static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
76978  static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
76979  static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
76980  int i, n;
76981  if( sqlite3Isdigit(*z) ){
76982    return (u8)atoi(z);
76983  }
76984  n = sqlite3Strlen30(z);
76985  for(i=0; i<ArraySize(iLength); i++){
76986    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
76987      return iValue[i];
76988    }
76989  }
76990  return 1;
76991}
76992
76993/*
76994** Interpret the given string as a boolean value.
76995*/
76996static u8 getBoolean(const char *z){
76997  return getSafetyLevel(z)&1;
76998}
76999
77000/*
77001** Interpret the given string as a locking mode value.
77002*/
77003static int getLockingMode(const char *z){
77004  if( z ){
77005    if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
77006    if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
77007  }
77008  return PAGER_LOCKINGMODE_QUERY;
77009}
77010
77011#ifndef SQLITE_OMIT_AUTOVACUUM
77012/*
77013** Interpret the given string as an auto-vacuum mode value.
77014**
77015** The following strings, "none", "full" and "incremental" are
77016** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
77017*/
77018static int getAutoVacuum(const char *z){
77019  int i;
77020  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
77021  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
77022  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
77023  i = atoi(z);
77024  return (u8)((i>=0&&i<=2)?i:0);
77025}
77026#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
77027
77028#ifndef SQLITE_OMIT_PAGER_PRAGMAS
77029/*
77030** Interpret the given string as a temp db location. Return 1 for file
77031** backed temporary databases, 2 for the Red-Black tree in memory database
77032** and 0 to use the compile-time default.
77033*/
77034static int getTempStore(const char *z){
77035  if( z[0]>='0' && z[0]<='2' ){
77036    return z[0] - '0';
77037  }else if( sqlite3StrICmp(z, "file")==0 ){
77038    return 1;
77039  }else if( sqlite3StrICmp(z, "memory")==0 ){
77040    return 2;
77041  }else{
77042    return 0;
77043  }
77044}
77045#endif /* SQLITE_PAGER_PRAGMAS */
77046
77047#ifndef SQLITE_OMIT_PAGER_PRAGMAS
77048/*
77049** Invalidate temp storage, either when the temp storage is changed
77050** from default, or when 'file' and the temp_store_directory has changed
77051*/
77052static int invalidateTempStorage(Parse *pParse){
77053  sqlite3 *db = pParse->db;
77054  if( db->aDb[1].pBt!=0 ){
77055    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
77056      sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
77057        "from within a transaction");
77058      return SQLITE_ERROR;
77059    }
77060    sqlite3BtreeClose(db->aDb[1].pBt);
77061    db->aDb[1].pBt = 0;
77062    sqlite3ResetInternalSchema(db, 0);
77063  }
77064  return SQLITE_OK;
77065}
77066#endif /* SQLITE_PAGER_PRAGMAS */
77067
77068#ifndef SQLITE_OMIT_PAGER_PRAGMAS
77069/*
77070** If the TEMP database is open, close it and mark the database schema
77071** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
77072** or DEFAULT_TEMP_STORE pragmas.
77073*/
77074static int changeTempStorage(Parse *pParse, const char *zStorageType){
77075  int ts = getTempStore(zStorageType);
77076  sqlite3 *db = pParse->db;
77077  if( db->temp_store==ts ) return SQLITE_OK;
77078  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
77079    return SQLITE_ERROR;
77080  }
77081  db->temp_store = (u8)ts;
77082  return SQLITE_OK;
77083}
77084#endif /* SQLITE_PAGER_PRAGMAS */
77085
77086/*
77087** Generate code to return a single integer value.
77088*/
77089static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
77090  Vdbe *v = sqlite3GetVdbe(pParse);
77091  int mem = ++pParse->nMem;
77092  i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
77093  if( pI64 ){
77094    memcpy(pI64, &value, sizeof(value));
77095  }
77096  sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
77097  sqlite3VdbeSetNumCols(v, 1);
77098  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
77099  sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
77100}
77101
77102#ifndef SQLITE_OMIT_FLAG_PRAGMAS
77103/*
77104** Check to see if zRight and zLeft refer to a pragma that queries
77105** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
77106** Also, implement the pragma.
77107*/
77108static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
77109  static const struct sPragmaType {
77110    const char *zName;  /* Name of the pragma */
77111    int mask;           /* Mask for the db->flags value */
77112  } aPragma[] = {
77113    { "full_column_names",        SQLITE_FullColNames  },
77114    { "short_column_names",       SQLITE_ShortColNames },
77115    { "count_changes",            SQLITE_CountRows     },
77116    { "empty_result_callbacks",   SQLITE_NullCallback  },
77117    { "legacy_file_format",       SQLITE_LegacyFileFmt },
77118    { "fullfsync",                SQLITE_FullFSync     },
77119    { "reverse_unordered_selects", SQLITE_ReverseOrder  },
77120#ifdef SQLITE_DEBUG
77121    { "sql_trace",                SQLITE_SqlTrace      },
77122    { "vdbe_listing",             SQLITE_VdbeListing   },
77123    { "vdbe_trace",               SQLITE_VdbeTrace     },
77124#endif
77125#ifndef SQLITE_OMIT_CHECK
77126    { "ignore_check_constraints", SQLITE_IgnoreChecks  },
77127#endif
77128    /* The following is VERY experimental */
77129    { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
77130    { "omit_readlock",            SQLITE_NoReadlock    },
77131
77132    /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
77133    ** flag if there are any active statements. */
77134    { "read_uncommitted",         SQLITE_ReadUncommitted },
77135    { "recursive_triggers",       SQLITE_RecTriggers },
77136
77137    /* This flag may only be set if both foreign-key and trigger support
77138    ** are present in the build.  */
77139#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
77140    { "foreign_keys",             SQLITE_ForeignKeys },
77141#endif
77142  };
77143  int i;
77144  const struct sPragmaType *p;
77145  for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
77146    if( sqlite3StrICmp(zLeft, p->zName)==0 ){
77147      sqlite3 *db = pParse->db;
77148      Vdbe *v;
77149      v = sqlite3GetVdbe(pParse);
77150      assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
77151      if( ALWAYS(v) ){
77152        if( zRight==0 ){
77153          returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
77154        }else{
77155          int mask = p->mask;          /* Mask of bits to set or clear. */
77156          if( db->autoCommit==0 ){
77157            /* Foreign key support may not be enabled or disabled while not
77158            ** in auto-commit mode.  */
77159            mask &= ~(SQLITE_ForeignKeys);
77160          }
77161
77162          if( getBoolean(zRight) ){
77163            db->flags |= mask;
77164          }else{
77165            db->flags &= ~mask;
77166          }
77167
77168          /* Many of the flag-pragmas modify the code generated by the SQL
77169          ** compiler (eg. count_changes). So add an opcode to expire all
77170          ** compiled SQL statements after modifying a pragma value.
77171          */
77172          sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
77173        }
77174      }
77175
77176      return 1;
77177    }
77178  }
77179  return 0;
77180}
77181#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
77182
77183/*
77184** Return a human-readable name for a constraint resolution action.
77185*/
77186#ifndef SQLITE_OMIT_FOREIGN_KEY
77187static const char *actionName(u8 action){
77188  const char *zName;
77189  switch( action ){
77190    case OE_SetNull:  zName = "SET NULL";        break;
77191    case OE_SetDflt:  zName = "SET DEFAULT";     break;
77192    case OE_Cascade:  zName = "CASCADE";         break;
77193    case OE_Restrict: zName = "RESTRICT";        break;
77194    default:          zName = "NO ACTION";
77195                      assert( action==OE_None ); break;
77196  }
77197  return zName;
77198}
77199#endif
77200
77201/*
77202** Process a pragma statement.
77203**
77204** Pragmas are of this form:
77205**
77206**      PRAGMA [database.]id [= value]
77207**
77208** The identifier might also be a string.  The value is a string, and
77209** identifier, or a number.  If minusFlag is true, then the value is
77210** a number that was preceded by a minus sign.
77211**
77212** If the left side is "database.id" then pId1 is the database name
77213** and pId2 is the id.  If the left side is just "id" then pId1 is the
77214** id and pId2 is any empty string.
77215*/
77216SQLITE_PRIVATE void sqlite3Pragma(
77217  Parse *pParse,
77218  Token *pId1,        /* First part of [database.]id field */
77219  Token *pId2,        /* Second part of [database.]id field, or NULL */
77220  Token *pValue,      /* Token for <value>, or NULL */
77221  int minusFlag       /* True if a '-' sign preceded <value> */
77222){
77223  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
77224  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
77225  const char *zDb = 0;   /* The database name */
77226  Token *pId;            /* Pointer to <id> token */
77227  int iDb;               /* Database index for <database> */
77228  sqlite3 *db = pParse->db;
77229  Db *pDb;
77230  Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
77231  if( v==0 ) return;
77232  sqlite3VdbeRunOnlyOnce(v);
77233  pParse->nMem = 2;
77234
77235  /* Interpret the [database.] part of the pragma statement. iDb is the
77236  ** index of the database this pragma is being applied to in db.aDb[]. */
77237  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
77238  if( iDb<0 ) return;
77239  pDb = &db->aDb[iDb];
77240
77241  /* If the temp database has been explicitly named as part of the
77242  ** pragma, make sure it is open.
77243  */
77244  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
77245    return;
77246  }
77247
77248  zLeft = sqlite3NameFromToken(db, pId);
77249  if( !zLeft ) return;
77250  if( minusFlag ){
77251    zRight = sqlite3MPrintf(db, "-%T", pValue);
77252  }else{
77253    zRight = sqlite3NameFromToken(db, pValue);
77254  }
77255
77256  assert( pId2 );
77257  zDb = pId2->n>0 ? pDb->zName : 0;
77258  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
77259    goto pragma_out;
77260  }
77261
77262#ifndef SQLITE_OMIT_PAGER_PRAGMAS
77263  /*
77264  **  PRAGMA [database.]default_cache_size
77265  **  PRAGMA [database.]default_cache_size=N
77266  **
77267  ** The first form reports the current persistent setting for the
77268  ** page cache size.  The value returned is the maximum number of
77269  ** pages in the page cache.  The second form sets both the current
77270  ** page cache size value and the persistent page cache size value
77271  ** stored in the database file.
77272  **
77273  ** The default cache size is stored in meta-value 2 of page 1 of the
77274  ** database file.  The cache size is actually the absolute value of
77275  ** this memory location.  The sign of meta-value 2 determines the
77276  ** synchronous setting.  A negative value means synchronous is off
77277  ** and a positive value means synchronous is on.
77278  */
77279  if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
77280    static const VdbeOpList getCacheSize[] = {
77281      { OP_Transaction, 0, 0,        0},                         /* 0 */
77282      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
77283      { OP_IfPos,       1, 7,        0},
77284      { OP_Integer,     0, 2,        0},
77285      { OP_Subtract,    1, 2,        1},
77286      { OP_IfPos,       1, 7,        0},
77287      { OP_Integer,     0, 1,        0},                         /* 6 */
77288      { OP_ResultRow,   1, 1,        0},
77289    };
77290    int addr;
77291    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77292    sqlite3VdbeUsesBtree(v, iDb);
77293    if( !zRight ){
77294      sqlite3VdbeSetNumCols(v, 1);
77295      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
77296      pParse->nMem += 2;
77297      addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
77298      sqlite3VdbeChangeP1(v, addr, iDb);
77299      sqlite3VdbeChangeP1(v, addr+1, iDb);
77300      sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
77301    }else{
77302      int size = atoi(zRight);
77303      if( size<0 ) size = -size;
77304      sqlite3BeginWriteOperation(pParse, 0, iDb);
77305      sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
77306      sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, 2, BTREE_DEFAULT_CACHE_SIZE);
77307      addr = sqlite3VdbeAddOp2(v, OP_IfPos, 2, 0);
77308      sqlite3VdbeAddOp2(v, OP_Integer, -size, 1);
77309      sqlite3VdbeJumpHere(v, addr);
77310      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
77311      pDb->pSchema->cache_size = size;
77312      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
77313    }
77314  }else
77315
77316  /*
77317  **  PRAGMA [database.]page_size
77318  **  PRAGMA [database.]page_size=N
77319  **
77320  ** The first form reports the current setting for the
77321  ** database page size in bytes.  The second form sets the
77322  ** database page size value.  The value can only be set if
77323  ** the database has not yet been created.
77324  */
77325  if( sqlite3StrICmp(zLeft,"page_size")==0 ){
77326    Btree *pBt = pDb->pBt;
77327    assert( pBt!=0 );
77328    if( !zRight ){
77329      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
77330      returnSingleInt(pParse, "page_size", size);
77331    }else{
77332      /* Malloc may fail when setting the page-size, as there is an internal
77333      ** buffer that the pager module resizes using sqlite3_realloc().
77334      */
77335      db->nextPagesize = atoi(zRight);
77336      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
77337        db->mallocFailed = 1;
77338      }
77339    }
77340  }else
77341
77342  /*
77343  **  PRAGMA [database.]max_page_count
77344  **  PRAGMA [database.]max_page_count=N
77345  **
77346  ** The first form reports the current setting for the
77347  ** maximum number of pages in the database file.  The
77348  ** second form attempts to change this setting.  Both
77349  ** forms return the current setting.
77350  */
77351  if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
77352    Btree *pBt = pDb->pBt;
77353    int newMax = 0;
77354    assert( pBt!=0 );
77355    if( zRight ){
77356      newMax = atoi(zRight);
77357    }
77358    if( ALWAYS(pBt) ){
77359      newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
77360    }
77361    returnSingleInt(pParse, "max_page_count", newMax);
77362  }else
77363
77364  /*
77365  **  PRAGMA [database.]page_count
77366  **
77367  ** Return the number of pages in the specified database.
77368  */
77369  if( sqlite3StrICmp(zLeft,"page_count")==0 ){
77370    int iReg;
77371    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77372    sqlite3CodeVerifySchema(pParse, iDb);
77373    iReg = ++pParse->nMem;
77374    sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
77375    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
77376    sqlite3VdbeSetNumCols(v, 1);
77377    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "page_count", SQLITE_STATIC);
77378  }else
77379
77380  /*
77381  **  PRAGMA [database.]locking_mode
77382  **  PRAGMA [database.]locking_mode = (normal|exclusive)
77383  */
77384  if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
77385    const char *zRet = "normal";
77386    int eMode = getLockingMode(zRight);
77387
77388    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
77389      /* Simple "PRAGMA locking_mode;" statement. This is a query for
77390      ** the current default locking mode (which may be different to
77391      ** the locking-mode of the main database).
77392      */
77393      eMode = db->dfltLockMode;
77394    }else{
77395      Pager *pPager;
77396      if( pId2->n==0 ){
77397        /* This indicates that no database name was specified as part
77398        ** of the PRAGMA command. In this case the locking-mode must be
77399        ** set on all attached databases, as well as the main db file.
77400        **
77401        ** Also, the sqlite3.dfltLockMode variable is set so that
77402        ** any subsequently attached databases also use the specified
77403        ** locking mode.
77404        */
77405        int ii;
77406        assert(pDb==&db->aDb[0]);
77407        for(ii=2; ii<db->nDb; ii++){
77408          pPager = sqlite3BtreePager(db->aDb[ii].pBt);
77409          sqlite3PagerLockingMode(pPager, eMode);
77410        }
77411        db->dfltLockMode = (u8)eMode;
77412      }
77413      pPager = sqlite3BtreePager(pDb->pBt);
77414      eMode = sqlite3PagerLockingMode(pPager, eMode);
77415    }
77416
77417    assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
77418    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
77419      zRet = "exclusive";
77420    }
77421    sqlite3VdbeSetNumCols(v, 1);
77422    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
77423    sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
77424    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77425  }else
77426
77427  /*
77428  **  PRAGMA [database.]journal_mode
77429  **  PRAGMA [database.]journal_mode = (delete|persist|off|truncate|memory)
77430  */
77431  if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
77432    int eMode;
77433    static char * const azModeName[] = {
77434      "delete", "persist", "off", "truncate", "memory"
77435    };
77436
77437    if( zRight==0 ){
77438      eMode = PAGER_JOURNALMODE_QUERY;
77439    }else{
77440      int n = sqlite3Strlen30(zRight);
77441      eMode = sizeof(azModeName)/sizeof(azModeName[0]) - 1;
77442      while( eMode>=0 && sqlite3StrNICmp(zRight, azModeName[eMode], n)!=0 ){
77443        eMode--;
77444      }
77445    }
77446    if( pId2->n==0 && eMode==PAGER_JOURNALMODE_QUERY ){
77447      /* Simple "PRAGMA journal_mode;" statement. This is a query for
77448      ** the current default journal mode (which may be different to
77449      ** the journal-mode of the main database).
77450      */
77451      eMode = db->dfltJournalMode;
77452    }else{
77453      Pager *pPager;
77454      if( pId2->n==0 ){
77455        /* This indicates that no database name was specified as part
77456        ** of the PRAGMA command. In this case the journal-mode must be
77457        ** set on all attached databases, as well as the main db file.
77458        **
77459        ** Also, the sqlite3.dfltJournalMode variable is set so that
77460        ** any subsequently attached databases also use the specified
77461        ** journal mode.
77462        */
77463        int ii;
77464        assert(pDb==&db->aDb[0]);
77465        for(ii=1; ii<db->nDb; ii++){
77466          if( db->aDb[ii].pBt ){
77467            pPager = sqlite3BtreePager(db->aDb[ii].pBt);
77468            sqlite3PagerJournalMode(pPager, eMode);
77469          }
77470        }
77471        db->dfltJournalMode = (u8)eMode;
77472      }
77473      pPager = sqlite3BtreePager(pDb->pBt);
77474      eMode = sqlite3PagerJournalMode(pPager, eMode);
77475    }
77476    assert( eMode==PAGER_JOURNALMODE_DELETE
77477              || eMode==PAGER_JOURNALMODE_TRUNCATE
77478              || eMode==PAGER_JOURNALMODE_PERSIST
77479              || eMode==PAGER_JOURNALMODE_OFF
77480              || eMode==PAGER_JOURNALMODE_MEMORY );
77481    sqlite3VdbeSetNumCols(v, 1);
77482    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
77483    sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0,
77484           azModeName[eMode], P4_STATIC);
77485    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77486  }else
77487
77488  /*
77489  **  PRAGMA [database.]journal_size_limit
77490  **  PRAGMA [database.]journal_size_limit=N
77491  **
77492  ** Get or set the size limit on rollback journal files.
77493  */
77494  if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
77495    Pager *pPager = sqlite3BtreePager(pDb->pBt);
77496    i64 iLimit = -2;
77497    if( zRight ){
77498      sqlite3Atoi64(zRight, &iLimit);
77499      if( iLimit<-1 ) iLimit = -1;
77500    }
77501    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
77502    returnSingleInt(pParse, "journal_size_limit", iLimit);
77503  }else
77504
77505#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
77506
77507  /*
77508  **  PRAGMA [database.]auto_vacuum
77509  **  PRAGMA [database.]auto_vacuum=N
77510  **
77511  ** Get or set the value of the database 'auto-vacuum' parameter.
77512  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
77513  */
77514#ifndef SQLITE_OMIT_AUTOVACUUM
77515  if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
77516    Btree *pBt = pDb->pBt;
77517    assert( pBt!=0 );
77518    if( sqlite3ReadSchema(pParse) ){
77519      goto pragma_out;
77520    }
77521    if( !zRight ){
77522      int auto_vacuum;
77523      if( ALWAYS(pBt) ){
77524         auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
77525      }else{
77526         auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
77527      }
77528      returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
77529    }else{
77530      int eAuto = getAutoVacuum(zRight);
77531      assert( eAuto>=0 && eAuto<=2 );
77532      db->nextAutovac = (u8)eAuto;
77533      if( ALWAYS(eAuto>=0) ){
77534        /* Call SetAutoVacuum() to set initialize the internal auto and
77535        ** incr-vacuum flags. This is required in case this connection
77536        ** creates the database file. It is important that it is created
77537        ** as an auto-vacuum capable db.
77538        */
77539        int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
77540        if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
77541          /* When setting the auto_vacuum mode to either "full" or
77542          ** "incremental", write the value of meta[6] in the database
77543          ** file. Before writing to meta[6], check that meta[3] indicates
77544          ** that this really is an auto-vacuum capable database.
77545          */
77546          static const VdbeOpList setMeta6[] = {
77547            { OP_Transaction,    0,         1,                 0},    /* 0 */
77548            { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
77549            { OP_If,             1,         0,                 0},    /* 2 */
77550            { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
77551            { OP_Integer,        0,         1,                 0},    /* 4 */
77552            { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
77553          };
77554          int iAddr;
77555          iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
77556          sqlite3VdbeChangeP1(v, iAddr, iDb);
77557          sqlite3VdbeChangeP1(v, iAddr+1, iDb);
77558          sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
77559          sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
77560          sqlite3VdbeChangeP1(v, iAddr+5, iDb);
77561          sqlite3VdbeUsesBtree(v, iDb);
77562        }
77563      }
77564    }
77565  }else
77566#endif
77567
77568  /*
77569  **  PRAGMA [database.]incremental_vacuum(N)
77570  **
77571  ** Do N steps of incremental vacuuming on a database.
77572  */
77573#ifndef SQLITE_OMIT_AUTOVACUUM
77574  if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
77575    int iLimit, addr;
77576    if( sqlite3ReadSchema(pParse) ){
77577      goto pragma_out;
77578    }
77579    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
77580      iLimit = 0x7fffffff;
77581    }
77582    sqlite3BeginWriteOperation(pParse, 0, iDb);
77583    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
77584    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
77585    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
77586    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
77587    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
77588    sqlite3VdbeJumpHere(v, addr);
77589  }else
77590#endif
77591
77592#ifndef SQLITE_OMIT_PAGER_PRAGMAS
77593  /*
77594  **  PRAGMA [database.]cache_size
77595  **  PRAGMA [database.]cache_size=N
77596  **
77597  ** The first form reports the current local setting for the
77598  ** page cache size.  The local setting can be different from
77599  ** the persistent cache size value that is stored in the database
77600  ** file itself.  The value returned is the maximum number of
77601  ** pages in the page cache.  The second form sets the local
77602  ** page cache size value.  It does not change the persistent
77603  ** cache size stored on the disk so the cache size will revert
77604  ** to its default value when the database is closed and reopened.
77605  ** N should be a positive integer.
77606  */
77607  if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
77608    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77609    if( !zRight ){
77610      returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
77611    }else{
77612      int size = atoi(zRight);
77613      if( size<0 ) size = -size;
77614      pDb->pSchema->cache_size = size;
77615      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
77616    }
77617  }else
77618
77619  /*
77620  **   PRAGMA temp_store
77621  **   PRAGMA temp_store = "default"|"memory"|"file"
77622  **
77623  ** Return or set the local value of the temp_store flag.  Changing
77624  ** the local value does not make changes to the disk file and the default
77625  ** value will be restored the next time the database is opened.
77626  **
77627  ** Note that it is possible for the library compile-time options to
77628  ** override this setting
77629  */
77630  if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
77631    if( !zRight ){
77632      returnSingleInt(pParse, "temp_store", db->temp_store);
77633    }else{
77634      changeTempStorage(pParse, zRight);
77635    }
77636  }else
77637
77638  /*
77639  **   PRAGMA temp_store_directory
77640  **   PRAGMA temp_store_directory = ""|"directory_name"
77641  **
77642  ** Return or set the local value of the temp_store_directory flag.  Changing
77643  ** the value sets a specific directory to be used for temporary files.
77644  ** Setting to a null string reverts to the default temporary directory search.
77645  ** If temporary directory is changed, then invalidateTempStorage.
77646  **
77647  */
77648  if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
77649    if( !zRight ){
77650      if( sqlite3_temp_directory ){
77651        sqlite3VdbeSetNumCols(v, 1);
77652        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
77653            "temp_store_directory", SQLITE_STATIC);
77654        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
77655        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77656      }
77657    }else{
77658#ifndef SQLITE_OMIT_WSD
77659      if( zRight[0] ){
77660        int rc;
77661        int res;
77662        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
77663        if( rc!=SQLITE_OK || res==0 ){
77664          sqlite3ErrorMsg(pParse, "not a writable directory");
77665          goto pragma_out;
77666        }
77667      }
77668      if( SQLITE_TEMP_STORE==0
77669       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
77670       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
77671      ){
77672        invalidateTempStorage(pParse);
77673      }
77674      sqlite3_free(sqlite3_temp_directory);
77675      if( zRight[0] ){
77676        sqlite3_temp_directory = sqlite3DbStrDup(0, zRight);
77677      }else{
77678        sqlite3_temp_directory = 0;
77679      }
77680#endif /* SQLITE_OMIT_WSD */
77681    }
77682  }else
77683
77684#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
77685#  if defined(__APPLE__)
77686#    define SQLITE_ENABLE_LOCKING_STYLE 1
77687#  else
77688#    define SQLITE_ENABLE_LOCKING_STYLE 0
77689#  endif
77690#endif
77691#if SQLITE_ENABLE_LOCKING_STYLE
77692  /*
77693   **   PRAGMA [database.]lock_proxy_file
77694   **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
77695   **
77696   ** Return or set the value of the lock_proxy_file flag.  Changing
77697   ** the value sets a specific file to be used for database access locks.
77698   **
77699   */
77700  if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
77701    if( !zRight ){
77702      Pager *pPager = sqlite3BtreePager(pDb->pBt);
77703      char *proxy_file_path = NULL;
77704      sqlite3_file *pFile = sqlite3PagerFile(pPager);
77705      sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE,
77706                           &proxy_file_path);
77707
77708      if( proxy_file_path ){
77709        sqlite3VdbeSetNumCols(v, 1);
77710        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
77711                              "lock_proxy_file", SQLITE_STATIC);
77712        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
77713        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77714      }
77715    }else{
77716      Pager *pPager = sqlite3BtreePager(pDb->pBt);
77717      sqlite3_file *pFile = sqlite3PagerFile(pPager);
77718      int res;
77719      if( zRight[0] ){
77720        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
77721                                     zRight);
77722      } else {
77723        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
77724                                     NULL);
77725      }
77726      if( res!=SQLITE_OK ){
77727        sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
77728        goto pragma_out;
77729      }
77730    }
77731  }else
77732#endif /* SQLITE_ENABLE_LOCKING_STYLE */
77733
77734  /*
77735  **   PRAGMA [database.]synchronous
77736  **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
77737  **
77738  ** Return or set the local value of the synchronous flag.  Changing
77739  ** the local value does not make changes to the disk file and the
77740  ** default value will be restored the next time the database is
77741  ** opened.
77742  */
77743  if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
77744    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77745    if( !zRight ){
77746      returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
77747    }else{
77748      if( !db->autoCommit ){
77749        sqlite3ErrorMsg(pParse,
77750            "Safety level may not be changed inside a transaction");
77751      }else{
77752        pDb->safety_level = getSafetyLevel(zRight)+1;
77753      }
77754    }
77755  }else
77756#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
77757
77758#ifndef SQLITE_OMIT_FLAG_PRAGMAS
77759  if( flagPragma(pParse, zLeft, zRight) ){
77760    /* The flagPragma() subroutine also generates any necessary code
77761    ** there is nothing more to do here */
77762  }else
77763#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
77764
77765#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
77766  /*
77767  **   PRAGMA table_info(<table>)
77768  **
77769  ** Return a single row for each column of the named table. The columns of
77770  ** the returned data set are:
77771  **
77772  ** cid:        Column id (numbered from left to right, starting at 0)
77773  ** name:       Column name
77774  ** type:       Column declaration type.
77775  ** notnull:    True if 'NOT NULL' is part of column declaration
77776  ** dflt_value: The default value for the column, if any.
77777  */
77778  if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
77779    Table *pTab;
77780    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77781    pTab = sqlite3FindTable(db, zRight, zDb);
77782    if( pTab ){
77783      int i;
77784      int nHidden = 0;
77785      Column *pCol;
77786      sqlite3VdbeSetNumCols(v, 6);
77787      pParse->nMem = 6;
77788      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
77789      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
77790      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
77791      sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
77792      sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
77793      sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
77794      sqlite3ViewGetColumnNames(pParse, pTab);
77795      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
77796        if( IsHiddenColumn(pCol) ){
77797          nHidden++;
77798          continue;
77799        }
77800        sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
77801        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
77802        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
77803           pCol->zType ? pCol->zType : "", 0);
77804        sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
77805        if( pCol->zDflt ){
77806          sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
77807        }else{
77808          sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
77809        }
77810        sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
77811        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
77812      }
77813    }
77814  }else
77815
77816  if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
77817    Index *pIdx;
77818    Table *pTab;
77819    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77820    pIdx = sqlite3FindIndex(db, zRight, zDb);
77821    if( pIdx ){
77822      int i;
77823      pTab = pIdx->pTable;
77824      sqlite3VdbeSetNumCols(v, 3);
77825      pParse->nMem = 3;
77826      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
77827      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
77828      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
77829      for(i=0; i<pIdx->nColumn; i++){
77830        int cnum = pIdx->aiColumn[i];
77831        sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
77832        sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
77833        assert( pTab->nCol>cnum );
77834        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
77835        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
77836      }
77837    }
77838  }else
77839
77840  if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
77841    Index *pIdx;
77842    Table *pTab;
77843    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77844    pTab = sqlite3FindTable(db, zRight, zDb);
77845    if( pTab ){
77846      v = sqlite3GetVdbe(pParse);
77847      pIdx = pTab->pIndex;
77848      if( pIdx ){
77849        int i = 0;
77850        sqlite3VdbeSetNumCols(v, 3);
77851        pParse->nMem = 3;
77852        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
77853        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
77854        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
77855        while(pIdx){
77856          sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
77857          sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
77858          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
77859          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
77860          ++i;
77861          pIdx = pIdx->pNext;
77862        }
77863      }
77864    }
77865  }else
77866
77867  if( sqlite3StrICmp(zLeft, "database_list")==0 ){
77868    int i;
77869    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77870    sqlite3VdbeSetNumCols(v, 3);
77871    pParse->nMem = 3;
77872    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
77873    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
77874    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
77875    for(i=0; i<db->nDb; i++){
77876      if( db->aDb[i].pBt==0 ) continue;
77877      assert( db->aDb[i].zName!=0 );
77878      sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
77879      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
77880      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
77881           sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
77882      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
77883    }
77884  }else
77885
77886  if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
77887    int i = 0;
77888    HashElem *p;
77889    sqlite3VdbeSetNumCols(v, 2);
77890    pParse->nMem = 2;
77891    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
77892    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
77893    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
77894      CollSeq *pColl = (CollSeq *)sqliteHashData(p);
77895      sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
77896      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
77897      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
77898    }
77899  }else
77900#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
77901
77902#ifndef SQLITE_OMIT_FOREIGN_KEY
77903  if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
77904    FKey *pFK;
77905    Table *pTab;
77906    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77907    pTab = sqlite3FindTable(db, zRight, zDb);
77908    if( pTab ){
77909      v = sqlite3GetVdbe(pParse);
77910      pFK = pTab->pFKey;
77911      if( pFK ){
77912        int i = 0;
77913        sqlite3VdbeSetNumCols(v, 8);
77914        pParse->nMem = 8;
77915        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
77916        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
77917        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
77918        sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
77919        sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
77920        sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
77921        sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
77922        sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
77923        while(pFK){
77924          int j;
77925          for(j=0; j<pFK->nCol; j++){
77926            char *zCol = pFK->aCol[j].zCol;
77927            char *zOnDelete = (char *)actionName(pFK->aAction[0]);
77928            char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
77929            sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
77930            sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
77931            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
77932            sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
77933                              pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
77934            sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
77935            sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
77936            sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
77937            sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
77938            sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
77939          }
77940          ++i;
77941          pFK = pFK->pNextFrom;
77942        }
77943      }
77944    }
77945  }else
77946#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
77947
77948#ifndef NDEBUG
77949  if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
77950    if( zRight ){
77951      if( getBoolean(zRight) ){
77952        sqlite3ParserTrace(stderr, "parser: ");
77953      }else{
77954        sqlite3ParserTrace(0, 0);
77955      }
77956    }
77957  }else
77958#endif
77959
77960  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
77961  ** used will be case sensitive or not depending on the RHS.
77962  */
77963  if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
77964    if( zRight ){
77965      sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
77966    }
77967  }else
77968
77969#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
77970# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
77971#endif
77972
77973#ifndef SQLITE_OMIT_INTEGRITY_CHECK
77974  /* Pragma "quick_check" is an experimental reduced version of
77975  ** integrity_check designed to detect most database corruption
77976  ** without most of the overhead of a full integrity-check.
77977  */
77978  if( sqlite3StrICmp(zLeft, "integrity_check")==0
77979   || sqlite3StrICmp(zLeft, "quick_check")==0
77980  ){
77981    int i, j, addr, mxErr;
77982
77983    /* Code that appears at the end of the integrity check.  If no error
77984    ** messages have been generated, output OK.  Otherwise output the
77985    ** error message
77986    */
77987    static const VdbeOpList endCode[] = {
77988      { OP_AddImm,      1, 0,        0},    /* 0 */
77989      { OP_IfNeg,       1, 0,        0},    /* 1 */
77990      { OP_String8,     0, 3,        0},    /* 2 */
77991      { OP_ResultRow,   3, 1,        0},
77992    };
77993
77994    int isQuick = (zLeft[0]=='q');
77995
77996    /* Initialize the VDBE program */
77997    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77998    pParse->nMem = 6;
77999    sqlite3VdbeSetNumCols(v, 1);
78000    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
78001
78002    /* Set the maximum error count */
78003    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
78004    if( zRight ){
78005      mxErr = atoi(zRight);
78006      if( mxErr<=0 ){
78007        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
78008      }
78009    }
78010    sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
78011
78012    /* Do an integrity check on each database file */
78013    for(i=0; i<db->nDb; i++){
78014      HashElem *x;
78015      Hash *pTbls;
78016      int cnt = 0;
78017
78018      if( OMIT_TEMPDB && i==1 ) continue;
78019
78020      sqlite3CodeVerifySchema(pParse, i);
78021      addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
78022      sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
78023      sqlite3VdbeJumpHere(v, addr);
78024
78025      /* Do an integrity check of the B-Tree
78026      **
78027      ** Begin by filling registers 2, 3, ... with the root pages numbers
78028      ** for all tables and indices in the database.
78029      */
78030      pTbls = &db->aDb[i].pSchema->tblHash;
78031      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
78032        Table *pTab = sqliteHashData(x);
78033        Index *pIdx;
78034        sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
78035        cnt++;
78036        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
78037          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
78038          cnt++;
78039        }
78040      }
78041
78042      /* Make sure sufficient number of registers have been allocated */
78043      if( pParse->nMem < cnt+4 ){
78044        pParse->nMem = cnt+4;
78045      }
78046
78047      /* Do the b-tree integrity checks */
78048      sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
78049      sqlite3VdbeChangeP5(v, (u8)i);
78050      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
78051      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
78052         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
78053         P4_DYNAMIC);
78054      sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
78055      sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
78056      sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
78057      sqlite3VdbeJumpHere(v, addr);
78058
78059      /* Make sure all the indices are constructed correctly.
78060      */
78061      for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
78062        Table *pTab = sqliteHashData(x);
78063        Index *pIdx;
78064        int loopTop;
78065
78066        if( pTab->pIndex==0 ) continue;
78067        addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
78068        sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
78069        sqlite3VdbeJumpHere(v, addr);
78070        sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
78071        sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
78072        loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
78073        sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
78074        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
78075          int jmp2;
78076          int r1;
78077          static const VdbeOpList idxErr[] = {
78078            { OP_AddImm,      1, -1,  0},
78079            { OP_String8,     0,  3,  0},    /* 1 */
78080            { OP_Rowid,       1,  4,  0},
78081            { OP_String8,     0,  5,  0},    /* 3 */
78082            { OP_String8,     0,  6,  0},    /* 4 */
78083            { OP_Concat,      4,  3,  3},
78084            { OP_Concat,      5,  3,  3},
78085            { OP_Concat,      6,  3,  3},
78086            { OP_ResultRow,   3,  1,  0},
78087            { OP_IfPos,       1,  0,  0},    /* 9 */
78088            { OP_Halt,        0,  0,  0},
78089          };
78090          r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
78091          jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
78092          addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
78093          sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
78094          sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
78095          sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
78096          sqlite3VdbeJumpHere(v, addr+9);
78097          sqlite3VdbeJumpHere(v, jmp2);
78098        }
78099        sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
78100        sqlite3VdbeJumpHere(v, loopTop);
78101        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
78102          static const VdbeOpList cntIdx[] = {
78103             { OP_Integer,      0,  3,  0},
78104             { OP_Rewind,       0,  0,  0},  /* 1 */
78105             { OP_AddImm,       3,  1,  0},
78106             { OP_Next,         0,  0,  0},  /* 3 */
78107             { OP_Eq,           2,  0,  3},  /* 4 */
78108             { OP_AddImm,       1, -1,  0},
78109             { OP_String8,      0,  2,  0},  /* 6 */
78110             { OP_String8,      0,  3,  0},  /* 7 */
78111             { OP_Concat,       3,  2,  2},
78112             { OP_ResultRow,    2,  1,  0},
78113          };
78114          addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
78115          sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
78116          sqlite3VdbeJumpHere(v, addr);
78117          addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
78118          sqlite3VdbeChangeP1(v, addr+1, j+2);
78119          sqlite3VdbeChangeP2(v, addr+1, addr+4);
78120          sqlite3VdbeChangeP1(v, addr+3, j+2);
78121          sqlite3VdbeChangeP2(v, addr+3, addr+2);
78122          sqlite3VdbeJumpHere(v, addr+4);
78123          sqlite3VdbeChangeP4(v, addr+6,
78124                     "wrong # of entries in index ", P4_STATIC);
78125          sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
78126        }
78127      }
78128    }
78129    addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
78130    sqlite3VdbeChangeP2(v, addr, -mxErr);
78131    sqlite3VdbeJumpHere(v, addr+1);
78132    sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
78133  }else
78134#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
78135
78136#ifndef SQLITE_OMIT_UTF16
78137  /*
78138  **   PRAGMA encoding
78139  **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
78140  **
78141  ** In its first form, this pragma returns the encoding of the main
78142  ** database. If the database is not initialized, it is initialized now.
78143  **
78144  ** The second form of this pragma is a no-op if the main database file
78145  ** has not already been initialized. In this case it sets the default
78146  ** encoding that will be used for the main database file if a new file
78147  ** is created. If an existing main database file is opened, then the
78148  ** default text encoding for the existing database is used.
78149  **
78150  ** In all cases new databases created using the ATTACH command are
78151  ** created to use the same default text encoding as the main database. If
78152  ** the main database has not been initialized and/or created when ATTACH
78153  ** is executed, this is done before the ATTACH operation.
78154  **
78155  ** In the second form this pragma sets the text encoding to be used in
78156  ** new database files created using this database handle. It is only
78157  ** useful if invoked immediately after the main database i
78158  */
78159  if( sqlite3StrICmp(zLeft, "encoding")==0 ){
78160    static const struct EncName {
78161      char *zName;
78162      u8 enc;
78163    } encnames[] = {
78164      { "UTF8",     SQLITE_UTF8        },
78165      { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
78166      { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
78167      { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
78168      { "UTF16le",  SQLITE_UTF16LE     },
78169      { "UTF16be",  SQLITE_UTF16BE     },
78170      { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
78171      { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
78172      { 0, 0 }
78173    };
78174    const struct EncName *pEnc;
78175    if( !zRight ){    /* "PRAGMA encoding" */
78176      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
78177      sqlite3VdbeSetNumCols(v, 1);
78178      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
78179      sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
78180      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
78181      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
78182      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
78183      sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
78184      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
78185    }else{                        /* "PRAGMA encoding = XXX" */
78186      /* Only change the value of sqlite.enc if the database handle is not
78187      ** initialized. If the main database exists, the new sqlite.enc value
78188      ** will be overwritten when the schema is next loaded. If it does not
78189      ** already exists, it will be created to use the new encoding value.
78190      */
78191      if(
78192        !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
78193        DbHasProperty(db, 0, DB_Empty)
78194      ){
78195        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
78196          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
78197            ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
78198            break;
78199          }
78200        }
78201        if( !pEnc->zName ){
78202          sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
78203        }
78204      }
78205    }
78206  }else
78207#endif /* SQLITE_OMIT_UTF16 */
78208
78209#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
78210  /*
78211  **   PRAGMA [database.]schema_version
78212  **   PRAGMA [database.]schema_version = <integer>
78213  **
78214  **   PRAGMA [database.]user_version
78215  **   PRAGMA [database.]user_version = <integer>
78216  **
78217  ** The pragma's schema_version and user_version are used to set or get
78218  ** the value of the schema-version and user-version, respectively. Both
78219  ** the schema-version and the user-version are 32-bit signed integers
78220  ** stored in the database header.
78221  **
78222  ** The schema-cookie is usually only manipulated internally by SQLite. It
78223  ** is incremented by SQLite whenever the database schema is modified (by
78224  ** creating or dropping a table or index). The schema version is used by
78225  ** SQLite each time a query is executed to ensure that the internal cache
78226  ** of the schema used when compiling the SQL query matches the schema of
78227  ** the database against which the compiled query is actually executed.
78228  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
78229  ** the schema-version is potentially dangerous and may lead to program
78230  ** crashes or database corruption. Use with caution!
78231  **
78232  ** The user-version is not used internally by SQLite. It may be used by
78233  ** applications for any purpose.
78234  */
78235  if( sqlite3StrICmp(zLeft, "schema_version")==0
78236   || sqlite3StrICmp(zLeft, "user_version")==0
78237   || sqlite3StrICmp(zLeft, "freelist_count")==0
78238  ){
78239    int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
78240    sqlite3VdbeUsesBtree(v, iDb);
78241    switch( zLeft[0] ){
78242      case 'f': case 'F':
78243        iCookie = BTREE_FREE_PAGE_COUNT;
78244        break;
78245      case 's': case 'S':
78246        iCookie = BTREE_SCHEMA_VERSION;
78247        break;
78248      default:
78249        iCookie = BTREE_USER_VERSION;
78250        break;
78251    }
78252
78253    if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
78254      /* Write the specified cookie value */
78255      static const VdbeOpList setCookie[] = {
78256        { OP_Transaction,    0,  1,  0},    /* 0 */
78257        { OP_Integer,        0,  1,  0},    /* 1 */
78258        { OP_SetCookie,      0,  0,  1},    /* 2 */
78259      };
78260      int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
78261      sqlite3VdbeChangeP1(v, addr, iDb);
78262      sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
78263      sqlite3VdbeChangeP1(v, addr+2, iDb);
78264      sqlite3VdbeChangeP2(v, addr+2, iCookie);
78265    }else{
78266      /* Read the specified cookie value */
78267      static const VdbeOpList readCookie[] = {
78268        { OP_Transaction,     0,  0,  0},    /* 0 */
78269        { OP_ReadCookie,      0,  1,  0},    /* 1 */
78270        { OP_ResultRow,       1,  1,  0}
78271      };
78272      int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
78273      sqlite3VdbeChangeP1(v, addr, iDb);
78274      sqlite3VdbeChangeP1(v, addr+1, iDb);
78275      sqlite3VdbeChangeP3(v, addr+1, iCookie);
78276      sqlite3VdbeSetNumCols(v, 1);
78277      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
78278    }
78279  }else
78280#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
78281
78282#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
78283  /*
78284  ** Report the current state of file logs for all databases
78285  */
78286  if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
78287    static const char *const azLockName[] = {
78288      "unlocked", "shared", "reserved", "pending", "exclusive"
78289    };
78290    int i;
78291    sqlite3VdbeSetNumCols(v, 2);
78292    pParse->nMem = 2;
78293    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
78294    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
78295    for(i=0; i<db->nDb; i++){
78296      Btree *pBt;
78297      Pager *pPager;
78298      const char *zState = "unknown";
78299      int j;
78300      if( db->aDb[i].zName==0 ) continue;
78301      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
78302      pBt = db->aDb[i].pBt;
78303      if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
78304        zState = "closed";
78305      }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
78306                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
78307         zState = azLockName[j];
78308      }
78309      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
78310      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
78311    }
78312
78313  }else
78314#endif
78315
78316#if SQLITE_HAS_CODEC
78317  if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
78318    sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
78319  }else
78320  if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
78321    sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
78322  }else
78323  if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
78324                 sqlite3StrICmp(zLeft, "hexrekey")==0) ){
78325    int i, h1, h2;
78326    char zKey[40];
78327    for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
78328      h1 += 9*(1&(h1>>6));
78329      h2 += 9*(1&(h2>>6));
78330      zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
78331    }
78332    if( (zLeft[3] & 0xf)==0xb ){
78333      sqlite3_key(db, zKey, i/2);
78334    }else{
78335      sqlite3_rekey(db, zKey, i/2);
78336    }
78337  }else
78338#endif
78339#if SQLITE_HAS_CODEC || defined(SQLITE_ENABLE_CEROD)
78340  if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
78341#if SQLITE_HAS_CODEC
78342    if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
78343      extern void sqlite3_activate_see(const char*);
78344      sqlite3_activate_see(&zRight[4]);
78345    }
78346#endif
78347#ifdef SQLITE_ENABLE_CEROD
78348    if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
78349      extern void sqlite3_activate_cerod(const char*);
78350      sqlite3_activate_cerod(&zRight[6]);
78351    }
78352#endif
78353  }else
78354#endif
78355
78356
78357  {/* Empty ELSE clause */}
78358
78359  /*
78360  ** Reset the safety level, in case the fullfsync flag or synchronous
78361  ** setting changed.
78362  */
78363#ifndef SQLITE_OMIT_PAGER_PRAGMAS
78364  if( db->autoCommit ){
78365    sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
78366               (db->flags&SQLITE_FullFSync)!=0);
78367  }
78368#endif
78369pragma_out:
78370  sqlite3DbFree(db, zLeft);
78371  sqlite3DbFree(db, zRight);
78372}
78373
78374#endif /* SQLITE_OMIT_PRAGMA */
78375
78376/************** End of pragma.c **********************************************/
78377/************** Begin file prepare.c *****************************************/
78378/*
78379** 2005 May 25
78380**
78381** The author disclaims copyright to this source code.  In place of
78382** a legal notice, here is a blessing:
78383**
78384**    May you do good and not evil.
78385**    May you find forgiveness for yourself and forgive others.
78386**    May you share freely, never taking more than you give.
78387**
78388*************************************************************************
78389** This file contains the implementation of the sqlite3_prepare()
78390** interface, and routines that contribute to loading the database schema
78391** from disk.
78392*/
78393
78394/*
78395** Fill the InitData structure with an error message that indicates
78396** that the database is corrupt.
78397*/
78398static void corruptSchema(
78399  InitData *pData,     /* Initialization context */
78400  const char *zObj,    /* Object being parsed at the point of error */
78401  const char *zExtra   /* Error information */
78402){
78403  sqlite3 *db = pData->db;
78404  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
78405    if( zObj==0 ) zObj = "?";
78406    sqlite3SetString(pData->pzErrMsg, db,
78407      "malformed database schema (%s)", zObj);
78408    if( zExtra ){
78409      *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
78410                                 "%s - %s", *pData->pzErrMsg, zExtra);
78411    }
78412  }
78413  pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT;
78414}
78415
78416/*
78417** This is the callback routine for the code that initializes the
78418** database.  See sqlite3Init() below for additional information.
78419** This routine is also called from the OP_ParseSchema opcode of the VDBE.
78420**
78421** Each callback contains the following information:
78422**
78423**     argv[0] = name of thing being created
78424**     argv[1] = root page number for table or index. 0 for trigger or view.
78425**     argv[2] = SQL text for the CREATE statement.
78426**
78427*/
78428SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
78429  InitData *pData = (InitData*)pInit;
78430  sqlite3 *db = pData->db;
78431  int iDb = pData->iDb;
78432
78433  assert( argc==3 );
78434  UNUSED_PARAMETER2(NotUsed, argc);
78435  assert( sqlite3_mutex_held(db->mutex) );
78436  DbClearProperty(db, iDb, DB_Empty);
78437  if( db->mallocFailed ){
78438    corruptSchema(pData, argv[0], 0);
78439    return 1;
78440  }
78441
78442  assert( iDb>=0 && iDb<db->nDb );
78443  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
78444  if( argv[1]==0 ){
78445    corruptSchema(pData, argv[0], 0);
78446  }else if( argv[2] && argv[2][0] ){
78447    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
78448    ** But because db->init.busy is set to 1, no VDBE code is generated
78449    ** or executed.  All the parser does is build the internal data
78450    ** structures that describe the table, index, or view.
78451    */
78452    char *zErr;
78453    int rc;
78454    assert( db->init.busy );
78455    db->init.iDb = iDb;
78456    db->init.newTnum = atoi(argv[1]);
78457    db->init.orphanTrigger = 0;
78458    rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
78459    db->init.iDb = 0;
78460    assert( rc!=SQLITE_OK || zErr==0 );
78461    if( SQLITE_OK!=rc ){
78462      if( db->init.orphanTrigger ){
78463        assert( iDb==1 );
78464      }else{
78465        pData->rc = rc;
78466        if( rc==SQLITE_NOMEM ){
78467          db->mallocFailed = 1;
78468        }else if( rc!=SQLITE_INTERRUPT && rc!=SQLITE_LOCKED ){
78469          corruptSchema(pData, argv[0], zErr);
78470        }
78471      }
78472      sqlite3DbFree(db, zErr);
78473    }
78474  }else if( argv[0]==0 ){
78475    corruptSchema(pData, 0, 0);
78476  }else{
78477    /* If the SQL column is blank it means this is an index that
78478    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
78479    ** constraint for a CREATE TABLE.  The index should have already
78480    ** been created when we processed the CREATE TABLE.  All we have
78481    ** to do here is record the root page number for that index.
78482    */
78483    Index *pIndex;
78484    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
78485    if( pIndex==0 ){
78486      /* This can occur if there exists an index on a TEMP table which
78487      ** has the same name as another index on a permanent index.  Since
78488      ** the permanent table is hidden by the TEMP table, we can also
78489      ** safely ignore the index on the permanent table.
78490      */
78491      /* Do Nothing */;
78492    }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
78493      corruptSchema(pData, argv[0], "invalid rootpage");
78494    }
78495  }
78496  return 0;
78497}
78498
78499/*
78500** Attempt to read the database schema and initialize internal
78501** data structures for a single database file.  The index of the
78502** database file is given by iDb.  iDb==0 is used for the main
78503** database.  iDb==1 should never be used.  iDb>=2 is used for
78504** auxiliary databases.  Return one of the SQLITE_ error codes to
78505** indicate success or failure.
78506*/
78507static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
78508  int rc;
78509  int i;
78510  int size;
78511  Table *pTab;
78512  Db *pDb;
78513  char const *azArg[4];
78514  int meta[5];
78515  InitData initData;
78516  char const *zMasterSchema;
78517  char const *zMasterName = SCHEMA_TABLE(iDb);
78518  int openedTransaction = 0;
78519
78520  /*
78521  ** The master database table has a structure like this
78522  */
78523  static const char master_schema[] =
78524     "CREATE TABLE sqlite_master(\n"
78525     "  type text,\n"
78526     "  name text,\n"
78527     "  tbl_name text,\n"
78528     "  rootpage integer,\n"
78529     "  sql text\n"
78530     ")"
78531  ;
78532#ifndef SQLITE_OMIT_TEMPDB
78533  static const char temp_master_schema[] =
78534     "CREATE TEMP TABLE sqlite_temp_master(\n"
78535     "  type text,\n"
78536     "  name text,\n"
78537     "  tbl_name text,\n"
78538     "  rootpage integer,\n"
78539     "  sql text\n"
78540     ")"
78541  ;
78542#else
78543  #define temp_master_schema 0
78544#endif
78545
78546  assert( iDb>=0 && iDb<db->nDb );
78547  assert( db->aDb[iDb].pSchema );
78548  assert( sqlite3_mutex_held(db->mutex) );
78549  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
78550
78551  /* zMasterSchema and zInitScript are set to point at the master schema
78552  ** and initialisation script appropriate for the database being
78553  ** initialised. zMasterName is the name of the master table.
78554  */
78555  if( !OMIT_TEMPDB && iDb==1 ){
78556    zMasterSchema = temp_master_schema;
78557  }else{
78558    zMasterSchema = master_schema;
78559  }
78560  zMasterName = SCHEMA_TABLE(iDb);
78561
78562  /* Construct the schema tables.  */
78563  azArg[0] = zMasterName;
78564  azArg[1] = "1";
78565  azArg[2] = zMasterSchema;
78566  azArg[3] = 0;
78567  initData.db = db;
78568  initData.iDb = iDb;
78569  initData.rc = SQLITE_OK;
78570  initData.pzErrMsg = pzErrMsg;
78571  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
78572  if( initData.rc ){
78573    rc = initData.rc;
78574    goto error_out;
78575  }
78576  pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
78577  if( ALWAYS(pTab) ){
78578    pTab->tabFlags |= TF_Readonly;
78579  }
78580
78581  /* Create a cursor to hold the database open
78582  */
78583  pDb = &db->aDb[iDb];
78584  if( pDb->pBt==0 ){
78585    if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
78586      DbSetProperty(db, 1, DB_SchemaLoaded);
78587    }
78588    return SQLITE_OK;
78589  }
78590
78591  /* If there is not already a read-only (or read-write) transaction opened
78592  ** on the b-tree database, open one now. If a transaction is opened, it
78593  ** will be closed before this function returns.  */
78594  sqlite3BtreeEnter(pDb->pBt);
78595  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
78596    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
78597    if( rc!=SQLITE_OK ){
78598      sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
78599      goto initone_error_out;
78600    }
78601    openedTransaction = 1;
78602  }
78603
78604  /* Get the database meta information.
78605  **
78606  ** Meta values are as follows:
78607  **    meta[0]   Schema cookie.  Changes with each schema change.
78608  **    meta[1]   File format of schema layer.
78609  **    meta[2]   Size of the page cache.
78610  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
78611  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
78612  **    meta[5]   User version
78613  **    meta[6]   Incremental vacuum mode
78614  **    meta[7]   unused
78615  **    meta[8]   unused
78616  **    meta[9]   unused
78617  **
78618  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
78619  ** the possible values of meta[4].
78620  */
78621  for(i=0; i<ArraySize(meta); i++){
78622    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
78623  }
78624  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
78625
78626  /* If opening a non-empty database, check the text encoding. For the
78627  ** main database, set sqlite3.enc to the encoding of the main database.
78628  ** For an attached db, it is an error if the encoding is not the same
78629  ** as sqlite3.enc.
78630  */
78631  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
78632    if( iDb==0 ){
78633      u8 encoding;
78634      /* If opening the main database, set ENC(db). */
78635      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
78636      if( encoding==0 ) encoding = SQLITE_UTF8;
78637      ENC(db) = encoding;
78638      db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
78639    }else{
78640      /* If opening an attached database, the encoding much match ENC(db) */
78641      if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
78642        sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
78643            " text encoding as main database");
78644        rc = SQLITE_ERROR;
78645        goto initone_error_out;
78646      }
78647    }
78648  }else{
78649    DbSetProperty(db, iDb, DB_Empty);
78650  }
78651  pDb->pSchema->enc = ENC(db);
78652
78653  if( pDb->pSchema->cache_size==0 ){
78654    size = meta[BTREE_DEFAULT_CACHE_SIZE-1];
78655    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
78656    if( size<0 ) size = -size;
78657    pDb->pSchema->cache_size = size;
78658    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
78659  }
78660
78661  /*
78662  ** file_format==1    Version 3.0.0.
78663  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
78664  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
78665  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
78666  */
78667  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
78668  if( pDb->pSchema->file_format==0 ){
78669    pDb->pSchema->file_format = 1;
78670  }
78671  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
78672    sqlite3SetString(pzErrMsg, db, "unsupported file format");
78673    rc = SQLITE_CORRUPT_BKPT; // Android Change from "rc = SQLITE_ERROR;"
78674    goto initone_error_out;
78675  }
78676
78677  /* Ticket #2804:  When we open a database in the newer file format,
78678  ** clear the legacy_file_format pragma flag so that a VACUUM will
78679  ** not downgrade the database and thus invalidate any descending
78680  ** indices that the user might have created.
78681  */
78682  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
78683    db->flags &= ~SQLITE_LegacyFileFmt;
78684  }
78685
78686  /* Read the schema information out of the schema tables
78687  */
78688  assert( db->init.busy );
78689  {
78690    char *zSql;
78691    zSql = sqlite3MPrintf(db,
78692        "SELECT name, rootpage, sql FROM '%q'.%s",
78693        db->aDb[iDb].zName, zMasterName);
78694#ifndef SQLITE_OMIT_AUTHORIZATION
78695    {
78696      int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
78697      xAuth = db->xAuth;
78698      db->xAuth = 0;
78699#endif
78700      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
78701#ifndef SQLITE_OMIT_AUTHORIZATION
78702      db->xAuth = xAuth;
78703    }
78704#endif
78705    if( rc==SQLITE_OK ) rc = initData.rc;
78706    sqlite3DbFree(db, zSql);
78707#ifndef SQLITE_OMIT_ANALYZE
78708    if( rc==SQLITE_OK ){
78709      sqlite3AnalysisLoad(db, iDb);
78710    }
78711#endif
78712  }
78713  if( db->mallocFailed ){
78714    rc = SQLITE_NOMEM;
78715    sqlite3ResetInternalSchema(db, 0);
78716  }
78717  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
78718    /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
78719    ** the schema loaded, even if errors occurred. In this situation the
78720    ** current sqlite3_prepare() operation will fail, but the following one
78721    ** will attempt to compile the supplied statement against whatever subset
78722    ** of the schema was loaded before the error occurred. The primary
78723    ** purpose of this is to allow access to the sqlite_master table
78724    ** even when its contents have been corrupted.
78725    */
78726    DbSetProperty(db, iDb, DB_SchemaLoaded);
78727    rc = SQLITE_OK;
78728  }
78729
78730  /* Jump here for an error that occurs after successfully allocating
78731  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
78732  ** before that point, jump to error_out.
78733  */
78734initone_error_out:
78735  if( openedTransaction ){
78736    sqlite3BtreeCommit(pDb->pBt);
78737  }
78738  sqlite3BtreeLeave(pDb->pBt);
78739
78740error_out:
78741  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
78742    db->mallocFailed = 1;
78743  }
78744  return rc;
78745}
78746
78747/*
78748** Initialize all database files - the main database file, the file
78749** used to store temporary tables, and any additional database files
78750** created using ATTACH statements.  Return a success code.  If an
78751** error occurs, write an error message into *pzErrMsg.
78752**
78753** After a database is initialized, the DB_SchemaLoaded bit is set
78754** bit is set in the flags field of the Db structure. If the database
78755** file was of zero-length, then the DB_Empty flag is also set.
78756*/
78757SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
78758  int i, rc;
78759  int commit_internal = !(db->flags&SQLITE_InternChanges);
78760
78761  assert( sqlite3_mutex_held(db->mutex) );
78762  rc = SQLITE_OK;
78763  db->init.busy = 1;
78764  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
78765    if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
78766    rc = sqlite3InitOne(db, i, pzErrMsg);
78767    if( rc ){
78768      sqlite3ResetInternalSchema(db, i);
78769    }
78770  }
78771
78772  /* Once all the other databases have been initialised, load the schema
78773  ** for the TEMP database. This is loaded last, as the TEMP database
78774  ** schema may contain references to objects in other databases.
78775  */
78776#ifndef SQLITE_OMIT_TEMPDB
78777  if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
78778                    && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
78779    rc = sqlite3InitOne(db, 1, pzErrMsg);
78780    if( rc ){
78781      sqlite3ResetInternalSchema(db, 1);
78782    }
78783  }
78784#endif
78785
78786  db->init.busy = 0;
78787  if( rc==SQLITE_OK && commit_internal ){
78788    sqlite3CommitInternalChanges(db);
78789  }
78790
78791  return rc;
78792}
78793
78794/*
78795** This routine is a no-op if the database schema is already initialised.
78796** Otherwise, the schema is loaded. An error code is returned.
78797*/
78798SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
78799  int rc = SQLITE_OK;
78800  sqlite3 *db = pParse->db;
78801  assert( sqlite3_mutex_held(db->mutex) );
78802  if( !db->init.busy ){
78803    rc = sqlite3Init(db, &pParse->zErrMsg);
78804  }
78805  if( rc!=SQLITE_OK ){
78806    pParse->rc = rc;
78807    pParse->nErr++;
78808  }
78809  return rc;
78810}
78811
78812
78813/*
78814** Check schema cookies in all databases.  If any cookie is out
78815** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
78816** make no changes to pParse->rc.
78817*/
78818static void schemaIsValid(Parse *pParse){
78819  sqlite3 *db = pParse->db;
78820  int iDb;
78821  int rc;
78822  int cookie;
78823
78824  assert( pParse->checkSchema );
78825  assert( sqlite3_mutex_held(db->mutex) );
78826  for(iDb=0; iDb<db->nDb; iDb++){
78827    int openedTransaction = 0;         /* True if a transaction is opened */
78828    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
78829    if( pBt==0 ) continue;
78830
78831    /* If there is not already a read-only (or read-write) transaction opened
78832    ** on the b-tree database, open one now. If a transaction is opened, it
78833    ** will be closed immediately after reading the meta-value. */
78834    if( !sqlite3BtreeIsInReadTrans(pBt) ){
78835      rc = sqlite3BtreeBeginTrans(pBt, 0);
78836      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
78837        db->mallocFailed = 1;
78838      }
78839      if( rc!=SQLITE_OK ) return;
78840      openedTransaction = 1;
78841    }
78842
78843    /* Read the schema cookie from the database. If it does not match the
78844    ** value stored as part of the in-memory schema representation,
78845    ** set Parse.rc to SQLITE_SCHEMA. */
78846    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
78847    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
78848      pParse->rc = SQLITE_SCHEMA;
78849    }
78850
78851    /* Close the transaction, if one was opened. */
78852    if( openedTransaction ){
78853      sqlite3BtreeCommit(pBt);
78854    }
78855  }
78856}
78857
78858/*
78859** Convert a schema pointer into the iDb index that indicates
78860** which database file in db->aDb[] the schema refers to.
78861**
78862** If the same database is attached more than once, the first
78863** attached database is returned.
78864*/
78865SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
78866  int i = -1000000;
78867
78868  /* If pSchema is NULL, then return -1000000. This happens when code in
78869  ** expr.c is trying to resolve a reference to a transient table (i.e. one
78870  ** created by a sub-select). In this case the return value of this
78871  ** function should never be used.
78872  **
78873  ** We return -1000000 instead of the more usual -1 simply because using
78874  ** -1000000 as the incorrect index into db->aDb[] is much
78875  ** more likely to cause a segfault than -1 (of course there are assert()
78876  ** statements too, but it never hurts to play the odds).
78877  */
78878  assert( sqlite3_mutex_held(db->mutex) );
78879  if( pSchema ){
78880    for(i=0; ALWAYS(i<db->nDb); i++){
78881      if( db->aDb[i].pSchema==pSchema ){
78882        break;
78883      }
78884    }
78885    assert( i>=0 && i<db->nDb );
78886  }
78887  return i;
78888}
78889
78890/*
78891** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
78892*/
78893static int sqlite3Prepare(
78894  sqlite3 *db,              /* Database handle. */
78895  const char *zSql,         /* UTF-8 encoded SQL statement. */
78896  int nBytes,               /* Length of zSql in bytes. */
78897  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
78898  Vdbe *pReprepare,         /* VM being reprepared */
78899  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
78900  const char **pzTail       /* OUT: End of parsed string */
78901){
78902  Parse *pParse;            /* Parsing context */
78903  char *zErrMsg = 0;        /* Error message */
78904  int rc = SQLITE_OK;       /* Result code */
78905  int i;                    /* Loop counter */
78906
78907  /* Allocate the parsing context */
78908  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
78909  if( pParse==0 ){
78910    rc = SQLITE_NOMEM;
78911    goto end_prepare;
78912  }
78913  pParse->pReprepare = pReprepare;
78914  assert( ppStmt && *ppStmt==0 );
78915  assert( !db->mallocFailed );
78916  assert( sqlite3_mutex_held(db->mutex) );
78917
78918  /* Check to verify that it is possible to get a read lock on all
78919  ** database schemas.  The inability to get a read lock indicates that
78920  ** some other database connection is holding a write-lock, which in
78921  ** turn means that the other connection has made uncommitted changes
78922  ** to the schema.
78923  **
78924  ** Were we to proceed and prepare the statement against the uncommitted
78925  ** schema changes and if those schema changes are subsequently rolled
78926  ** back and different changes are made in their place, then when this
78927  ** prepared statement goes to run the schema cookie would fail to detect
78928  ** the schema change.  Disaster would follow.
78929  **
78930  ** This thread is currently holding mutexes on all Btrees (because
78931  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
78932  ** is not possible for another thread to start a new schema change
78933  ** while this routine is running.  Hence, we do not need to hold
78934  ** locks on the schema, we just need to make sure nobody else is
78935  ** holding them.
78936  **
78937  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
78938  ** but it does *not* override schema lock detection, so this all still
78939  ** works even if READ_UNCOMMITTED is set.
78940  */
78941  for(i=0; i<db->nDb; i++) {
78942    Btree *pBt = db->aDb[i].pBt;
78943    if( pBt ){
78944      assert( sqlite3BtreeHoldsMutex(pBt) );
78945      rc = sqlite3BtreeSchemaLocked(pBt);
78946      if( rc ){
78947        const char *zDb = db->aDb[i].zName;
78948        sqlite3Error(db, rc, "database schema is locked: %s", zDb);
78949        testcase( db->flags & SQLITE_ReadUncommitted );
78950        goto end_prepare;
78951      }
78952    }
78953  }
78954
78955  sqlite3VtabUnlockList(db);
78956
78957  pParse->db = db;
78958  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
78959    char *zSqlCopy;
78960    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
78961    testcase( nBytes==mxLen );
78962    testcase( nBytes==mxLen+1 );
78963    if( nBytes>mxLen ){
78964      sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
78965      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
78966      goto end_prepare;
78967    }
78968    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
78969    if( zSqlCopy ){
78970      sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
78971      sqlite3DbFree(db, zSqlCopy);
78972      pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
78973    }else{
78974      pParse->zTail = &zSql[nBytes];
78975    }
78976  }else{
78977    sqlite3RunParser(pParse, zSql, &zErrMsg);
78978  }
78979
78980  if( db->mallocFailed ){
78981    pParse->rc = SQLITE_NOMEM;
78982  }
78983  if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
78984  if( pParse->checkSchema ){
78985    schemaIsValid(pParse);
78986  }
78987  if( pParse->rc==SQLITE_SCHEMA ){
78988    sqlite3ResetInternalSchema(db, 0);
78989  }
78990  if( db->mallocFailed ){
78991    pParse->rc = SQLITE_NOMEM;
78992  }
78993  if( pzTail ){
78994    *pzTail = pParse->zTail;
78995  }
78996  rc = pParse->rc;
78997
78998#ifndef SQLITE_OMIT_EXPLAIN
78999  if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
79000    static const char * const azColName[] = {
79001       "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
79002       "order", "from", "detail"
79003    };
79004    int iFirst, mx;
79005    if( pParse->explain==2 ){
79006      sqlite3VdbeSetNumCols(pParse->pVdbe, 3);
79007      iFirst = 8;
79008      mx = 11;
79009    }else{
79010      sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
79011      iFirst = 0;
79012      mx = 8;
79013    }
79014    for(i=iFirst; i<mx; i++){
79015      sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
79016                            azColName[i], SQLITE_STATIC);
79017    }
79018  }
79019#endif
79020
79021  assert( db->init.busy==0 || saveSqlFlag==0 );
79022  if( db->init.busy==0 ){
79023    Vdbe *pVdbe = pParse->pVdbe;
79024    sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
79025  }
79026  if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
79027    sqlite3VdbeFinalize(pParse->pVdbe);
79028    assert(!(*ppStmt));
79029  }else{
79030    *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
79031  }
79032
79033  if( zErrMsg ){
79034    sqlite3Error(db, rc, "%s", zErrMsg);
79035    sqlite3DbFree(db, zErrMsg);
79036  }else{
79037    sqlite3Error(db, rc, 0);
79038  }
79039
79040  /* Delete any TriggerPrg structures allocated while parsing this statement. */
79041  while( pParse->pTriggerPrg ){
79042    TriggerPrg *pT = pParse->pTriggerPrg;
79043    pParse->pTriggerPrg = pT->pNext;
79044    sqlite3VdbeProgramDelete(db, pT->pProgram, 0);
79045    sqlite3DbFree(db, pT);
79046  }
79047
79048end_prepare:
79049
79050  sqlite3StackFree(db, pParse);
79051  rc = sqlite3ApiExit(db, rc);
79052  assert( (rc&db->errMask)==rc );
79053  return rc;
79054}
79055static int sqlite3LockAndPrepare(
79056  sqlite3 *db,              /* Database handle. */
79057  const char *zSql,         /* UTF-8 encoded SQL statement. */
79058  int nBytes,               /* Length of zSql in bytes. */
79059  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
79060  Vdbe *pOld,               /* VM being reprepared */
79061  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
79062  const char **pzTail       /* OUT: End of parsed string */
79063){
79064  int rc;
79065  assert( ppStmt!=0 );
79066  *ppStmt = 0;
79067  if( !sqlite3SafetyCheckOk(db) ){
79068    return SQLITE_MISUSE_BKPT;
79069  }
79070  sqlite3_mutex_enter(db->mutex);
79071  sqlite3BtreeEnterAll(db);
79072  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
79073  if( rc==SQLITE_SCHEMA ){
79074    sqlite3_finalize(*ppStmt);
79075    rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
79076  }
79077  sqlite3BtreeLeaveAll(db);
79078  sqlite3_mutex_leave(db->mutex);
79079  return rc;
79080}
79081
79082/*
79083** Rerun the compilation of a statement after a schema change.
79084**
79085** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
79086** if the statement cannot be recompiled because another connection has
79087** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
79088** occurs, return SQLITE_SCHEMA.
79089*/
79090SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
79091  int rc;
79092  sqlite3_stmt *pNew;
79093  const char *zSql;
79094  sqlite3 *db;
79095
79096  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
79097  zSql = sqlite3_sql((sqlite3_stmt *)p);
79098  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
79099  db = sqlite3VdbeDb(p);
79100  assert( sqlite3_mutex_held(db->mutex) );
79101  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
79102  if( rc ){
79103    if( rc==SQLITE_NOMEM ){
79104      db->mallocFailed = 1;
79105    }
79106    assert( pNew==0 );
79107    return rc;
79108  }else{
79109    assert( pNew!=0 );
79110  }
79111  sqlite3VdbeSwap((Vdbe*)pNew, p);
79112  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
79113  sqlite3VdbeResetStepResult((Vdbe*)pNew);
79114  sqlite3VdbeFinalize((Vdbe*)pNew);
79115  return SQLITE_OK;
79116}
79117
79118
79119/*
79120** Two versions of the official API.  Legacy and new use.  In the legacy
79121** version, the original SQL text is not saved in the prepared statement
79122** and so if a schema change occurs, SQLITE_SCHEMA is returned by
79123** sqlite3_step().  In the new version, the original SQL text is retained
79124** and the statement is automatically recompiled if an schema change
79125** occurs.
79126*/
79127SQLITE_API int sqlite3_prepare(
79128  sqlite3 *db,              /* Database handle. */
79129  const char *zSql,         /* UTF-8 encoded SQL statement. */
79130  int nBytes,               /* Length of zSql in bytes. */
79131  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
79132  const char **pzTail       /* OUT: End of parsed string */
79133){
79134  int rc;
79135  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
79136  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
79137  return rc;
79138}
79139SQLITE_API int sqlite3_prepare_v2(
79140  sqlite3 *db,              /* Database handle. */
79141  const char *zSql,         /* UTF-8 encoded SQL statement. */
79142  int nBytes,               /* Length of zSql in bytes. */
79143  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
79144  const char **pzTail       /* OUT: End of parsed string */
79145){
79146  int rc;
79147  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
79148  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
79149  return rc;
79150}
79151
79152
79153#ifndef SQLITE_OMIT_UTF16
79154/*
79155** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
79156*/
79157static int sqlite3Prepare16(
79158  sqlite3 *db,              /* Database handle. */
79159  const void *zSql,         /* UTF-8 encoded SQL statement. */
79160  int nBytes,               /* Length of zSql in bytes. */
79161  int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
79162  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
79163  const void **pzTail       /* OUT: End of parsed string */
79164){
79165  /* This function currently works by first transforming the UTF-16
79166  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
79167  ** tricky bit is figuring out the pointer to return in *pzTail.
79168  */
79169  char *zSql8;
79170  const char *zTail8 = 0;
79171  int rc = SQLITE_OK;
79172
79173  assert( ppStmt );
79174  *ppStmt = 0;
79175  if( !sqlite3SafetyCheckOk(db) ){
79176    return SQLITE_MISUSE_BKPT;
79177  }
79178  sqlite3_mutex_enter(db->mutex);
79179  zSql8 = sqlite3Utf16to8(db, zSql, nBytes);
79180  if( zSql8 ){
79181    rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
79182  }
79183
79184  if( zTail8 && pzTail ){
79185    /* If sqlite3_prepare returns a tail pointer, we calculate the
79186    ** equivalent pointer into the UTF-16 string by counting the unicode
79187    ** characters between zSql8 and zTail8, and then returning a pointer
79188    ** the same number of characters into the UTF-16 string.
79189    */
79190    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
79191    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
79192  }
79193  sqlite3DbFree(db, zSql8);
79194  rc = sqlite3ApiExit(db, rc);
79195  sqlite3_mutex_leave(db->mutex);
79196  return rc;
79197}
79198
79199/*
79200** Two versions of the official API.  Legacy and new use.  In the legacy
79201** version, the original SQL text is not saved in the prepared statement
79202** and so if a schema change occurs, SQLITE_SCHEMA is returned by
79203** sqlite3_step().  In the new version, the original SQL text is retained
79204** and the statement is automatically recompiled if an schema change
79205** occurs.
79206*/
79207SQLITE_API int sqlite3_prepare16(
79208  sqlite3 *db,              /* Database handle. */
79209  const void *zSql,         /* UTF-8 encoded SQL statement. */
79210  int nBytes,               /* Length of zSql in bytes. */
79211  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
79212  const void **pzTail       /* OUT: End of parsed string */
79213){
79214  int rc;
79215  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
79216  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
79217  return rc;
79218}
79219SQLITE_API int sqlite3_prepare16_v2(
79220  sqlite3 *db,              /* Database handle. */
79221  const void *zSql,         /* UTF-8 encoded SQL statement. */
79222  int nBytes,               /* Length of zSql in bytes. */
79223  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
79224  const void **pzTail       /* OUT: End of parsed string */
79225){
79226  int rc;
79227  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
79228  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
79229  return rc;
79230}
79231
79232#endif /* SQLITE_OMIT_UTF16 */
79233
79234/************** End of prepare.c *********************************************/
79235/************** Begin file select.c ******************************************/
79236/*
79237** 2001 September 15
79238**
79239** The author disclaims copyright to this source code.  In place of
79240** a legal notice, here is a blessing:
79241**
79242**    May you do good and not evil.
79243**    May you find forgiveness for yourself and forgive others.
79244**    May you share freely, never taking more than you give.
79245**
79246*************************************************************************
79247** This file contains C code routines that are called by the parser
79248** to handle SELECT statements in SQLite.
79249*/
79250
79251
79252/*
79253** Delete all the content of a Select structure but do not deallocate
79254** the select structure itself.
79255*/
79256static void clearSelect(sqlite3 *db, Select *p){
79257  sqlite3ExprListDelete(db, p->pEList);
79258  sqlite3SrcListDelete(db, p->pSrc);
79259  sqlite3ExprDelete(db, p->pWhere);
79260  sqlite3ExprListDelete(db, p->pGroupBy);
79261  sqlite3ExprDelete(db, p->pHaving);
79262  sqlite3ExprListDelete(db, p->pOrderBy);
79263  sqlite3SelectDelete(db, p->pPrior);
79264  sqlite3ExprDelete(db, p->pLimit);
79265  sqlite3ExprDelete(db, p->pOffset);
79266}
79267
79268/*
79269** Initialize a SelectDest structure.
79270*/
79271SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
79272  pDest->eDest = (u8)eDest;
79273  pDest->iParm = iParm;
79274  pDest->affinity = 0;
79275  pDest->iMem = 0;
79276  pDest->nMem = 0;
79277}
79278
79279
79280/*
79281** Allocate a new Select structure and return a pointer to that
79282** structure.
79283*/
79284SQLITE_PRIVATE Select *sqlite3SelectNew(
79285  Parse *pParse,        /* Parsing context */
79286  ExprList *pEList,     /* which columns to include in the result */
79287  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
79288  Expr *pWhere,         /* the WHERE clause */
79289  ExprList *pGroupBy,   /* the GROUP BY clause */
79290  Expr *pHaving,        /* the HAVING clause */
79291  ExprList *pOrderBy,   /* the ORDER BY clause */
79292  int isDistinct,       /* true if the DISTINCT keyword is present */
79293  Expr *pLimit,         /* LIMIT value.  NULL means not used */
79294  Expr *pOffset         /* OFFSET value.  NULL means no offset */
79295){
79296  Select *pNew;
79297  Select standin;
79298  sqlite3 *db = pParse->db;
79299  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
79300  assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
79301  if( pNew==0 ){
79302    pNew = &standin;
79303    memset(pNew, 0, sizeof(*pNew));
79304  }
79305  if( pEList==0 ){
79306    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
79307  }
79308  pNew->pEList = pEList;
79309  pNew->pSrc = pSrc;
79310  pNew->pWhere = pWhere;
79311  pNew->pGroupBy = pGroupBy;
79312  pNew->pHaving = pHaving;
79313  pNew->pOrderBy = pOrderBy;
79314  pNew->selFlags = isDistinct ? SF_Distinct : 0;
79315  pNew->op = TK_SELECT;
79316  pNew->pLimit = pLimit;
79317  pNew->pOffset = pOffset;
79318  assert( pOffset==0 || pLimit!=0 );
79319  pNew->addrOpenEphm[0] = -1;
79320  pNew->addrOpenEphm[1] = -1;
79321  pNew->addrOpenEphm[2] = -1;
79322  if( db->mallocFailed ) {
79323    clearSelect(db, pNew);
79324    if( pNew!=&standin ) sqlite3DbFree(db, pNew);
79325    pNew = 0;
79326  }
79327  return pNew;
79328}
79329
79330/*
79331** Delete the given Select structure and all of its substructures.
79332*/
79333SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
79334  if( p ){
79335    clearSelect(db, p);
79336    sqlite3DbFree(db, p);
79337  }
79338}
79339
79340/*
79341** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
79342** type of join.  Return an integer constant that expresses that type
79343** in terms of the following bit values:
79344**
79345**     JT_INNER
79346**     JT_CROSS
79347**     JT_OUTER
79348**     JT_NATURAL
79349**     JT_LEFT
79350**     JT_RIGHT
79351**
79352** A full outer join is the combination of JT_LEFT and JT_RIGHT.
79353**
79354** If an illegal or unsupported join type is seen, then still return
79355** a join type, but put an error in the pParse structure.
79356*/
79357SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
79358  int jointype = 0;
79359  Token *apAll[3];
79360  Token *p;
79361                             /*   0123456789 123456789 123456789 123 */
79362  static const char zKeyText[] = "naturaleftouterightfullinnercross";
79363  static const struct {
79364    u8 i;        /* Beginning of keyword text in zKeyText[] */
79365    u8 nChar;    /* Length of the keyword in characters */
79366    u8 code;     /* Join type mask */
79367  } aKeyword[] = {
79368    /* natural */ { 0,  7, JT_NATURAL                },
79369    /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
79370    /* outer   */ { 10, 5, JT_OUTER                  },
79371    /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
79372    /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
79373    /* inner   */ { 23, 5, JT_INNER                  },
79374    /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
79375  };
79376  int i, j;
79377  apAll[0] = pA;
79378  apAll[1] = pB;
79379  apAll[2] = pC;
79380  for(i=0; i<3 && apAll[i]; i++){
79381    p = apAll[i];
79382    for(j=0; j<ArraySize(aKeyword); j++){
79383      if( p->n==aKeyword[j].nChar
79384          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
79385        jointype |= aKeyword[j].code;
79386        break;
79387      }
79388    }
79389    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
79390    if( j>=ArraySize(aKeyword) ){
79391      jointype |= JT_ERROR;
79392      break;
79393    }
79394  }
79395  if(
79396     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
79397     (jointype & JT_ERROR)!=0
79398  ){
79399    const char *zSp = " ";
79400    assert( pB!=0 );
79401    if( pC==0 ){ zSp++; }
79402    sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
79403       "%T %T%s%T", pA, pB, zSp, pC);
79404    jointype = JT_INNER;
79405  }else if( (jointype & JT_OUTER)!=0
79406         && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
79407    sqlite3ErrorMsg(pParse,
79408      "RIGHT and FULL OUTER JOINs are not currently supported");
79409    jointype = JT_INNER;
79410  }
79411  return jointype;
79412}
79413
79414/*
79415** Return the index of a column in a table.  Return -1 if the column
79416** is not contained in the table.
79417*/
79418static int columnIndex(Table *pTab, const char *zCol){
79419  int i;
79420  for(i=0; i<pTab->nCol; i++){
79421    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
79422  }
79423  return -1;
79424}
79425
79426/*
79427** Search the first N tables in pSrc, from left to right, looking for a
79428** table that has a column named zCol.
79429**
79430** When found, set *piTab and *piCol to the table index and column index
79431** of the matching column and return TRUE.
79432**
79433** If not found, return FALSE.
79434*/
79435static int tableAndColumnIndex(
79436  SrcList *pSrc,       /* Array of tables to search */
79437  int N,               /* Number of tables in pSrc->a[] to search */
79438  const char *zCol,    /* Name of the column we are looking for */
79439  int *piTab,          /* Write index of pSrc->a[] here */
79440  int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
79441){
79442  int i;               /* For looping over tables in pSrc */
79443  int iCol;            /* Index of column matching zCol */
79444
79445  assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
79446  for(i=0; i<N; i++){
79447    iCol = columnIndex(pSrc->a[i].pTab, zCol);
79448    if( iCol>=0 ){
79449      if( piTab ){
79450        *piTab = i;
79451        *piCol = iCol;
79452      }
79453      return 1;
79454    }
79455  }
79456  return 0;
79457}
79458
79459/*
79460** This function is used to add terms implied by JOIN syntax to the
79461** WHERE clause expression of a SELECT statement. The new term, which
79462** is ANDed with the existing WHERE clause, is of the form:
79463**
79464**    (tab1.col1 = tab2.col2)
79465**
79466** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
79467** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
79468** column iColRight of tab2.
79469*/
79470static void addWhereTerm(
79471  Parse *pParse,                  /* Parsing context */
79472  SrcList *pSrc,                  /* List of tables in FROM clause */
79473  int iLeft,                      /* Index of first table to join in pSrc */
79474  int iColLeft,                   /* Index of column in first table */
79475  int iRight,                     /* Index of second table in pSrc */
79476  int iColRight,                  /* Index of column in second table */
79477  int isOuterJoin,                /* True if this is an OUTER join */
79478  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
79479){
79480  sqlite3 *db = pParse->db;
79481  Expr *pE1;
79482  Expr *pE2;
79483  Expr *pEq;
79484
79485  assert( iLeft<iRight );
79486  assert( pSrc->nSrc>iRight );
79487  assert( pSrc->a[iLeft].pTab );
79488  assert( pSrc->a[iRight].pTab );
79489
79490  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
79491  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
79492
79493  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
79494  if( pEq && isOuterJoin ){
79495    ExprSetProperty(pEq, EP_FromJoin);
79496    assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
79497    ExprSetIrreducible(pEq);
79498    pEq->iRightJoinTable = (i16)pE2->iTable;
79499  }
79500  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
79501}
79502
79503/*
79504** Set the EP_FromJoin property on all terms of the given expression.
79505** And set the Expr.iRightJoinTable to iTable for every term in the
79506** expression.
79507**
79508** The EP_FromJoin property is used on terms of an expression to tell
79509** the LEFT OUTER JOIN processing logic that this term is part of the
79510** join restriction specified in the ON or USING clause and not a part
79511** of the more general WHERE clause.  These terms are moved over to the
79512** WHERE clause during join processing but we need to remember that they
79513** originated in the ON or USING clause.
79514**
79515** The Expr.iRightJoinTable tells the WHERE clause processing that the
79516** expression depends on table iRightJoinTable even if that table is not
79517** explicitly mentioned in the expression.  That information is needed
79518** for cases like this:
79519**
79520**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
79521**
79522** The where clause needs to defer the handling of the t1.x=5
79523** term until after the t2 loop of the join.  In that way, a
79524** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
79525** defer the handling of t1.x=5, it will be processed immediately
79526** after the t1 loop and rows with t1.x!=5 will never appear in
79527** the output, which is incorrect.
79528*/
79529static void setJoinExpr(Expr *p, int iTable){
79530  while( p ){
79531    ExprSetProperty(p, EP_FromJoin);
79532    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
79533    ExprSetIrreducible(p);
79534    p->iRightJoinTable = (i16)iTable;
79535    setJoinExpr(p->pLeft, iTable);
79536    p = p->pRight;
79537  }
79538}
79539
79540/*
79541** This routine processes the join information for a SELECT statement.
79542** ON and USING clauses are converted into extra terms of the WHERE clause.
79543** NATURAL joins also create extra WHERE clause terms.
79544**
79545** The terms of a FROM clause are contained in the Select.pSrc structure.
79546** The left most table is the first entry in Select.pSrc.  The right-most
79547** table is the last entry.  The join operator is held in the entry to
79548** the left.  Thus entry 0 contains the join operator for the join between
79549** entries 0 and 1.  Any ON or USING clauses associated with the join are
79550** also attached to the left entry.
79551**
79552** This routine returns the number of errors encountered.
79553*/
79554static int sqliteProcessJoin(Parse *pParse, Select *p){
79555  SrcList *pSrc;                  /* All tables in the FROM clause */
79556  int i, j;                       /* Loop counters */
79557  struct SrcList_item *pLeft;     /* Left table being joined */
79558  struct SrcList_item *pRight;    /* Right table being joined */
79559
79560  pSrc = p->pSrc;
79561  pLeft = &pSrc->a[0];
79562  pRight = &pLeft[1];
79563  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
79564    Table *pLeftTab = pLeft->pTab;
79565    Table *pRightTab = pRight->pTab;
79566    int isOuter;
79567
79568    if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
79569    isOuter = (pRight->jointype & JT_OUTER)!=0;
79570
79571    /* When the NATURAL keyword is present, add WHERE clause terms for
79572    ** every column that the two tables have in common.
79573    */
79574    if( pRight->jointype & JT_NATURAL ){
79575      if( pRight->pOn || pRight->pUsing ){
79576        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
79577           "an ON or USING clause", 0);
79578        return 1;
79579      }
79580      for(j=0; j<pRightTab->nCol; j++){
79581        char *zName;   /* Name of column in the right table */
79582        int iLeft;     /* Matching left table */
79583        int iLeftCol;  /* Matching column in the left table */
79584
79585        zName = pRightTab->aCol[j].zName;
79586        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
79587          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
79588                       isOuter, &p->pWhere);
79589        }
79590      }
79591    }
79592
79593    /* Disallow both ON and USING clauses in the same join
79594    */
79595    if( pRight->pOn && pRight->pUsing ){
79596      sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
79597        "clauses in the same join");
79598      return 1;
79599    }
79600
79601    /* Add the ON clause to the end of the WHERE clause, connected by
79602    ** an AND operator.
79603    */
79604    if( pRight->pOn ){
79605      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
79606      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
79607      pRight->pOn = 0;
79608    }
79609
79610    /* Create extra terms on the WHERE clause for each column named
79611    ** in the USING clause.  Example: If the two tables to be joined are
79612    ** A and B and the USING clause names X, Y, and Z, then add this
79613    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
79614    ** Report an error if any column mentioned in the USING clause is
79615    ** not contained in both tables to be joined.
79616    */
79617    if( pRight->pUsing ){
79618      IdList *pList = pRight->pUsing;
79619      for(j=0; j<pList->nId; j++){
79620        char *zName;     /* Name of the term in the USING clause */
79621        int iLeft;       /* Table on the left with matching column name */
79622        int iLeftCol;    /* Column number of matching column on the left */
79623        int iRightCol;   /* Column number of matching column on the right */
79624
79625        zName = pList->a[j].zName;
79626        iRightCol = columnIndex(pRightTab, zName);
79627        if( iRightCol<0
79628         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
79629        ){
79630          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
79631            "not present in both tables", zName);
79632          return 1;
79633        }
79634        addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
79635                     isOuter, &p->pWhere);
79636      }
79637    }
79638  }
79639  return 0;
79640}
79641
79642/*
79643** Insert code into "v" that will push the record on the top of the
79644** stack into the sorter.
79645*/
79646static void pushOntoSorter(
79647  Parse *pParse,         /* Parser context */
79648  ExprList *pOrderBy,    /* The ORDER BY clause */
79649  Select *pSelect,       /* The whole SELECT statement */
79650  int regData            /* Register holding data to be sorted */
79651){
79652  Vdbe *v = pParse->pVdbe;
79653  int nExpr = pOrderBy->nExpr;
79654  int regBase = sqlite3GetTempRange(pParse, nExpr+2);
79655  int regRecord = sqlite3GetTempReg(pParse);
79656  sqlite3ExprCacheClear(pParse);
79657  sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
79658  sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
79659  sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
79660  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
79661  sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
79662  sqlite3ReleaseTempReg(pParse, regRecord);
79663  sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
79664  if( pSelect->iLimit ){
79665    int addr1, addr2;
79666    int iLimit;
79667    if( pSelect->iOffset ){
79668      iLimit = pSelect->iOffset+1;
79669    }else{
79670      iLimit = pSelect->iLimit;
79671    }
79672    addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
79673    sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
79674    addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
79675    sqlite3VdbeJumpHere(v, addr1);
79676    sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
79677    sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
79678    sqlite3VdbeJumpHere(v, addr2);
79679    pSelect->iLimit = 0;
79680  }
79681}
79682
79683/*
79684** Add code to implement the OFFSET
79685*/
79686static void codeOffset(
79687  Vdbe *v,          /* Generate code into this VM */
79688  Select *p,        /* The SELECT statement being coded */
79689  int iContinue     /* Jump here to skip the current record */
79690){
79691  if( p->iOffset && iContinue!=0 ){
79692    int addr;
79693    sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
79694    addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
79695    sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
79696    VdbeComment((v, "skip OFFSET records"));
79697    sqlite3VdbeJumpHere(v, addr);
79698  }
79699}
79700
79701/*
79702** Add code that will check to make sure the N registers starting at iMem
79703** form a distinct entry.  iTab is a sorting index that holds previously
79704** seen combinations of the N values.  A new entry is made in iTab
79705** if the current N values are new.
79706**
79707** A jump to addrRepeat is made and the N+1 values are popped from the
79708** stack if the top N elements are not distinct.
79709*/
79710static void codeDistinct(
79711  Parse *pParse,     /* Parsing and code generating context */
79712  int iTab,          /* A sorting index used to test for distinctness */
79713  int addrRepeat,    /* Jump to here if not distinct */
79714  int N,             /* Number of elements */
79715  int iMem           /* First element */
79716){
79717  Vdbe *v;
79718  int r1;
79719
79720  v = pParse->pVdbe;
79721  r1 = sqlite3GetTempReg(pParse);
79722  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
79723  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
79724  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
79725  sqlite3ReleaseTempReg(pParse, r1);
79726}
79727
79728/*
79729** Generate an error message when a SELECT is used within a subexpression
79730** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
79731** column.  We do this in a subroutine because the error occurs in multiple
79732** places.
79733*/
79734static int checkForMultiColumnSelectError(
79735  Parse *pParse,       /* Parse context. */
79736  SelectDest *pDest,   /* Destination of SELECT results */
79737  int nExpr            /* Number of result columns returned by SELECT */
79738){
79739  int eDest = pDest->eDest;
79740  if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
79741    sqlite3ErrorMsg(pParse, "only a single result allowed for "
79742       "a SELECT that is part of an expression");
79743    return 1;
79744  }else{
79745    return 0;
79746  }
79747}
79748
79749/*
79750** This routine generates the code for the inside of the inner loop
79751** of a SELECT.
79752**
79753** If srcTab and nColumn are both zero, then the pEList expressions
79754** are evaluated in order to get the data for this row.  If nColumn>0
79755** then data is pulled from srcTab and pEList is used only to get the
79756** datatypes for each column.
79757*/
79758static void selectInnerLoop(
79759  Parse *pParse,          /* The parser context */
79760  Select *p,              /* The complete select statement being coded */
79761  ExprList *pEList,       /* List of values being extracted */
79762  int srcTab,             /* Pull data from this table */
79763  int nColumn,            /* Number of columns in the source table */
79764  ExprList *pOrderBy,     /* If not NULL, sort results using this key */
79765  int distinct,           /* If >=0, make sure results are distinct */
79766  SelectDest *pDest,      /* How to dispose of the results */
79767  int iContinue,          /* Jump here to continue with next row */
79768  int iBreak              /* Jump here to break out of the inner loop */
79769){
79770  Vdbe *v = pParse->pVdbe;
79771  int i;
79772  int hasDistinct;        /* True if the DISTINCT keyword is present */
79773  int regResult;              /* Start of memory holding result set */
79774  int eDest = pDest->eDest;   /* How to dispose of results */
79775  int iParm = pDest->iParm;   /* First argument to disposal method */
79776  int nResultCol;             /* Number of result columns */
79777
79778  assert( v );
79779  if( NEVER(v==0) ) return;
79780  assert( pEList!=0 );
79781  hasDistinct = distinct>=0;
79782  if( pOrderBy==0 && !hasDistinct ){
79783    codeOffset(v, p, iContinue);
79784  }
79785
79786  /* Pull the requested columns.
79787  */
79788  if( nColumn>0 ){
79789    nResultCol = nColumn;
79790  }else{
79791    nResultCol = pEList->nExpr;
79792  }
79793  if( pDest->iMem==0 ){
79794    pDest->iMem = pParse->nMem+1;
79795    pDest->nMem = nResultCol;
79796    pParse->nMem += nResultCol;
79797  }else{
79798    assert( pDest->nMem==nResultCol );
79799  }
79800  regResult = pDest->iMem;
79801  if( nColumn>0 ){
79802    for(i=0; i<nColumn; i++){
79803      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
79804    }
79805  }else if( eDest!=SRT_Exists ){
79806    /* If the destination is an EXISTS(...) expression, the actual
79807    ** values returned by the SELECT are not required.
79808    */
79809    sqlite3ExprCacheClear(pParse);
79810    sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
79811  }
79812  nColumn = nResultCol;
79813
79814  /* If the DISTINCT keyword was present on the SELECT statement
79815  ** and this row has been seen before, then do not make this row
79816  ** part of the result.
79817  */
79818  if( hasDistinct ){
79819    assert( pEList!=0 );
79820    assert( pEList->nExpr==nColumn );
79821    codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
79822    if( pOrderBy==0 ){
79823      codeOffset(v, p, iContinue);
79824    }
79825  }
79826
79827  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
79828    return;
79829  }
79830
79831  switch( eDest ){
79832    /* In this mode, write each query result to the key of the temporary
79833    ** table iParm.
79834    */
79835#ifndef SQLITE_OMIT_COMPOUND_SELECT
79836    case SRT_Union: {
79837      int r1;
79838      r1 = sqlite3GetTempReg(pParse);
79839      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
79840      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
79841      sqlite3ReleaseTempReg(pParse, r1);
79842      break;
79843    }
79844
79845    /* Construct a record from the query result, but instead of
79846    ** saving that record, use it as a key to delete elements from
79847    ** the temporary table iParm.
79848    */
79849    case SRT_Except: {
79850      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
79851      break;
79852    }
79853#endif
79854
79855    /* Store the result as data using a unique key.
79856    */
79857    case SRT_Table:
79858    case SRT_EphemTab: {
79859      int r1 = sqlite3GetTempReg(pParse);
79860      testcase( eDest==SRT_Table );
79861      testcase( eDest==SRT_EphemTab );
79862      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
79863      if( pOrderBy ){
79864        pushOntoSorter(pParse, pOrderBy, p, r1);
79865      }else{
79866        int r2 = sqlite3GetTempReg(pParse);
79867        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
79868        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
79869        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
79870        sqlite3ReleaseTempReg(pParse, r2);
79871      }
79872      sqlite3ReleaseTempReg(pParse, r1);
79873      break;
79874    }
79875
79876#ifndef SQLITE_OMIT_SUBQUERY
79877    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
79878    ** then there should be a single item on the stack.  Write this
79879    ** item into the set table with bogus data.
79880    */
79881    case SRT_Set: {
79882      assert( nColumn==1 );
79883      p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
79884      if( pOrderBy ){
79885        /* At first glance you would think we could optimize out the
79886        ** ORDER BY in this case since the order of entries in the set
79887        ** does not matter.  But there might be a LIMIT clause, in which
79888        ** case the order does matter */
79889        pushOntoSorter(pParse, pOrderBy, p, regResult);
79890      }else{
79891        int r1 = sqlite3GetTempReg(pParse);
79892        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
79893        sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
79894        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
79895        sqlite3ReleaseTempReg(pParse, r1);
79896      }
79897      break;
79898    }
79899
79900    /* If any row exist in the result set, record that fact and abort.
79901    */
79902    case SRT_Exists: {
79903      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
79904      /* The LIMIT clause will terminate the loop for us */
79905      break;
79906    }
79907
79908    /* If this is a scalar select that is part of an expression, then
79909    ** store the results in the appropriate memory cell and break out
79910    ** of the scan loop.
79911    */
79912    case SRT_Mem: {
79913      assert( nColumn==1 );
79914      if( pOrderBy ){
79915        pushOntoSorter(pParse, pOrderBy, p, regResult);
79916      }else{
79917        sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
79918        /* The LIMIT clause will jump out of the loop for us */
79919      }
79920      break;
79921    }
79922#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
79923
79924    /* Send the data to the callback function or to a subroutine.  In the
79925    ** case of a subroutine, the subroutine itself is responsible for
79926    ** popping the data from the stack.
79927    */
79928    case SRT_Coroutine:
79929    case SRT_Output: {
79930      testcase( eDest==SRT_Coroutine );
79931      testcase( eDest==SRT_Output );
79932      if( pOrderBy ){
79933        int r1 = sqlite3GetTempReg(pParse);
79934        sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
79935        pushOntoSorter(pParse, pOrderBy, p, r1);
79936        sqlite3ReleaseTempReg(pParse, r1);
79937      }else if( eDest==SRT_Coroutine ){
79938        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
79939      }else{
79940        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
79941        sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
79942      }
79943      break;
79944    }
79945
79946#if !defined(SQLITE_OMIT_TRIGGER)
79947    /* Discard the results.  This is used for SELECT statements inside
79948    ** the body of a TRIGGER.  The purpose of such selects is to call
79949    ** user-defined functions that have side effects.  We do not care
79950    ** about the actual results of the select.
79951    */
79952    default: {
79953      assert( eDest==SRT_Discard );
79954      break;
79955    }
79956#endif
79957  }
79958
79959  /* Jump to the end of the loop if the LIMIT is reached.
79960  */
79961  if( p->iLimit ){
79962    assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
79963                            ** pushOntoSorter() would have cleared p->iLimit */
79964    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
79965  }
79966}
79967
79968/*
79969** Given an expression list, generate a KeyInfo structure that records
79970** the collating sequence for each expression in that expression list.
79971**
79972** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
79973** KeyInfo structure is appropriate for initializing a virtual index to
79974** implement that clause.  If the ExprList is the result set of a SELECT
79975** then the KeyInfo structure is appropriate for initializing a virtual
79976** index to implement a DISTINCT test.
79977**
79978** Space to hold the KeyInfo structure is obtain from malloc.  The calling
79979** function is responsible for seeing that this structure is eventually
79980** freed.  Add the KeyInfo structure to the P4 field of an opcode using
79981** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
79982*/
79983static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
79984  sqlite3 *db = pParse->db;
79985  int nExpr;
79986  KeyInfo *pInfo;
79987  struct ExprList_item *pItem;
79988  int i;
79989
79990  nExpr = pList->nExpr;
79991  pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
79992  if( pInfo ){
79993    pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
79994    pInfo->nField = (u16)nExpr;
79995    pInfo->enc = ENC(db);
79996    pInfo->db = db;
79997    for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
79998      CollSeq *pColl;
79999      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
80000      if( !pColl ){
80001        pColl = db->pDfltColl;
80002      }
80003      pInfo->aColl[i] = pColl;
80004      pInfo->aSortOrder[i] = pItem->sortOrder;
80005    }
80006  }
80007  return pInfo;
80008}
80009
80010
80011/*
80012** If the inner loop was generated using a non-null pOrderBy argument,
80013** then the results were placed in a sorter.  After the loop is terminated
80014** we need to run the sorter and output the results.  The following
80015** routine generates the code needed to do that.
80016*/
80017static void generateSortTail(
80018  Parse *pParse,    /* Parsing context */
80019  Select *p,        /* The SELECT statement */
80020  Vdbe *v,          /* Generate code into this VDBE */
80021  int nColumn,      /* Number of columns of data */
80022  SelectDest *pDest /* Write the sorted results here */
80023){
80024  int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
80025  int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
80026  int addr;
80027  int iTab;
80028  int pseudoTab = 0;
80029  ExprList *pOrderBy = p->pOrderBy;
80030
80031  int eDest = pDest->eDest;
80032  int iParm = pDest->iParm;
80033
80034  int regRow;
80035  int regRowid;
80036
80037  iTab = pOrderBy->iECursor;
80038  regRow = sqlite3GetTempReg(pParse);
80039  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
80040    pseudoTab = pParse->nTab++;
80041    sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
80042    regRowid = 0;
80043  }else{
80044    regRowid = sqlite3GetTempReg(pParse);
80045  }
80046  addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
80047  codeOffset(v, p, addrContinue);
80048  sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
80049  switch( eDest ){
80050    case SRT_Table:
80051    case SRT_EphemTab: {
80052      testcase( eDest==SRT_Table );
80053      testcase( eDest==SRT_EphemTab );
80054      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
80055      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
80056      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
80057      break;
80058    }
80059#ifndef SQLITE_OMIT_SUBQUERY
80060    case SRT_Set: {
80061      assert( nColumn==1 );
80062      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
80063      sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
80064      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
80065      break;
80066    }
80067    case SRT_Mem: {
80068      assert( nColumn==1 );
80069      sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
80070      /* The LIMIT clause will terminate the loop for us */
80071      break;
80072    }
80073#endif
80074    default: {
80075      int i;
80076      assert( eDest==SRT_Output || eDest==SRT_Coroutine );
80077      testcase( eDest==SRT_Output );
80078      testcase( eDest==SRT_Coroutine );
80079      for(i=0; i<nColumn; i++){
80080        assert( regRow!=pDest->iMem+i );
80081        sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
80082        if( i==0 ){
80083          sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
80084        }
80085      }
80086      if( eDest==SRT_Output ){
80087        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
80088        sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
80089      }else{
80090        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
80091      }
80092      break;
80093    }
80094  }
80095  sqlite3ReleaseTempReg(pParse, regRow);
80096  sqlite3ReleaseTempReg(pParse, regRowid);
80097
80098  /* LIMIT has been implemented by the pushOntoSorter() routine.
80099  */
80100  assert( p->iLimit==0 );
80101
80102  /* The bottom of the loop
80103  */
80104  sqlite3VdbeResolveLabel(v, addrContinue);
80105  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
80106  sqlite3VdbeResolveLabel(v, addrBreak);
80107  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
80108    sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
80109  }
80110}
80111
80112/*
80113** Return a pointer to a string containing the 'declaration type' of the
80114** expression pExpr. The string may be treated as static by the caller.
80115**
80116** The declaration type is the exact datatype definition extracted from the
80117** original CREATE TABLE statement if the expression is a column. The
80118** declaration type for a ROWID field is INTEGER. Exactly when an expression
80119** is considered a column can be complex in the presence of subqueries. The
80120** result-set expression in all of the following SELECT statements is
80121** considered a column by this function.
80122**
80123**   SELECT col FROM tbl;
80124**   SELECT (SELECT col FROM tbl;
80125**   SELECT (SELECT col FROM tbl);
80126**   SELECT abc FROM (SELECT col AS abc FROM tbl);
80127**
80128** The declaration type for any expression other than a column is NULL.
80129*/
80130static const char *columnType(
80131  NameContext *pNC,
80132  Expr *pExpr,
80133  const char **pzOriginDb,
80134  const char **pzOriginTab,
80135  const char **pzOriginCol
80136){
80137  char const *zType = 0;
80138  char const *zOriginDb = 0;
80139  char const *zOriginTab = 0;
80140  char const *zOriginCol = 0;
80141  int j;
80142  if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
80143
80144  switch( pExpr->op ){
80145    case TK_AGG_COLUMN:
80146    case TK_COLUMN: {
80147      /* The expression is a column. Locate the table the column is being
80148      ** extracted from in NameContext.pSrcList. This table may be real
80149      ** database table or a subquery.
80150      */
80151      Table *pTab = 0;            /* Table structure column is extracted from */
80152      Select *pS = 0;             /* Select the column is extracted from */
80153      int iCol = pExpr->iColumn;  /* Index of column in pTab */
80154      testcase( pExpr->op==TK_AGG_COLUMN );
80155      testcase( pExpr->op==TK_COLUMN );
80156      while( pNC && !pTab ){
80157        SrcList *pTabList = pNC->pSrcList;
80158        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
80159        if( j<pTabList->nSrc ){
80160          pTab = pTabList->a[j].pTab;
80161          pS = pTabList->a[j].pSelect;
80162        }else{
80163          pNC = pNC->pNext;
80164        }
80165      }
80166
80167      if( pTab==0 ){
80168        /* At one time, code such as "SELECT new.x" within a trigger would
80169        ** cause this condition to run.  Since then, we have restructured how
80170        ** trigger code is generated and so this condition is no longer
80171        ** possible. However, it can still be true for statements like
80172        ** the following:
80173        **
80174        **   CREATE TABLE t1(col INTEGER);
80175        **   SELECT (SELECT t1.col) FROM FROM t1;
80176        **
80177        ** when columnType() is called on the expression "t1.col" in the
80178        ** sub-select. In this case, set the column type to NULL, even
80179        ** though it should really be "INTEGER".
80180        **
80181        ** This is not a problem, as the column type of "t1.col" is never
80182        ** used. When columnType() is called on the expression
80183        ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
80184        ** branch below.  */
80185        break;
80186      }
80187
80188      assert( pTab && pExpr->pTab==pTab );
80189      if( pS ){
80190        /* The "table" is actually a sub-select or a view in the FROM clause
80191        ** of the SELECT statement. Return the declaration type and origin
80192        ** data for the result-set column of the sub-select.
80193        */
80194        if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
80195          /* If iCol is less than zero, then the expression requests the
80196          ** rowid of the sub-select or view. This expression is legal (see
80197          ** test case misc2.2.2) - it always evaluates to NULL.
80198          */
80199          NameContext sNC;
80200          Expr *p = pS->pEList->a[iCol].pExpr;
80201          sNC.pSrcList = pS->pSrc;
80202          sNC.pNext = pNC;
80203          sNC.pParse = pNC->pParse;
80204          zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
80205        }
80206      }else if( ALWAYS(pTab->pSchema) ){
80207        /* A real table */
80208        assert( !pS );
80209        if( iCol<0 ) iCol = pTab->iPKey;
80210        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
80211        if( iCol<0 ){
80212          zType = "INTEGER";
80213          zOriginCol = "rowid";
80214        }else{
80215          zType = pTab->aCol[iCol].zType;
80216          zOriginCol = pTab->aCol[iCol].zName;
80217        }
80218        zOriginTab = pTab->zName;
80219        if( pNC->pParse ){
80220          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
80221          zOriginDb = pNC->pParse->db->aDb[iDb].zName;
80222        }
80223      }
80224      break;
80225    }
80226#ifndef SQLITE_OMIT_SUBQUERY
80227    case TK_SELECT: {
80228      /* The expression is a sub-select. Return the declaration type and
80229      ** origin info for the single column in the result set of the SELECT
80230      ** statement.
80231      */
80232      NameContext sNC;
80233      Select *pS = pExpr->x.pSelect;
80234      Expr *p = pS->pEList->a[0].pExpr;
80235      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
80236      sNC.pSrcList = pS->pSrc;
80237      sNC.pNext = pNC;
80238      sNC.pParse = pNC->pParse;
80239      zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
80240      break;
80241    }
80242#endif
80243  }
80244
80245  if( pzOriginDb ){
80246    assert( pzOriginTab && pzOriginCol );
80247    *pzOriginDb = zOriginDb;
80248    *pzOriginTab = zOriginTab;
80249    *pzOriginCol = zOriginCol;
80250  }
80251  return zType;
80252}
80253
80254/*
80255** Generate code that will tell the VDBE the declaration types of columns
80256** in the result set.
80257*/
80258static void generateColumnTypes(
80259  Parse *pParse,      /* Parser context */
80260  SrcList *pTabList,  /* List of tables */
80261  ExprList *pEList    /* Expressions defining the result set */
80262){
80263#ifndef SQLITE_OMIT_DECLTYPE
80264  Vdbe *v = pParse->pVdbe;
80265  int i;
80266  NameContext sNC;
80267  sNC.pSrcList = pTabList;
80268  sNC.pParse = pParse;
80269  for(i=0; i<pEList->nExpr; i++){
80270    Expr *p = pEList->a[i].pExpr;
80271    const char *zType;
80272#ifdef SQLITE_ENABLE_COLUMN_METADATA
80273    const char *zOrigDb = 0;
80274    const char *zOrigTab = 0;
80275    const char *zOrigCol = 0;
80276    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
80277
80278    /* The vdbe must make its own copy of the column-type and other
80279    ** column specific strings, in case the schema is reset before this
80280    ** virtual machine is deleted.
80281    */
80282    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
80283    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
80284    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
80285#else
80286    zType = columnType(&sNC, p, 0, 0, 0);
80287#endif
80288    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
80289  }
80290#endif /* SQLITE_OMIT_DECLTYPE */
80291}
80292
80293/*
80294** Generate code that will tell the VDBE the names of columns
80295** in the result set.  This information is used to provide the
80296** azCol[] values in the callback.
80297*/
80298static void generateColumnNames(
80299  Parse *pParse,      /* Parser context */
80300  SrcList *pTabList,  /* List of tables */
80301  ExprList *pEList    /* Expressions defining the result set */
80302){
80303  Vdbe *v = pParse->pVdbe;
80304  int i, j;
80305  sqlite3 *db = pParse->db;
80306  int fullNames, shortNames;
80307
80308#ifndef SQLITE_OMIT_EXPLAIN
80309  /* If this is an EXPLAIN, skip this step */
80310  if( pParse->explain ){
80311    return;
80312  }
80313#endif
80314
80315  if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
80316  pParse->colNamesSet = 1;
80317  fullNames = (db->flags & SQLITE_FullColNames)!=0;
80318  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
80319  sqlite3VdbeSetNumCols(v, pEList->nExpr);
80320  for(i=0; i<pEList->nExpr; i++){
80321    Expr *p;
80322    p = pEList->a[i].pExpr;
80323    if( NEVER(p==0) ) continue;
80324    if( pEList->a[i].zName ){
80325      char *zName = pEList->a[i].zName;
80326      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
80327    }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
80328      Table *pTab;
80329      char *zCol;
80330      int iCol = p->iColumn;
80331      for(j=0; ALWAYS(j<pTabList->nSrc); j++){
80332        if( pTabList->a[j].iCursor==p->iTable ) break;
80333      }
80334      assert( j<pTabList->nSrc );
80335      pTab = pTabList->a[j].pTab;
80336      if( iCol<0 ) iCol = pTab->iPKey;
80337      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
80338      if( iCol<0 ){
80339        zCol = "rowid";
80340      }else{
80341        zCol = pTab->aCol[iCol].zName;
80342      }
80343      if( !shortNames && !fullNames ){
80344        sqlite3VdbeSetColName(v, i, COLNAME_NAME,
80345            sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
80346      }else if( fullNames ){
80347        char *zName = 0;
80348        zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
80349        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
80350      }else{
80351        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
80352      }
80353    }else{
80354      sqlite3VdbeSetColName(v, i, COLNAME_NAME,
80355          sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
80356    }
80357  }
80358  generateColumnTypes(pParse, pTabList, pEList);
80359}
80360
80361#ifndef SQLITE_OMIT_COMPOUND_SELECT
80362/*
80363** Name of the connection operator, used for error messages.
80364*/
80365static const char *selectOpName(int id){
80366  char *z;
80367  switch( id ){
80368    case TK_ALL:       z = "UNION ALL";   break;
80369    case TK_INTERSECT: z = "INTERSECT";   break;
80370    case TK_EXCEPT:    z = "EXCEPT";      break;
80371    default:           z = "UNION";       break;
80372  }
80373  return z;
80374}
80375#endif /* SQLITE_OMIT_COMPOUND_SELECT */
80376
80377/*
80378** Given a an expression list (which is really the list of expressions
80379** that form the result set of a SELECT statement) compute appropriate
80380** column names for a table that would hold the expression list.
80381**
80382** All column names will be unique.
80383**
80384** Only the column names are computed.  Column.zType, Column.zColl,
80385** and other fields of Column are zeroed.
80386**
80387** Return SQLITE_OK on success.  If a memory allocation error occurs,
80388** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
80389*/
80390static int selectColumnsFromExprList(
80391  Parse *pParse,          /* Parsing context */
80392  ExprList *pEList,       /* Expr list from which to derive column names */
80393  int *pnCol,             /* Write the number of columns here */
80394  Column **paCol          /* Write the new column list here */
80395){
80396  sqlite3 *db = pParse->db;   /* Database connection */
80397  int i, j;                   /* Loop counters */
80398  int cnt;                    /* Index added to make the name unique */
80399  Column *aCol, *pCol;        /* For looping over result columns */
80400  int nCol;                   /* Number of columns in the result set */
80401  Expr *p;                    /* Expression for a single result column */
80402  char *zName;                /* Column name */
80403  int nName;                  /* Size of name in zName[] */
80404
80405  *pnCol = nCol = pEList->nExpr;
80406  aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
80407  if( aCol==0 ) return SQLITE_NOMEM;
80408  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
80409    /* Get an appropriate name for the column
80410    */
80411    p = pEList->a[i].pExpr;
80412    assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
80413               || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
80414    if( (zName = pEList->a[i].zName)!=0 ){
80415      /* If the column contains an "AS <name>" phrase, use <name> as the name */
80416      zName = sqlite3DbStrDup(db, zName);
80417    }else{
80418      Expr *pColExpr = p;  /* The expression that is the result column name */
80419      Table *pTab;         /* Table associated with this expression */
80420      while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
80421      if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
80422        /* For columns use the column name name */
80423        int iCol = pColExpr->iColumn;
80424        pTab = pColExpr->pTab;
80425        if( iCol<0 ) iCol = pTab->iPKey;
80426        zName = sqlite3MPrintf(db, "%s",
80427                 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
80428      }else if( pColExpr->op==TK_ID ){
80429        assert( !ExprHasProperty(pColExpr, EP_IntValue) );
80430        zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
80431      }else{
80432        /* Use the original text of the column expression as its name */
80433        zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
80434      }
80435    }
80436    if( db->mallocFailed ){
80437      sqlite3DbFree(db, zName);
80438      break;
80439    }
80440
80441    /* Make sure the column name is unique.  If the name is not unique,
80442    ** append a integer to the name so that it becomes unique.
80443    */
80444    nName = sqlite3Strlen30(zName);
80445    for(j=cnt=0; j<i; j++){
80446      if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
80447        char *zNewName;
80448        zName[nName] = 0;
80449        zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
80450        sqlite3DbFree(db, zName);
80451        zName = zNewName;
80452        j = -1;
80453        if( zName==0 ) break;
80454      }
80455    }
80456    pCol->zName = zName;
80457  }
80458  if( db->mallocFailed ){
80459    for(j=0; j<i; j++){
80460      sqlite3DbFree(db, aCol[j].zName);
80461    }
80462    sqlite3DbFree(db, aCol);
80463    *paCol = 0;
80464    *pnCol = 0;
80465    return SQLITE_NOMEM;
80466  }
80467  return SQLITE_OK;
80468}
80469
80470/*
80471** Add type and collation information to a column list based on
80472** a SELECT statement.
80473**
80474** The column list presumably came from selectColumnNamesFromExprList().
80475** The column list has only names, not types or collations.  This
80476** routine goes through and adds the types and collations.
80477**
80478** This routine requires that all identifiers in the SELECT
80479** statement be resolved.
80480*/
80481static void selectAddColumnTypeAndCollation(
80482  Parse *pParse,        /* Parsing contexts */
80483  int nCol,             /* Number of columns */
80484  Column *aCol,         /* List of columns */
80485  Select *pSelect       /* SELECT used to determine types and collations */
80486){
80487  sqlite3 *db = pParse->db;
80488  NameContext sNC;
80489  Column *pCol;
80490  CollSeq *pColl;
80491  int i;
80492  Expr *p;
80493  struct ExprList_item *a;
80494
80495  assert( pSelect!=0 );
80496  assert( (pSelect->selFlags & SF_Resolved)!=0 );
80497  assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
80498  if( db->mallocFailed ) return;
80499  memset(&sNC, 0, sizeof(sNC));
80500  sNC.pSrcList = pSelect->pSrc;
80501  a = pSelect->pEList->a;
80502  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
80503    p = a[i].pExpr;
80504    pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
80505    pCol->affinity = sqlite3ExprAffinity(p);
80506    if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
80507    pColl = sqlite3ExprCollSeq(pParse, p);
80508    if( pColl ){
80509      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
80510    }
80511  }
80512}
80513
80514/*
80515** Given a SELECT statement, generate a Table structure that describes
80516** the result set of that SELECT.
80517*/
80518SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
80519  Table *pTab;
80520  sqlite3 *db = pParse->db;
80521  int savedFlags;
80522
80523  savedFlags = db->flags;
80524  db->flags &= ~SQLITE_FullColNames;
80525  db->flags |= SQLITE_ShortColNames;
80526  sqlite3SelectPrep(pParse, pSelect, 0);
80527  if( pParse->nErr ) return 0;
80528  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
80529  db->flags = savedFlags;
80530  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
80531  if( pTab==0 ){
80532    return 0;
80533  }
80534  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
80535  ** is disabled, so we might as well hard-code pTab->dbMem to NULL. */
80536  assert( db->lookaside.bEnabled==0 );
80537  pTab->dbMem = 0;
80538  pTab->nRef = 1;
80539  pTab->zName = 0;
80540  selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
80541  selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
80542  pTab->iPKey = -1;
80543  if( db->mallocFailed ){
80544    sqlite3DeleteTable(pTab);
80545    return 0;
80546  }
80547  return pTab;
80548}
80549
80550/*
80551** Get a VDBE for the given parser context.  Create a new one if necessary.
80552** If an error occurs, return NULL and leave a message in pParse.
80553*/
80554SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
80555  Vdbe *v = pParse->pVdbe;
80556  if( v==0 ){
80557    v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
80558#ifndef SQLITE_OMIT_TRACE
80559    if( v ){
80560      sqlite3VdbeAddOp0(v, OP_Trace);
80561    }
80562#endif
80563  }
80564  return v;
80565}
80566
80567
80568/*
80569** Compute the iLimit and iOffset fields of the SELECT based on the
80570** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
80571** that appear in the original SQL statement after the LIMIT and OFFSET
80572** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
80573** are the integer memory register numbers for counters used to compute
80574** the limit and offset.  If there is no limit and/or offset, then
80575** iLimit and iOffset are negative.
80576**
80577** This routine changes the values of iLimit and iOffset only if
80578** a limit or offset is defined by pLimit and pOffset.  iLimit and
80579** iOffset should have been preset to appropriate default values
80580** (usually but not always -1) prior to calling this routine.
80581** Only if pLimit!=0 or pOffset!=0 do the limit registers get
80582** redefined.  The UNION ALL operator uses this property to force
80583** the reuse of the same limit and offset registers across multiple
80584** SELECT statements.
80585*/
80586static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
80587  Vdbe *v = 0;
80588  int iLimit = 0;
80589  int iOffset;
80590  int addr1, n;
80591  if( p->iLimit ) return;
80592
80593  /*
80594  ** "LIMIT -1" always shows all rows.  There is some
80595  ** contraversy about what the correct behavior should be.
80596  ** The current implementation interprets "LIMIT 0" to mean
80597  ** no rows.
80598  */
80599  sqlite3ExprCacheClear(pParse);
80600  assert( p->pOffset==0 || p->pLimit!=0 );
80601  if( p->pLimit ){
80602    p->iLimit = iLimit = ++pParse->nMem;
80603    v = sqlite3GetVdbe(pParse);
80604    if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
80605    if( sqlite3ExprIsInteger(p->pLimit, &n) ){
80606      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
80607      VdbeComment((v, "LIMIT counter"));
80608      if( n==0 ){
80609        sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
80610      }
80611    }else{
80612      sqlite3ExprCode(pParse, p->pLimit, iLimit);
80613      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
80614      VdbeComment((v, "LIMIT counter"));
80615      sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
80616    }
80617    if( p->pOffset ){
80618      p->iOffset = iOffset = ++pParse->nMem;
80619      pParse->nMem++;   /* Allocate an extra register for limit+offset */
80620      sqlite3ExprCode(pParse, p->pOffset, iOffset);
80621      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
80622      VdbeComment((v, "OFFSET counter"));
80623      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
80624      sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
80625      sqlite3VdbeJumpHere(v, addr1);
80626      sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
80627      VdbeComment((v, "LIMIT+OFFSET"));
80628      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
80629      sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
80630      sqlite3VdbeJumpHere(v, addr1);
80631    }
80632  }
80633}
80634
80635#ifndef SQLITE_OMIT_COMPOUND_SELECT
80636/*
80637** Return the appropriate collating sequence for the iCol-th column of
80638** the result set for the compound-select statement "p".  Return NULL if
80639** the column has no default collating sequence.
80640**
80641** The collating sequence for the compound select is taken from the
80642** left-most term of the select that has a collating sequence.
80643*/
80644static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
80645  CollSeq *pRet;
80646  if( p->pPrior ){
80647    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
80648  }else{
80649    pRet = 0;
80650  }
80651  assert( iCol>=0 );
80652  if( pRet==0 && iCol<p->pEList->nExpr ){
80653    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
80654  }
80655  return pRet;
80656}
80657#endif /* SQLITE_OMIT_COMPOUND_SELECT */
80658
80659/* Forward reference */
80660static int multiSelectOrderBy(
80661  Parse *pParse,        /* Parsing context */
80662  Select *p,            /* The right-most of SELECTs to be coded */
80663  SelectDest *pDest     /* What to do with query results */
80664);
80665
80666
80667#ifndef SQLITE_OMIT_COMPOUND_SELECT
80668/*
80669** This routine is called to process a compound query form from
80670** two or more separate queries using UNION, UNION ALL, EXCEPT, or
80671** INTERSECT
80672**
80673** "p" points to the right-most of the two queries.  the query on the
80674** left is p->pPrior.  The left query could also be a compound query
80675** in which case this routine will be called recursively.
80676**
80677** The results of the total query are to be written into a destination
80678** of type eDest with parameter iParm.
80679**
80680** Example 1:  Consider a three-way compound SQL statement.
80681**
80682**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
80683**
80684** This statement is parsed up as follows:
80685**
80686**     SELECT c FROM t3
80687**      |
80688**      `----->  SELECT b FROM t2
80689**                |
80690**                `------>  SELECT a FROM t1
80691**
80692** The arrows in the diagram above represent the Select.pPrior pointer.
80693** So if this routine is called with p equal to the t3 query, then
80694** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
80695**
80696** Notice that because of the way SQLite parses compound SELECTs, the
80697** individual selects always group from left to right.
80698*/
80699static int multiSelect(
80700  Parse *pParse,        /* Parsing context */
80701  Select *p,            /* The right-most of SELECTs to be coded */
80702  SelectDest *pDest     /* What to do with query results */
80703){
80704  int rc = SQLITE_OK;   /* Success code from a subroutine */
80705  Select *pPrior;       /* Another SELECT immediately to our left */
80706  Vdbe *v;              /* Generate code to this VDBE */
80707  SelectDest dest;      /* Alternative data destination */
80708  Select *pDelete = 0;  /* Chain of simple selects to delete */
80709  sqlite3 *db;          /* Database connection */
80710
80711  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
80712  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
80713  */
80714  assert( p && p->pPrior );  /* Calling function guarantees this much */
80715  db = pParse->db;
80716  pPrior = p->pPrior;
80717  assert( pPrior->pRightmost!=pPrior );
80718  assert( pPrior->pRightmost==p->pRightmost );
80719  dest = *pDest;
80720  if( pPrior->pOrderBy ){
80721    sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
80722      selectOpName(p->op));
80723    rc = 1;
80724    goto multi_select_end;
80725  }
80726  if( pPrior->pLimit ){
80727    sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
80728      selectOpName(p->op));
80729    rc = 1;
80730    goto multi_select_end;
80731  }
80732
80733  v = sqlite3GetVdbe(pParse);
80734  assert( v!=0 );  /* The VDBE already created by calling function */
80735
80736  /* Create the destination temporary table if necessary
80737  */
80738  if( dest.eDest==SRT_EphemTab ){
80739    assert( p->pEList );
80740    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
80741    dest.eDest = SRT_Table;
80742  }
80743
80744  /* Make sure all SELECTs in the statement have the same number of elements
80745  ** in their result sets.
80746  */
80747  assert( p->pEList && pPrior->pEList );
80748  if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
80749    sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
80750      " do not have the same number of result columns", selectOpName(p->op));
80751    rc = 1;
80752    goto multi_select_end;
80753  }
80754
80755  /* Compound SELECTs that have an ORDER BY clause are handled separately.
80756  */
80757  if( p->pOrderBy ){
80758    return multiSelectOrderBy(pParse, p, pDest);
80759  }
80760
80761  /* Generate code for the left and right SELECT statements.
80762  */
80763  switch( p->op ){
80764    case TK_ALL: {
80765      int addr = 0;
80766      assert( !pPrior->pLimit );
80767      pPrior->pLimit = p->pLimit;
80768      pPrior->pOffset = p->pOffset;
80769      rc = sqlite3Select(pParse, pPrior, &dest);
80770      p->pLimit = 0;
80771      p->pOffset = 0;
80772      if( rc ){
80773        goto multi_select_end;
80774      }
80775      p->pPrior = 0;
80776      p->iLimit = pPrior->iLimit;
80777      p->iOffset = pPrior->iOffset;
80778      if( p->iLimit ){
80779        addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
80780        VdbeComment((v, "Jump ahead if LIMIT reached"));
80781      }
80782      rc = sqlite3Select(pParse, p, &dest);
80783      testcase( rc!=SQLITE_OK );
80784      pDelete = p->pPrior;
80785      p->pPrior = pPrior;
80786      if( addr ){
80787        sqlite3VdbeJumpHere(v, addr);
80788      }
80789      break;
80790    }
80791    case TK_EXCEPT:
80792    case TK_UNION: {
80793      int unionTab;    /* Cursor number of the temporary table holding result */
80794      u8 op = 0;       /* One of the SRT_ operations to apply to self */
80795      int priorOp;     /* The SRT_ operation to apply to prior selects */
80796      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
80797      int addr;
80798      SelectDest uniondest;
80799
80800      testcase( p->op==TK_EXCEPT );
80801      testcase( p->op==TK_UNION );
80802      priorOp = SRT_Union;
80803      if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
80804        /* We can reuse a temporary table generated by a SELECT to our
80805        ** right.
80806        */
80807        assert( p->pRightmost!=p );  /* Can only happen for leftward elements
80808                                     ** of a 3-way or more compound */
80809        assert( p->pLimit==0 );      /* Not allowed on leftward elements */
80810        assert( p->pOffset==0 );     /* Not allowed on leftward elements */
80811        unionTab = dest.iParm;
80812      }else{
80813        /* We will need to create our own temporary table to hold the
80814        ** intermediate results.
80815        */
80816        unionTab = pParse->nTab++;
80817        assert( p->pOrderBy==0 );
80818        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
80819        assert( p->addrOpenEphm[0] == -1 );
80820        p->addrOpenEphm[0] = addr;
80821        p->pRightmost->selFlags |= SF_UsesEphemeral;
80822        assert( p->pEList );
80823      }
80824
80825      /* Code the SELECT statements to our left
80826      */
80827      assert( !pPrior->pOrderBy );
80828      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
80829      rc = sqlite3Select(pParse, pPrior, &uniondest);
80830      if( rc ){
80831        goto multi_select_end;
80832      }
80833
80834      /* Code the current SELECT statement
80835      */
80836      if( p->op==TK_EXCEPT ){
80837        op = SRT_Except;
80838      }else{
80839        assert( p->op==TK_UNION );
80840        op = SRT_Union;
80841      }
80842      p->pPrior = 0;
80843      pLimit = p->pLimit;
80844      p->pLimit = 0;
80845      pOffset = p->pOffset;
80846      p->pOffset = 0;
80847      uniondest.eDest = op;
80848      rc = sqlite3Select(pParse, p, &uniondest);
80849      testcase( rc!=SQLITE_OK );
80850      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
80851      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
80852      sqlite3ExprListDelete(db, p->pOrderBy);
80853      pDelete = p->pPrior;
80854      p->pPrior = pPrior;
80855      p->pOrderBy = 0;
80856      sqlite3ExprDelete(db, p->pLimit);
80857      p->pLimit = pLimit;
80858      p->pOffset = pOffset;
80859      p->iLimit = 0;
80860      p->iOffset = 0;
80861
80862      /* Convert the data in the temporary table into whatever form
80863      ** it is that we currently need.
80864      */
80865      assert( unionTab==dest.iParm || dest.eDest!=priorOp );
80866      if( dest.eDest!=priorOp ){
80867        int iCont, iBreak, iStart;
80868        assert( p->pEList );
80869        if( dest.eDest==SRT_Output ){
80870          Select *pFirst = p;
80871          while( pFirst->pPrior ) pFirst = pFirst->pPrior;
80872          generateColumnNames(pParse, 0, pFirst->pEList);
80873        }
80874        iBreak = sqlite3VdbeMakeLabel(v);
80875        iCont = sqlite3VdbeMakeLabel(v);
80876        computeLimitRegisters(pParse, p, iBreak);
80877        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
80878        iStart = sqlite3VdbeCurrentAddr(v);
80879        selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
80880                        0, -1, &dest, iCont, iBreak);
80881        sqlite3VdbeResolveLabel(v, iCont);
80882        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
80883        sqlite3VdbeResolveLabel(v, iBreak);
80884        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
80885      }
80886      break;
80887    }
80888    default: assert( p->op==TK_INTERSECT ); {
80889      int tab1, tab2;
80890      int iCont, iBreak, iStart;
80891      Expr *pLimit, *pOffset;
80892      int addr;
80893      SelectDest intersectdest;
80894      int r1;
80895
80896      /* INTERSECT is different from the others since it requires
80897      ** two temporary tables.  Hence it has its own case.  Begin
80898      ** by allocating the tables we will need.
80899      */
80900      tab1 = pParse->nTab++;
80901      tab2 = pParse->nTab++;
80902      assert( p->pOrderBy==0 );
80903
80904      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
80905      assert( p->addrOpenEphm[0] == -1 );
80906      p->addrOpenEphm[0] = addr;
80907      p->pRightmost->selFlags |= SF_UsesEphemeral;
80908      assert( p->pEList );
80909
80910      /* Code the SELECTs to our left into temporary table "tab1".
80911      */
80912      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
80913      rc = sqlite3Select(pParse, pPrior, &intersectdest);
80914      if( rc ){
80915        goto multi_select_end;
80916      }
80917
80918      /* Code the current SELECT into temporary table "tab2"
80919      */
80920      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
80921      assert( p->addrOpenEphm[1] == -1 );
80922      p->addrOpenEphm[1] = addr;
80923      p->pPrior = 0;
80924      pLimit = p->pLimit;
80925      p->pLimit = 0;
80926      pOffset = p->pOffset;
80927      p->pOffset = 0;
80928      intersectdest.iParm = tab2;
80929      rc = sqlite3Select(pParse, p, &intersectdest);
80930      testcase( rc!=SQLITE_OK );
80931      pDelete = p->pPrior;
80932      p->pPrior = pPrior;
80933      sqlite3ExprDelete(db, p->pLimit);
80934      p->pLimit = pLimit;
80935      p->pOffset = pOffset;
80936
80937      /* Generate code to take the intersection of the two temporary
80938      ** tables.
80939      */
80940      assert( p->pEList );
80941      if( dest.eDest==SRT_Output ){
80942        Select *pFirst = p;
80943        while( pFirst->pPrior ) pFirst = pFirst->pPrior;
80944        generateColumnNames(pParse, 0, pFirst->pEList);
80945      }
80946      iBreak = sqlite3VdbeMakeLabel(v);
80947      iCont = sqlite3VdbeMakeLabel(v);
80948      computeLimitRegisters(pParse, p, iBreak);
80949      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
80950      r1 = sqlite3GetTempReg(pParse);
80951      iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
80952      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
80953      sqlite3ReleaseTempReg(pParse, r1);
80954      selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
80955                      0, -1, &dest, iCont, iBreak);
80956      sqlite3VdbeResolveLabel(v, iCont);
80957      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
80958      sqlite3VdbeResolveLabel(v, iBreak);
80959      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
80960      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
80961      break;
80962    }
80963  }
80964
80965  /* Compute collating sequences used by
80966  ** temporary tables needed to implement the compound select.
80967  ** Attach the KeyInfo structure to all temporary tables.
80968  **
80969  ** This section is run by the right-most SELECT statement only.
80970  ** SELECT statements to the left always skip this part.  The right-most
80971  ** SELECT might also skip this part if it has no ORDER BY clause and
80972  ** no temp tables are required.
80973  */
80974  if( p->selFlags & SF_UsesEphemeral ){
80975    int i;                        /* Loop counter */
80976    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
80977    Select *pLoop;                /* For looping through SELECT statements */
80978    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
80979    int nCol;                     /* Number of columns in result set */
80980
80981    assert( p->pRightmost==p );
80982    nCol = p->pEList->nExpr;
80983    pKeyInfo = sqlite3DbMallocZero(db,
80984                       sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
80985    if( !pKeyInfo ){
80986      rc = SQLITE_NOMEM;
80987      goto multi_select_end;
80988    }
80989
80990    pKeyInfo->enc = ENC(db);
80991    pKeyInfo->nField = (u16)nCol;
80992
80993    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
80994      *apColl = multiSelectCollSeq(pParse, p, i);
80995      if( 0==*apColl ){
80996        *apColl = db->pDfltColl;
80997      }
80998    }
80999
81000    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
81001      for(i=0; i<2; i++){
81002        int addr = pLoop->addrOpenEphm[i];
81003        if( addr<0 ){
81004          /* If [0] is unused then [1] is also unused.  So we can
81005          ** always safely abort as soon as the first unused slot is found */
81006          assert( pLoop->addrOpenEphm[1]<0 );
81007          break;
81008        }
81009        sqlite3VdbeChangeP2(v, addr, nCol);
81010        sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
81011        pLoop->addrOpenEphm[i] = -1;
81012      }
81013    }
81014    sqlite3DbFree(db, pKeyInfo);
81015  }
81016
81017multi_select_end:
81018  pDest->iMem = dest.iMem;
81019  pDest->nMem = dest.nMem;
81020  sqlite3SelectDelete(db, pDelete);
81021  return rc;
81022}
81023#endif /* SQLITE_OMIT_COMPOUND_SELECT */
81024
81025/*
81026** Code an output subroutine for a coroutine implementation of a
81027** SELECT statment.
81028**
81029** The data to be output is contained in pIn->iMem.  There are
81030** pIn->nMem columns to be output.  pDest is where the output should
81031** be sent.
81032**
81033** regReturn is the number of the register holding the subroutine
81034** return address.
81035**
81036** If regPrev>0 then it is a the first register in a vector that
81037** records the previous output.  mem[regPrev] is a flag that is false
81038** if there has been no previous output.  If regPrev>0 then code is
81039** generated to suppress duplicates.  pKeyInfo is used for comparing
81040** keys.
81041**
81042** If the LIMIT found in p->iLimit is reached, jump immediately to
81043** iBreak.
81044*/
81045static int generateOutputSubroutine(
81046  Parse *pParse,          /* Parsing context */
81047  Select *p,              /* The SELECT statement */
81048  SelectDest *pIn,        /* Coroutine supplying data */
81049  SelectDest *pDest,      /* Where to send the data */
81050  int regReturn,          /* The return address register */
81051  int regPrev,            /* Previous result register.  No uniqueness if 0 */
81052  KeyInfo *pKeyInfo,      /* For comparing with previous entry */
81053  int p4type,             /* The p4 type for pKeyInfo */
81054  int iBreak              /* Jump here if we hit the LIMIT */
81055){
81056  Vdbe *v = pParse->pVdbe;
81057  int iContinue;
81058  int addr;
81059
81060  addr = sqlite3VdbeCurrentAddr(v);
81061  iContinue = sqlite3VdbeMakeLabel(v);
81062
81063  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
81064  */
81065  if( regPrev ){
81066    int j1, j2;
81067    j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
81068    j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
81069                              (char*)pKeyInfo, p4type);
81070    sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
81071    sqlite3VdbeJumpHere(v, j1);
81072    sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
81073    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
81074  }
81075  if( pParse->db->mallocFailed ) return 0;
81076
81077  /* Suppress the the first OFFSET entries if there is an OFFSET clause
81078  */
81079  codeOffset(v, p, iContinue);
81080
81081  switch( pDest->eDest ){
81082    /* Store the result as data using a unique key.
81083    */
81084    case SRT_Table:
81085    case SRT_EphemTab: {
81086      int r1 = sqlite3GetTempReg(pParse);
81087      int r2 = sqlite3GetTempReg(pParse);
81088      testcase( pDest->eDest==SRT_Table );
81089      testcase( pDest->eDest==SRT_EphemTab );
81090      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
81091      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
81092      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
81093      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
81094      sqlite3ReleaseTempReg(pParse, r2);
81095      sqlite3ReleaseTempReg(pParse, r1);
81096      break;
81097    }
81098
81099#ifndef SQLITE_OMIT_SUBQUERY
81100    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
81101    ** then there should be a single item on the stack.  Write this
81102    ** item into the set table with bogus data.
81103    */
81104    case SRT_Set: {
81105      int r1;
81106      assert( pIn->nMem==1 );
81107      p->affinity =
81108         sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
81109      r1 = sqlite3GetTempReg(pParse);
81110      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
81111      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
81112      sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
81113      sqlite3ReleaseTempReg(pParse, r1);
81114      break;
81115    }
81116
81117#if 0  /* Never occurs on an ORDER BY query */
81118    /* If any row exist in the result set, record that fact and abort.
81119    */
81120    case SRT_Exists: {
81121      sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
81122      /* The LIMIT clause will terminate the loop for us */
81123      break;
81124    }
81125#endif
81126
81127    /* If this is a scalar select that is part of an expression, then
81128    ** store the results in the appropriate memory cell and break out
81129    ** of the scan loop.
81130    */
81131    case SRT_Mem: {
81132      assert( pIn->nMem==1 );
81133      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
81134      /* The LIMIT clause will jump out of the loop for us */
81135      break;
81136    }
81137#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
81138
81139    /* The results are stored in a sequence of registers
81140    ** starting at pDest->iMem.  Then the co-routine yields.
81141    */
81142    case SRT_Coroutine: {
81143      if( pDest->iMem==0 ){
81144        pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
81145        pDest->nMem = pIn->nMem;
81146      }
81147      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
81148      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
81149      break;
81150    }
81151
81152    /* If none of the above, then the result destination must be
81153    ** SRT_Output.  This routine is never called with any other
81154    ** destination other than the ones handled above or SRT_Output.
81155    **
81156    ** For SRT_Output, results are stored in a sequence of registers.
81157    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
81158    ** return the next row of result.
81159    */
81160    default: {
81161      assert( pDest->eDest==SRT_Output );
81162      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
81163      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
81164      break;
81165    }
81166  }
81167
81168  /* Jump to the end of the loop if the LIMIT is reached.
81169  */
81170  if( p->iLimit ){
81171    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
81172  }
81173
81174  /* Generate the subroutine return
81175  */
81176  sqlite3VdbeResolveLabel(v, iContinue);
81177  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
81178
81179  return addr;
81180}
81181
81182/*
81183** Alternative compound select code generator for cases when there
81184** is an ORDER BY clause.
81185**
81186** We assume a query of the following form:
81187**
81188**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
81189**
81190** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
81191** is to code both <selectA> and <selectB> with the ORDER BY clause as
81192** co-routines.  Then run the co-routines in parallel and merge the results
81193** into the output.  In addition to the two coroutines (called selectA and
81194** selectB) there are 7 subroutines:
81195**
81196**    outA:    Move the output of the selectA coroutine into the output
81197**             of the compound query.
81198**
81199**    outB:    Move the output of the selectB coroutine into the output
81200**             of the compound query.  (Only generated for UNION and
81201**             UNION ALL.  EXCEPT and INSERTSECT never output a row that
81202**             appears only in B.)
81203**
81204**    AltB:    Called when there is data from both coroutines and A<B.
81205**
81206**    AeqB:    Called when there is data from both coroutines and A==B.
81207**
81208**    AgtB:    Called when there is data from both coroutines and A>B.
81209**
81210**    EofA:    Called when data is exhausted from selectA.
81211**
81212**    EofB:    Called when data is exhausted from selectB.
81213**
81214** The implementation of the latter five subroutines depend on which
81215** <operator> is used:
81216**
81217**
81218**             UNION ALL         UNION            EXCEPT          INTERSECT
81219**          -------------  -----------------  --------------  -----------------
81220**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
81221**
81222**   AeqB:   outA, nextA         nextA             nextA         outA, nextA
81223**
81224**   AgtB:   outB, nextB      outB, nextB          nextB            nextB
81225**
81226**   EofA:   outB, nextB      outB, nextB          halt             halt
81227**
81228**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
81229**
81230** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
81231** causes an immediate jump to EofA and an EOF on B following nextB causes
81232** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
81233** following nextX causes a jump to the end of the select processing.
81234**
81235** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
81236** within the output subroutine.  The regPrev register set holds the previously
81237** output value.  A comparison is made against this value and the output
81238** is skipped if the next results would be the same as the previous.
81239**
81240** The implementation plan is to implement the two coroutines and seven
81241** subroutines first, then put the control logic at the bottom.  Like this:
81242**
81243**          goto Init
81244**     coA: coroutine for left query (A)
81245**     coB: coroutine for right query (B)
81246**    outA: output one row of A
81247**    outB: output one row of B (UNION and UNION ALL only)
81248**    EofA: ...
81249**    EofB: ...
81250**    AltB: ...
81251**    AeqB: ...
81252**    AgtB: ...
81253**    Init: initialize coroutine registers
81254**          yield coA
81255**          if eof(A) goto EofA
81256**          yield coB
81257**          if eof(B) goto EofB
81258**    Cmpr: Compare A, B
81259**          Jump AltB, AeqB, AgtB
81260**     End: ...
81261**
81262** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
81263** actually called using Gosub and they do not Return.  EofA and EofB loop
81264** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
81265** and AgtB jump to either L2 or to one of EofA or EofB.
81266*/
81267#ifndef SQLITE_OMIT_COMPOUND_SELECT
81268static int multiSelectOrderBy(
81269  Parse *pParse,        /* Parsing context */
81270  Select *p,            /* The right-most of SELECTs to be coded */
81271  SelectDest *pDest     /* What to do with query results */
81272){
81273  int i, j;             /* Loop counters */
81274  Select *pPrior;       /* Another SELECT immediately to our left */
81275  Vdbe *v;              /* Generate code to this VDBE */
81276  SelectDest destA;     /* Destination for coroutine A */
81277  SelectDest destB;     /* Destination for coroutine B */
81278  int regAddrA;         /* Address register for select-A coroutine */
81279  int regEofA;          /* Flag to indicate when select-A is complete */
81280  int regAddrB;         /* Address register for select-B coroutine */
81281  int regEofB;          /* Flag to indicate when select-B is complete */
81282  int addrSelectA;      /* Address of the select-A coroutine */
81283  int addrSelectB;      /* Address of the select-B coroutine */
81284  int regOutA;          /* Address register for the output-A subroutine */
81285  int regOutB;          /* Address register for the output-B subroutine */
81286  int addrOutA;         /* Address of the output-A subroutine */
81287  int addrOutB = 0;     /* Address of the output-B subroutine */
81288  int addrEofA;         /* Address of the select-A-exhausted subroutine */
81289  int addrEofB;         /* Address of the select-B-exhausted subroutine */
81290  int addrAltB;         /* Address of the A<B subroutine */
81291  int addrAeqB;         /* Address of the A==B subroutine */
81292  int addrAgtB;         /* Address of the A>B subroutine */
81293  int regLimitA;        /* Limit register for select-A */
81294  int regLimitB;        /* Limit register for select-A */
81295  int regPrev;          /* A range of registers to hold previous output */
81296  int savedLimit;       /* Saved value of p->iLimit */
81297  int savedOffset;      /* Saved value of p->iOffset */
81298  int labelCmpr;        /* Label for the start of the merge algorithm */
81299  int labelEnd;         /* Label for the end of the overall SELECT stmt */
81300  int j1;               /* Jump instructions that get retargetted */
81301  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
81302  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
81303  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
81304  sqlite3 *db;          /* Database connection */
81305  ExprList *pOrderBy;   /* The ORDER BY clause */
81306  int nOrderBy;         /* Number of terms in the ORDER BY clause */
81307  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
81308
81309  assert( p->pOrderBy!=0 );
81310  assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
81311  db = pParse->db;
81312  v = pParse->pVdbe;
81313  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
81314  labelEnd = sqlite3VdbeMakeLabel(v);
81315  labelCmpr = sqlite3VdbeMakeLabel(v);
81316
81317
81318  /* Patch up the ORDER BY clause
81319  */
81320  op = p->op;
81321  pPrior = p->pPrior;
81322  assert( pPrior->pOrderBy==0 );
81323  pOrderBy = p->pOrderBy;
81324  assert( pOrderBy );
81325  nOrderBy = pOrderBy->nExpr;
81326
81327  /* For operators other than UNION ALL we have to make sure that
81328  ** the ORDER BY clause covers every term of the result set.  Add
81329  ** terms to the ORDER BY clause as necessary.
81330  */
81331  if( op!=TK_ALL ){
81332    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
81333      struct ExprList_item *pItem;
81334      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
81335        assert( pItem->iCol>0 );
81336        if( pItem->iCol==i ) break;
81337      }
81338      if( j==nOrderBy ){
81339        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
81340        if( pNew==0 ) return SQLITE_NOMEM;
81341        pNew->flags |= EP_IntValue;
81342        pNew->u.iValue = i;
81343        pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
81344        pOrderBy->a[nOrderBy++].iCol = (u16)i;
81345      }
81346    }
81347  }
81348
81349  /* Compute the comparison permutation and keyinfo that is used with
81350  ** the permutation used to determine if the next
81351  ** row of results comes from selectA or selectB.  Also add explicit
81352  ** collations to the ORDER BY clause terms so that when the subqueries
81353  ** to the right and the left are evaluated, they use the correct
81354  ** collation.
81355  */
81356  aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
81357  if( aPermute ){
81358    struct ExprList_item *pItem;
81359    for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
81360      assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
81361      aPermute[i] = pItem->iCol - 1;
81362    }
81363    pKeyMerge =
81364      sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
81365    if( pKeyMerge ){
81366      pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
81367      pKeyMerge->nField = (u16)nOrderBy;
81368      pKeyMerge->enc = ENC(db);
81369      for(i=0; i<nOrderBy; i++){
81370        CollSeq *pColl;
81371        Expr *pTerm = pOrderBy->a[i].pExpr;
81372        if( pTerm->flags & EP_ExpCollate ){
81373          pColl = pTerm->pColl;
81374        }else{
81375          pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
81376          pTerm->flags |= EP_ExpCollate;
81377          pTerm->pColl = pColl;
81378        }
81379        pKeyMerge->aColl[i] = pColl;
81380        pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
81381      }
81382    }
81383  }else{
81384    pKeyMerge = 0;
81385  }
81386
81387  /* Reattach the ORDER BY clause to the query.
81388  */
81389  p->pOrderBy = pOrderBy;
81390  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
81391
81392  /* Allocate a range of temporary registers and the KeyInfo needed
81393  ** for the logic that removes duplicate result rows when the
81394  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
81395  */
81396  if( op==TK_ALL ){
81397    regPrev = 0;
81398  }else{
81399    int nExpr = p->pEList->nExpr;
81400    assert( nOrderBy>=nExpr || db->mallocFailed );
81401    regPrev = sqlite3GetTempRange(pParse, nExpr+1);
81402    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
81403    pKeyDup = sqlite3DbMallocZero(db,
81404                  sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
81405    if( pKeyDup ){
81406      pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
81407      pKeyDup->nField = (u16)nExpr;
81408      pKeyDup->enc = ENC(db);
81409      for(i=0; i<nExpr; i++){
81410        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
81411        pKeyDup->aSortOrder[i] = 0;
81412      }
81413    }
81414  }
81415
81416  /* Separate the left and the right query from one another
81417  */
81418  p->pPrior = 0;
81419  pPrior->pRightmost = 0;
81420  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
81421  if( pPrior->pPrior==0 ){
81422    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
81423  }
81424
81425  /* Compute the limit registers */
81426  computeLimitRegisters(pParse, p, labelEnd);
81427  if( p->iLimit && op==TK_ALL ){
81428    regLimitA = ++pParse->nMem;
81429    regLimitB = ++pParse->nMem;
81430    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
81431                                  regLimitA);
81432    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
81433  }else{
81434    regLimitA = regLimitB = 0;
81435  }
81436  sqlite3ExprDelete(db, p->pLimit);
81437  p->pLimit = 0;
81438  sqlite3ExprDelete(db, p->pOffset);
81439  p->pOffset = 0;
81440
81441  regAddrA = ++pParse->nMem;
81442  regEofA = ++pParse->nMem;
81443  regAddrB = ++pParse->nMem;
81444  regEofB = ++pParse->nMem;
81445  regOutA = ++pParse->nMem;
81446  regOutB = ++pParse->nMem;
81447  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
81448  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
81449
81450  /* Jump past the various subroutines and coroutines to the main
81451  ** merge loop
81452  */
81453  j1 = sqlite3VdbeAddOp0(v, OP_Goto);
81454  addrSelectA = sqlite3VdbeCurrentAddr(v);
81455
81456
81457  /* Generate a coroutine to evaluate the SELECT statement to the
81458  ** left of the compound operator - the "A" select.
81459  */
81460  VdbeNoopComment((v, "Begin coroutine for left SELECT"));
81461  pPrior->iLimit = regLimitA;
81462  sqlite3Select(pParse, pPrior, &destA);
81463  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
81464  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
81465  VdbeNoopComment((v, "End coroutine for left SELECT"));
81466
81467  /* Generate a coroutine to evaluate the SELECT statement on
81468  ** the right - the "B" select
81469  */
81470  addrSelectB = sqlite3VdbeCurrentAddr(v);
81471  VdbeNoopComment((v, "Begin coroutine for right SELECT"));
81472  savedLimit = p->iLimit;
81473  savedOffset = p->iOffset;
81474  p->iLimit = regLimitB;
81475  p->iOffset = 0;
81476  sqlite3Select(pParse, p, &destB);
81477  p->iLimit = savedLimit;
81478  p->iOffset = savedOffset;
81479  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
81480  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
81481  VdbeNoopComment((v, "End coroutine for right SELECT"));
81482
81483  /* Generate a subroutine that outputs the current row of the A
81484  ** select as the next output row of the compound select.
81485  */
81486  VdbeNoopComment((v, "Output routine for A"));
81487  addrOutA = generateOutputSubroutine(pParse,
81488                 p, &destA, pDest, regOutA,
81489                 regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
81490
81491  /* Generate a subroutine that outputs the current row of the B
81492  ** select as the next output row of the compound select.
81493  */
81494  if( op==TK_ALL || op==TK_UNION ){
81495    VdbeNoopComment((v, "Output routine for B"));
81496    addrOutB = generateOutputSubroutine(pParse,
81497                 p, &destB, pDest, regOutB,
81498                 regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
81499  }
81500
81501  /* Generate a subroutine to run when the results from select A
81502  ** are exhausted and only data in select B remains.
81503  */
81504  VdbeNoopComment((v, "eof-A subroutine"));
81505  if( op==TK_EXCEPT || op==TK_INTERSECT ){
81506    addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
81507  }else{
81508    addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
81509    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
81510    sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
81511    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
81512  }
81513
81514  /* Generate a subroutine to run when the results from select B
81515  ** are exhausted and only data in select A remains.
81516  */
81517  if( op==TK_INTERSECT ){
81518    addrEofB = addrEofA;
81519  }else{
81520    VdbeNoopComment((v, "eof-B subroutine"));
81521    addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
81522    sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
81523    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
81524    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
81525  }
81526
81527  /* Generate code to handle the case of A<B
81528  */
81529  VdbeNoopComment((v, "A-lt-B subroutine"));
81530  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
81531  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
81532  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
81533  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
81534
81535  /* Generate code to handle the case of A==B
81536  */
81537  if( op==TK_ALL ){
81538    addrAeqB = addrAltB;
81539  }else if( op==TK_INTERSECT ){
81540    addrAeqB = addrAltB;
81541    addrAltB++;
81542  }else{
81543    VdbeNoopComment((v, "A-eq-B subroutine"));
81544    addrAeqB =
81545    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
81546    sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
81547    sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
81548  }
81549
81550  /* Generate code to handle the case of A>B
81551  */
81552  VdbeNoopComment((v, "A-gt-B subroutine"));
81553  addrAgtB = sqlite3VdbeCurrentAddr(v);
81554  if( op==TK_ALL || op==TK_UNION ){
81555    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
81556  }
81557  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
81558  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
81559  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
81560
81561  /* This code runs once to initialize everything.
81562  */
81563  sqlite3VdbeJumpHere(v, j1);
81564  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
81565  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
81566  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
81567  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
81568  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
81569  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
81570
81571  /* Implement the main merge loop
81572  */
81573  sqlite3VdbeResolveLabel(v, labelCmpr);
81574  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
81575  sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
81576                         (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
81577  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
81578
81579  /* Release temporary registers
81580  */
81581  if( regPrev ){
81582    sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
81583  }
81584
81585  /* Jump to the this point in order to terminate the query.
81586  */
81587  sqlite3VdbeResolveLabel(v, labelEnd);
81588
81589  /* Set the number of output columns
81590  */
81591  if( pDest->eDest==SRT_Output ){
81592    Select *pFirst = pPrior;
81593    while( pFirst->pPrior ) pFirst = pFirst->pPrior;
81594    generateColumnNames(pParse, 0, pFirst->pEList);
81595  }
81596
81597  /* Reassembly the compound query so that it will be freed correctly
81598  ** by the calling function */
81599  if( p->pPrior ){
81600    sqlite3SelectDelete(db, p->pPrior);
81601  }
81602  p->pPrior = pPrior;
81603
81604  /*** TBD:  Insert subroutine calls to close cursors on incomplete
81605  **** subqueries ****/
81606  return SQLITE_OK;
81607}
81608#endif
81609
81610#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
81611/* Forward Declarations */
81612static void substExprList(sqlite3*, ExprList*, int, ExprList*);
81613static void substSelect(sqlite3*, Select *, int, ExprList *);
81614
81615/*
81616** Scan through the expression pExpr.  Replace every reference to
81617** a column in table number iTable with a copy of the iColumn-th
81618** entry in pEList.  (But leave references to the ROWID column
81619** unchanged.)
81620**
81621** This routine is part of the flattening procedure.  A subquery
81622** whose result set is defined by pEList appears as entry in the
81623** FROM clause of a SELECT such that the VDBE cursor assigned to that
81624** FORM clause entry is iTable.  This routine make the necessary
81625** changes to pExpr so that it refers directly to the source table
81626** of the subquery rather the result set of the subquery.
81627*/
81628static Expr *substExpr(
81629  sqlite3 *db,        /* Report malloc errors to this connection */
81630  Expr *pExpr,        /* Expr in which substitution occurs */
81631  int iTable,         /* Table to be substituted */
81632  ExprList *pEList    /* Substitute expressions */
81633){
81634  if( pExpr==0 ) return 0;
81635  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
81636    if( pExpr->iColumn<0 ){
81637      pExpr->op = TK_NULL;
81638    }else{
81639      Expr *pNew;
81640      assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
81641      assert( pExpr->pLeft==0 && pExpr->pRight==0 );
81642      pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
81643      if( pNew && pExpr->pColl ){
81644        pNew->pColl = pExpr->pColl;
81645      }
81646      sqlite3ExprDelete(db, pExpr);
81647      pExpr = pNew;
81648    }
81649  }else{
81650    pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
81651    pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
81652    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
81653      substSelect(db, pExpr->x.pSelect, iTable, pEList);
81654    }else{
81655      substExprList(db, pExpr->x.pList, iTable, pEList);
81656    }
81657  }
81658  return pExpr;
81659}
81660static void substExprList(
81661  sqlite3 *db,         /* Report malloc errors here */
81662  ExprList *pList,     /* List to scan and in which to make substitutes */
81663  int iTable,          /* Table to be substituted */
81664  ExprList *pEList     /* Substitute values */
81665){
81666  int i;
81667  if( pList==0 ) return;
81668  for(i=0; i<pList->nExpr; i++){
81669    pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
81670  }
81671}
81672static void substSelect(
81673  sqlite3 *db,         /* Report malloc errors here */
81674  Select *p,           /* SELECT statement in which to make substitutions */
81675  int iTable,          /* Table to be replaced */
81676  ExprList *pEList     /* Substitute values */
81677){
81678  SrcList *pSrc;
81679  struct SrcList_item *pItem;
81680  int i;
81681  if( !p ) return;
81682  substExprList(db, p->pEList, iTable, pEList);
81683  substExprList(db, p->pGroupBy, iTable, pEList);
81684  substExprList(db, p->pOrderBy, iTable, pEList);
81685  p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
81686  p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
81687  substSelect(db, p->pPrior, iTable, pEList);
81688  pSrc = p->pSrc;
81689  assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
81690  if( ALWAYS(pSrc) ){
81691    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
81692      substSelect(db, pItem->pSelect, iTable, pEList);
81693    }
81694  }
81695}
81696#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
81697
81698#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
81699/*
81700** This routine attempts to flatten subqueries in order to speed
81701** execution.  It returns 1 if it makes changes and 0 if no flattening
81702** occurs.
81703**
81704** To understand the concept of flattening, consider the following
81705** query:
81706**
81707**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
81708**
81709** The default way of implementing this query is to execute the
81710** subquery first and store the results in a temporary table, then
81711** run the outer query on that temporary table.  This requires two
81712** passes over the data.  Furthermore, because the temporary table
81713** has no indices, the WHERE clause on the outer query cannot be
81714** optimized.
81715**
81716** This routine attempts to rewrite queries such as the above into
81717** a single flat select, like this:
81718**
81719**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
81720**
81721** The code generated for this simpification gives the same result
81722** but only has to scan the data once.  And because indices might
81723** exist on the table t1, a complete scan of the data might be
81724** avoided.
81725**
81726** Flattening is only attempted if all of the following are true:
81727**
81728**   (1)  The subquery and the outer query do not both use aggregates.
81729**
81730**   (2)  The subquery is not an aggregate or the outer query is not a join.
81731**
81732**   (3)  The subquery is not the right operand of a left outer join
81733**        (Originally ticket #306.  Strenghtened by ticket #3300)
81734**
81735**   (4)  The subquery is not DISTINCT or the outer query is not a join.
81736**
81737**   (5)  The subquery is not DISTINCT or the outer query does not use
81738**        aggregates.
81739**
81740**   (6)  The subquery does not use aggregates or the outer query is not
81741**        DISTINCT.
81742**
81743**   (7)  The subquery has a FROM clause.
81744**
81745**   (8)  The subquery does not use LIMIT or the outer query is not a join.
81746**
81747**   (9)  The subquery does not use LIMIT or the outer query does not use
81748**        aggregates.
81749**
81750**  (10)  The subquery does not use aggregates or the outer query does not
81751**        use LIMIT.
81752**
81753**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
81754**
81755**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
81756**        a separate restriction deriving from ticket #350.
81757**
81758**  (13)  The subquery and outer query do not both use LIMIT
81759**
81760**  (14)  The subquery does not use OFFSET
81761**
81762**  (15)  The outer query is not part of a compound select or the
81763**        subquery does not have both an ORDER BY and a LIMIT clause.
81764**        (See ticket #2339)
81765**
81766**  (16)  The outer query is not an aggregate or the subquery does
81767**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
81768**        until we introduced the group_concat() function.
81769**
81770**  (17)  The sub-query is not a compound select, or it is a UNION ALL
81771**        compound clause made up entirely of non-aggregate queries, and
81772**        the parent query:
81773**
81774**          * is not itself part of a compound select,
81775**          * is not an aggregate or DISTINCT query, and
81776**          * has no other tables or sub-selects in the FROM clause.
81777**
81778**        The parent and sub-query may contain WHERE clauses. Subject to
81779**        rules (11), (13) and (14), they may also contain ORDER BY,
81780**        LIMIT and OFFSET clauses.
81781**
81782**  (18)  If the sub-query is a compound select, then all terms of the
81783**        ORDER by clause of the parent must be simple references to
81784**        columns of the sub-query.
81785**
81786**  (19)  The subquery does not use LIMIT or the outer query does not
81787**        have a WHERE clause.
81788**
81789**  (20)  If the sub-query is a compound select, then it must not use
81790**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
81791**        somewhat by saying that the terms of the ORDER BY clause must
81792**        appear as unmodified result columns in the outer query.  But
81793**        have other optimizations in mind to deal with that case.
81794**
81795** In this routine, the "p" parameter is a pointer to the outer query.
81796** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
81797** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
81798**
81799** If flattening is not attempted, this routine is a no-op and returns 0.
81800** If flattening is attempted this routine returns 1.
81801**
81802** All of the expression analysis must occur on both the outer query and
81803** the subquery before this routine runs.
81804*/
81805static int flattenSubquery(
81806  Parse *pParse,       /* Parsing context */
81807  Select *p,           /* The parent or outer SELECT statement */
81808  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
81809  int isAgg,           /* True if outer SELECT uses aggregate functions */
81810  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
81811){
81812  const char *zSavedAuthContext = pParse->zAuthContext;
81813  Select *pParent;
81814  Select *pSub;       /* The inner query or "subquery" */
81815  Select *pSub1;      /* Pointer to the rightmost select in sub-query */
81816  SrcList *pSrc;      /* The FROM clause of the outer query */
81817  SrcList *pSubSrc;   /* The FROM clause of the subquery */
81818  ExprList *pList;    /* The result set of the outer query */
81819  int iParent;        /* VDBE cursor number of the pSub result set temp table */
81820  int i;              /* Loop counter */
81821  Expr *pWhere;                    /* The WHERE clause */
81822  struct SrcList_item *pSubitem;   /* The subquery */
81823  sqlite3 *db = pParse->db;
81824
81825  /* Check to see if flattening is permitted.  Return 0 if not.
81826  */
81827  assert( p!=0 );
81828  assert( p->pPrior==0 );  /* Unable to flatten compound queries */
81829  if( db->flags & SQLITE_QueryFlattener ) return 0;
81830  pSrc = p->pSrc;
81831  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
81832  pSubitem = &pSrc->a[iFrom];
81833  iParent = pSubitem->iCursor;
81834  pSub = pSubitem->pSelect;
81835  assert( pSub!=0 );
81836  if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
81837  if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
81838  pSubSrc = pSub->pSrc;
81839  assert( pSubSrc );
81840  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
81841  ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
81842  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
81843  ** became arbitrary expressions, we were forced to add restrictions (13)
81844  ** and (14). */
81845  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
81846  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
81847  if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
81848    return 0;                                            /* Restriction (15) */
81849  }
81850  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
81851  if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit)
81852         && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
81853     return 0;
81854  }
81855  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
81856     return 0;         /* Restriction (6)  */
81857  }
81858  if( p->pOrderBy && pSub->pOrderBy ){
81859     return 0;                                           /* Restriction (11) */
81860  }
81861  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
81862  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
81863
81864  /* OBSOLETE COMMENT 1:
81865  ** Restriction 3:  If the subquery is a join, make sure the subquery is
81866  ** not used as the right operand of an outer join.  Examples of why this
81867  ** is not allowed:
81868  **
81869  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
81870  **
81871  ** If we flatten the above, we would get
81872  **
81873  **         (t1 LEFT OUTER JOIN t2) JOIN t3
81874  **
81875  ** which is not at all the same thing.
81876  **
81877  ** OBSOLETE COMMENT 2:
81878  ** Restriction 12:  If the subquery is the right operand of a left outer
81879  ** join, make sure the subquery has no WHERE clause.
81880  ** An examples of why this is not allowed:
81881  **
81882  **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
81883  **
81884  ** If we flatten the above, we would get
81885  **
81886  **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
81887  **
81888  ** But the t2.x>0 test will always fail on a NULL row of t2, which
81889  ** effectively converts the OUTER JOIN into an INNER JOIN.
81890  **
81891  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
81892  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
81893  ** is fraught with danger.  Best to avoid the whole thing.  If the
81894  ** subquery is the right term of a LEFT JOIN, then do not flatten.
81895  */
81896  if( (pSubitem->jointype & JT_OUTER)!=0 ){
81897    return 0;
81898  }
81899
81900  /* Restriction 17: If the sub-query is a compound SELECT, then it must
81901  ** use only the UNION ALL operator. And none of the simple select queries
81902  ** that make up the compound SELECT are allowed to be aggregate or distinct
81903  ** queries.
81904  */
81905  if( pSub->pPrior ){
81906    if( pSub->pOrderBy ){
81907      return 0;  /* Restriction 20 */
81908    }
81909    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
81910      return 0;
81911    }
81912    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
81913      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
81914      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
81915      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
81916       || (pSub1->pPrior && pSub1->op!=TK_ALL)
81917       || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
81918      ){
81919        return 0;
81920      }
81921    }
81922
81923    /* Restriction 18. */
81924    if( p->pOrderBy ){
81925      int ii;
81926      for(ii=0; ii<p->pOrderBy->nExpr; ii++){
81927        if( p->pOrderBy->a[ii].iCol==0 ) return 0;
81928      }
81929    }
81930  }
81931
81932  /***** If we reach this point, flattening is permitted. *****/
81933
81934  /* Authorize the subquery */
81935  pParse->zAuthContext = pSubitem->zName;
81936  sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
81937  pParse->zAuthContext = zSavedAuthContext;
81938
81939  /* If the sub-query is a compound SELECT statement, then (by restrictions
81940  ** 17 and 18 above) it must be a UNION ALL and the parent query must
81941  ** be of the form:
81942  **
81943  **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
81944  **
81945  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
81946  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
81947  ** OFFSET clauses and joins them to the left-hand-side of the original
81948  ** using UNION ALL operators. In this case N is the number of simple
81949  ** select statements in the compound sub-query.
81950  **
81951  ** Example:
81952  **
81953  **     SELECT a+1 FROM (
81954  **        SELECT x FROM tab
81955  **        UNION ALL
81956  **        SELECT y FROM tab
81957  **        UNION ALL
81958  **        SELECT abs(z*2) FROM tab2
81959  **     ) WHERE a!=5 ORDER BY 1
81960  **
81961  ** Transformed into:
81962  **
81963  **     SELECT x+1 FROM tab WHERE x+1!=5
81964  **     UNION ALL
81965  **     SELECT y+1 FROM tab WHERE y+1!=5
81966  **     UNION ALL
81967  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
81968  **     ORDER BY 1
81969  **
81970  ** We call this the "compound-subquery flattening".
81971  */
81972  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
81973    Select *pNew;
81974    ExprList *pOrderBy = p->pOrderBy;
81975    Expr *pLimit = p->pLimit;
81976    Select *pPrior = p->pPrior;
81977    p->pOrderBy = 0;
81978    p->pSrc = 0;
81979    p->pPrior = 0;
81980    p->pLimit = 0;
81981    pNew = sqlite3SelectDup(db, p, 0);
81982    p->pLimit = pLimit;
81983    p->pOrderBy = pOrderBy;
81984    p->pSrc = pSrc;
81985    p->op = TK_ALL;
81986    p->pRightmost = 0;
81987    if( pNew==0 ){
81988      pNew = pPrior;
81989    }else{
81990      pNew->pPrior = pPrior;
81991      pNew->pRightmost = 0;
81992    }
81993    p->pPrior = pNew;
81994    if( db->mallocFailed ) return 1;
81995  }
81996
81997  /* Begin flattening the iFrom-th entry of the FROM clause
81998  ** in the outer query.
81999  */
82000  pSub = pSub1 = pSubitem->pSelect;
82001
82002  /* Delete the transient table structure associated with the
82003  ** subquery
82004  */
82005  sqlite3DbFree(db, pSubitem->zDatabase);
82006  sqlite3DbFree(db, pSubitem->zName);
82007  sqlite3DbFree(db, pSubitem->zAlias);
82008  pSubitem->zDatabase = 0;
82009  pSubitem->zName = 0;
82010  pSubitem->zAlias = 0;
82011  pSubitem->pSelect = 0;
82012
82013  /* Defer deleting the Table object associated with the
82014  ** subquery until code generation is
82015  ** complete, since there may still exist Expr.pTab entries that
82016  ** refer to the subquery even after flattening.  Ticket #3346.
82017  **
82018  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
82019  */
82020  if( ALWAYS(pSubitem->pTab!=0) ){
82021    Table *pTabToDel = pSubitem->pTab;
82022    if( pTabToDel->nRef==1 ){
82023      Parse *pToplevel = sqlite3ParseToplevel(pParse);
82024      pTabToDel->pNextZombie = pToplevel->pZombieTab;
82025      pToplevel->pZombieTab = pTabToDel;
82026    }else{
82027      pTabToDel->nRef--;
82028    }
82029    pSubitem->pTab = 0;
82030  }
82031
82032  /* The following loop runs once for each term in a compound-subquery
82033  ** flattening (as described above).  If we are doing a different kind
82034  ** of flattening - a flattening other than a compound-subquery flattening -
82035  ** then this loop only runs once.
82036  **
82037  ** This loop moves all of the FROM elements of the subquery into the
82038  ** the FROM clause of the outer query.  Before doing this, remember
82039  ** the cursor number for the original outer query FROM element in
82040  ** iParent.  The iParent cursor will never be used.  Subsequent code
82041  ** will scan expressions looking for iParent references and replace
82042  ** those references with expressions that resolve to the subquery FROM
82043  ** elements we are now copying in.
82044  */
82045  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
82046    int nSubSrc;
82047    u8 jointype = 0;
82048    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
82049    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
82050    pSrc = pParent->pSrc;     /* FROM clause of the outer query */
82051
82052    if( pSrc ){
82053      assert( pParent==p );  /* First time through the loop */
82054      jointype = pSubitem->jointype;
82055    }else{
82056      assert( pParent!=p );  /* 2nd and subsequent times through the loop */
82057      pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
82058      if( pSrc==0 ){
82059        assert( db->mallocFailed );
82060        break;
82061      }
82062    }
82063
82064    /* The subquery uses a single slot of the FROM clause of the outer
82065    ** query.  If the subquery has more than one element in its FROM clause,
82066    ** then expand the outer query to make space for it to hold all elements
82067    ** of the subquery.
82068    **
82069    ** Example:
82070    **
82071    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
82072    **
82073    ** The outer query has 3 slots in its FROM clause.  One slot of the
82074    ** outer query (the middle slot) is used by the subquery.  The next
82075    ** block of code will expand the out query to 4 slots.  The middle
82076    ** slot is expanded to two slots in order to make space for the
82077    ** two elements in the FROM clause of the subquery.
82078    */
82079    if( nSubSrc>1 ){
82080      pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
82081      if( db->mallocFailed ){
82082        break;
82083      }
82084    }
82085
82086    /* Transfer the FROM clause terms from the subquery into the
82087    ** outer query.
82088    */
82089    for(i=0; i<nSubSrc; i++){
82090      sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
82091      pSrc->a[i+iFrom] = pSubSrc->a[i];
82092      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
82093    }
82094    pSrc->a[iFrom].jointype = jointype;
82095
82096    /* Now begin substituting subquery result set expressions for
82097    ** references to the iParent in the outer query.
82098    **
82099    ** Example:
82100    **
82101    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
82102    **   \                     \_____________ subquery __________/          /
82103    **    \_____________________ outer query ______________________________/
82104    **
82105    ** We look at every expression in the outer query and every place we see
82106    ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
82107    */
82108    pList = pParent->pEList;
82109    for(i=0; i<pList->nExpr; i++){
82110      if( pList->a[i].zName==0 ){
82111        const char *zSpan = pList->a[i].zSpan;
82112        if( ALWAYS(zSpan) ){
82113          pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
82114        }
82115      }
82116    }
82117    substExprList(db, pParent->pEList, iParent, pSub->pEList);
82118    if( isAgg ){
82119      substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
82120      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
82121    }
82122    if( pSub->pOrderBy ){
82123      assert( pParent->pOrderBy==0 );
82124      pParent->pOrderBy = pSub->pOrderBy;
82125      pSub->pOrderBy = 0;
82126    }else if( pParent->pOrderBy ){
82127      substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
82128    }
82129    if( pSub->pWhere ){
82130      pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
82131    }else{
82132      pWhere = 0;
82133    }
82134    if( subqueryIsAgg ){
82135      assert( pParent->pHaving==0 );
82136      pParent->pHaving = pParent->pWhere;
82137      pParent->pWhere = pWhere;
82138      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
82139      pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
82140                                  sqlite3ExprDup(db, pSub->pHaving, 0));
82141      assert( pParent->pGroupBy==0 );
82142      pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
82143    }else{
82144      pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
82145      pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
82146    }
82147
82148    /* The flattened query is distinct if either the inner or the
82149    ** outer query is distinct.
82150    */
82151    pParent->selFlags |= pSub->selFlags & SF_Distinct;
82152
82153    /*
82154    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
82155    **
82156    ** One is tempted to try to add a and b to combine the limits.  But this
82157    ** does not work if either limit is negative.
82158    */
82159    if( pSub->pLimit ){
82160      pParent->pLimit = pSub->pLimit;
82161      pSub->pLimit = 0;
82162    }
82163  }
82164
82165  /* Finially, delete what is left of the subquery and return
82166  ** success.
82167  */
82168  sqlite3SelectDelete(db, pSub1);
82169
82170  return 1;
82171}
82172#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
82173
82174/*
82175** Analyze the SELECT statement passed as an argument to see if it
82176** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
82177** it is, or 0 otherwise. At present, a query is considered to be
82178** a min()/max() query if:
82179**
82180**   1. There is a single object in the FROM clause.
82181**
82182**   2. There is a single expression in the result set, and it is
82183**      either min(x) or max(x), where x is a column reference.
82184*/
82185static u8 minMaxQuery(Select *p){
82186  Expr *pExpr;
82187  ExprList *pEList = p->pEList;
82188
82189  if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
82190  pExpr = pEList->a[0].pExpr;
82191  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
82192  if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
82193  pEList = pExpr->x.pList;
82194  if( pEList==0 || pEList->nExpr!=1 ) return 0;
82195  if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
82196  assert( !ExprHasProperty(pExpr, EP_IntValue) );
82197  if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
82198    return WHERE_ORDERBY_MIN;
82199  }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
82200    return WHERE_ORDERBY_MAX;
82201  }
82202  return WHERE_ORDERBY_NORMAL;
82203}
82204
82205/*
82206** The select statement passed as the first argument is an aggregate query.
82207** The second argment is the associated aggregate-info object. This
82208** function tests if the SELECT is of the form:
82209**
82210**   SELECT count(*) FROM <tbl>
82211**
82212** where table is a database table, not a sub-select or view. If the query
82213** does match this pattern, then a pointer to the Table object representing
82214** <tbl> is returned. Otherwise, 0 is returned.
82215*/
82216static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
82217  Table *pTab;
82218  Expr *pExpr;
82219
82220  assert( !p->pGroupBy );
82221
82222  if( p->pWhere || p->pEList->nExpr!=1
82223   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
82224  ){
82225    return 0;
82226  }
82227  pTab = p->pSrc->a[0].pTab;
82228  pExpr = p->pEList->a[0].pExpr;
82229  assert( pTab && !pTab->pSelect && pExpr );
82230
82231  if( IsVirtual(pTab) ) return 0;
82232  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
82233  if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
82234  if( pExpr->flags&EP_Distinct ) return 0;
82235
82236  return pTab;
82237}
82238
82239/*
82240** If the source-list item passed as an argument was augmented with an
82241** INDEXED BY clause, then try to locate the specified index. If there
82242** was such a clause and the named index cannot be found, return
82243** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
82244** pFrom->pIndex and return SQLITE_OK.
82245*/
82246SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
82247  if( pFrom->pTab && pFrom->zIndex ){
82248    Table *pTab = pFrom->pTab;
82249    char *zIndex = pFrom->zIndex;
82250    Index *pIdx;
82251    for(pIdx=pTab->pIndex;
82252        pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
82253        pIdx=pIdx->pNext
82254    );
82255    if( !pIdx ){
82256      sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
82257      return SQLITE_ERROR;
82258    }
82259    pFrom->pIndex = pIdx;
82260  }
82261  return SQLITE_OK;
82262}
82263
82264/*
82265** This routine is a Walker callback for "expanding" a SELECT statement.
82266** "Expanding" means to do the following:
82267**
82268**    (1)  Make sure VDBE cursor numbers have been assigned to every
82269**         element of the FROM clause.
82270**
82271**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
82272**         defines FROM clause.  When views appear in the FROM clause,
82273**         fill pTabList->a[].pSelect with a copy of the SELECT statement
82274**         that implements the view.  A copy is made of the view's SELECT
82275**         statement so that we can freely modify or delete that statement
82276**         without worrying about messing up the presistent representation
82277**         of the view.
82278**
82279**    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
82280**         on joins and the ON and USING clause of joins.
82281**
82282**    (4)  Scan the list of columns in the result set (pEList) looking
82283**         for instances of the "*" operator or the TABLE.* operator.
82284**         If found, expand each "*" to be every column in every table
82285**         and TABLE.* to be every column in TABLE.
82286**
82287*/
82288static int selectExpander(Walker *pWalker, Select *p){
82289  Parse *pParse = pWalker->pParse;
82290  int i, j, k;
82291  SrcList *pTabList;
82292  ExprList *pEList;
82293  struct SrcList_item *pFrom;
82294  sqlite3 *db = pParse->db;
82295
82296  if( db->mallocFailed  ){
82297    return WRC_Abort;
82298  }
82299  if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
82300    return WRC_Prune;
82301  }
82302  p->selFlags |= SF_Expanded;
82303  pTabList = p->pSrc;
82304  pEList = p->pEList;
82305
82306  /* Make sure cursor numbers have been assigned to all entries in
82307  ** the FROM clause of the SELECT statement.
82308  */
82309  sqlite3SrcListAssignCursors(pParse, pTabList);
82310
82311  /* Look up every table named in the FROM clause of the select.  If
82312  ** an entry of the FROM clause is a subquery instead of a table or view,
82313  ** then create a transient table structure to describe the subquery.
82314  */
82315  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
82316    Table *pTab;
82317    if( pFrom->pTab!=0 ){
82318      /* This statement has already been prepared.  There is no need
82319      ** to go further. */
82320      assert( i==0 );
82321      return WRC_Prune;
82322    }
82323    if( pFrom->zName==0 ){
82324#ifndef SQLITE_OMIT_SUBQUERY
82325      Select *pSel = pFrom->pSelect;
82326      /* A sub-query in the FROM clause of a SELECT */
82327      assert( pSel!=0 );
82328      assert( pFrom->pTab==0 );
82329      sqlite3WalkSelect(pWalker, pSel);
82330      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
82331      if( pTab==0 ) return WRC_Abort;
82332      pTab->dbMem = db->lookaside.bEnabled ? db : 0;
82333      pTab->nRef = 1;
82334      pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
82335      while( pSel->pPrior ){ pSel = pSel->pPrior; }
82336      selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
82337      pTab->iPKey = -1;
82338      pTab->tabFlags |= TF_Ephemeral;
82339#endif
82340    }else{
82341      /* An ordinary table or view name in the FROM clause */
82342      assert( pFrom->pTab==0 );
82343      pFrom->pTab = pTab =
82344        sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
82345      if( pTab==0 ) return WRC_Abort;
82346      pTab->nRef++;
82347#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
82348      if( pTab->pSelect || IsVirtual(pTab) ){
82349        /* We reach here if the named table is a really a view */
82350        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
82351        assert( pFrom->pSelect==0 );
82352        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
82353        sqlite3WalkSelect(pWalker, pFrom->pSelect);
82354      }
82355#endif
82356    }
82357
82358    /* Locate the index named by the INDEXED BY clause, if any. */
82359    if( sqlite3IndexedByLookup(pParse, pFrom) ){
82360      return WRC_Abort;
82361    }
82362  }
82363
82364  /* Process NATURAL keywords, and ON and USING clauses of joins.
82365  */
82366  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
82367    return WRC_Abort;
82368  }
82369
82370  /* For every "*" that occurs in the column list, insert the names of
82371  ** all columns in all tables.  And for every TABLE.* insert the names
82372  ** of all columns in TABLE.  The parser inserted a special expression
82373  ** with the TK_ALL operator for each "*" that it found in the column list.
82374  ** The following code just has to locate the TK_ALL expressions and expand
82375  ** each one to the list of all columns in all tables.
82376  **
82377  ** The first loop just checks to see if there are any "*" operators
82378  ** that need expanding.
82379  */
82380  for(k=0; k<pEList->nExpr; k++){
82381    Expr *pE = pEList->a[k].pExpr;
82382    if( pE->op==TK_ALL ) break;
82383    assert( pE->op!=TK_DOT || pE->pRight!=0 );
82384    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
82385    if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
82386  }
82387  if( k<pEList->nExpr ){
82388    /*
82389    ** If we get here it means the result set contains one or more "*"
82390    ** operators that need to be expanded.  Loop through each expression
82391    ** in the result set and expand them one by one.
82392    */
82393    struct ExprList_item *a = pEList->a;
82394    ExprList *pNew = 0;
82395    int flags = pParse->db->flags;
82396    int longNames = (flags & SQLITE_FullColNames)!=0
82397                      && (flags & SQLITE_ShortColNames)==0;
82398
82399    for(k=0; k<pEList->nExpr; k++){
82400      Expr *pE = a[k].pExpr;
82401      assert( pE->op!=TK_DOT || pE->pRight!=0 );
82402      if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
82403        /* This particular expression does not need to be expanded.
82404        */
82405        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
82406        if( pNew ){
82407          pNew->a[pNew->nExpr-1].zName = a[k].zName;
82408          pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
82409          a[k].zName = 0;
82410          a[k].zSpan = 0;
82411        }
82412        a[k].pExpr = 0;
82413      }else{
82414        /* This expression is a "*" or a "TABLE.*" and needs to be
82415        ** expanded. */
82416        int tableSeen = 0;      /* Set to 1 when TABLE matches */
82417        char *zTName;            /* text of name of TABLE */
82418        if( pE->op==TK_DOT ){
82419          assert( pE->pLeft!=0 );
82420          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
82421          zTName = pE->pLeft->u.zToken;
82422        }else{
82423          zTName = 0;
82424        }
82425        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
82426          Table *pTab = pFrom->pTab;
82427          char *zTabName = pFrom->zAlias;
82428          if( zTabName==0 ){
82429            zTabName = pTab->zName;
82430          }
82431          if( db->mallocFailed ) break;
82432          if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
82433            continue;
82434          }
82435          tableSeen = 1;
82436          for(j=0; j<pTab->nCol; j++){
82437            Expr *pExpr, *pRight;
82438            char *zName = pTab->aCol[j].zName;
82439            char *zColname;  /* The computed column name */
82440            char *zToFree;   /* Malloced string that needs to be freed */
82441            Token sColname;  /* Computed column name as a token */
82442
82443            /* If a column is marked as 'hidden' (currently only possible
82444            ** for virtual tables), do not include it in the expanded
82445            ** result-set list.
82446            */
82447            if( IsHiddenColumn(&pTab->aCol[j]) ){
82448              assert(IsVirtual(pTab));
82449              continue;
82450            }
82451
82452            if( i>0 && zTName==0 ){
82453              if( (pFrom->jointype & JT_NATURAL)!=0
82454                && tableAndColumnIndex(pTabList, i, zName, 0, 0)
82455              ){
82456                /* In a NATURAL join, omit the join columns from the
82457                ** table to the right of the join */
82458                continue;
82459              }
82460              if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
82461                /* In a join with a USING clause, omit columns in the
82462                ** using clause from the table on the right. */
82463                continue;
82464              }
82465            }
82466            pRight = sqlite3Expr(db, TK_ID, zName);
82467            zColname = zName;
82468            zToFree = 0;
82469            if( longNames || pTabList->nSrc>1 ){
82470              Expr *pLeft;
82471              pLeft = sqlite3Expr(db, TK_ID, zTabName);
82472              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
82473              if( longNames ){
82474                zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
82475                zToFree = zColname;
82476              }
82477            }else{
82478              pExpr = pRight;
82479            }
82480            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
82481            sColname.z = zColname;
82482            sColname.n = sqlite3Strlen30(zColname);
82483            sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
82484            sqlite3DbFree(db, zToFree);
82485          }
82486        }
82487        if( !tableSeen ){
82488          if( zTName ){
82489            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
82490          }else{
82491            sqlite3ErrorMsg(pParse, "no tables specified");
82492          }
82493        }
82494      }
82495    }
82496    sqlite3ExprListDelete(db, pEList);
82497    p->pEList = pNew;
82498  }
82499#if SQLITE_MAX_COLUMN
82500  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
82501    sqlite3ErrorMsg(pParse, "too many columns in result set");
82502  }
82503#endif
82504  return WRC_Continue;
82505}
82506
82507/*
82508** No-op routine for the parse-tree walker.
82509**
82510** When this routine is the Walker.xExprCallback then expression trees
82511** are walked without any actions being taken at each node.  Presumably,
82512** when this routine is used for Walker.xExprCallback then
82513** Walker.xSelectCallback is set to do something useful for every
82514** subquery in the parser tree.
82515*/
82516static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
82517  UNUSED_PARAMETER2(NotUsed, NotUsed2);
82518  return WRC_Continue;
82519}
82520
82521/*
82522** This routine "expands" a SELECT statement and all of its subqueries.
82523** For additional information on what it means to "expand" a SELECT
82524** statement, see the comment on the selectExpand worker callback above.
82525**
82526** Expanding a SELECT statement is the first step in processing a
82527** SELECT statement.  The SELECT statement must be expanded before
82528** name resolution is performed.
82529**
82530** If anything goes wrong, an error message is written into pParse.
82531** The calling function can detect the problem by looking at pParse->nErr
82532** and/or pParse->db->mallocFailed.
82533*/
82534static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
82535  Walker w;
82536  w.xSelectCallback = selectExpander;
82537  w.xExprCallback = exprWalkNoop;
82538  w.pParse = pParse;
82539  sqlite3WalkSelect(&w, pSelect);
82540}
82541
82542
82543#ifndef SQLITE_OMIT_SUBQUERY
82544/*
82545** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
82546** interface.
82547**
82548** For each FROM-clause subquery, add Column.zType and Column.zColl
82549** information to the Table structure that represents the result set
82550** of that subquery.
82551**
82552** The Table structure that represents the result set was constructed
82553** by selectExpander() but the type and collation information was omitted
82554** at that point because identifiers had not yet been resolved.  This
82555** routine is called after identifier resolution.
82556*/
82557static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
82558  Parse *pParse;
82559  int i;
82560  SrcList *pTabList;
82561  struct SrcList_item *pFrom;
82562
82563  assert( p->selFlags & SF_Resolved );
82564  assert( (p->selFlags & SF_HasTypeInfo)==0 );
82565  p->selFlags |= SF_HasTypeInfo;
82566  pParse = pWalker->pParse;
82567  pTabList = p->pSrc;
82568  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
82569    Table *pTab = pFrom->pTab;
82570    if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
82571      /* A sub-query in the FROM clause of a SELECT */
82572      Select *pSel = pFrom->pSelect;
82573      assert( pSel );
82574      while( pSel->pPrior ) pSel = pSel->pPrior;
82575      selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
82576    }
82577  }
82578  return WRC_Continue;
82579}
82580#endif
82581
82582
82583/*
82584** This routine adds datatype and collating sequence information to
82585** the Table structures of all FROM-clause subqueries in a
82586** SELECT statement.
82587**
82588** Use this routine after name resolution.
82589*/
82590static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
82591#ifndef SQLITE_OMIT_SUBQUERY
82592  Walker w;
82593  w.xSelectCallback = selectAddSubqueryTypeInfo;
82594  w.xExprCallback = exprWalkNoop;
82595  w.pParse = pParse;
82596  sqlite3WalkSelect(&w, pSelect);
82597#endif
82598}
82599
82600
82601/*
82602** This routine sets of a SELECT statement for processing.  The
82603** following is accomplished:
82604**
82605**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
82606**     *  Ephemeral Table objects are created for all FROM-clause subqueries.
82607**     *  ON and USING clauses are shifted into WHERE statements
82608**     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
82609**     *  Identifiers in expression are matched to tables.
82610**
82611** This routine acts recursively on all subqueries within the SELECT.
82612*/
82613SQLITE_PRIVATE void sqlite3SelectPrep(
82614  Parse *pParse,         /* The parser context */
82615  Select *p,             /* The SELECT statement being coded. */
82616  NameContext *pOuterNC  /* Name context for container */
82617){
82618  sqlite3 *db;
82619  if( NEVER(p==0) ) return;
82620  db = pParse->db;
82621  if( p->selFlags & SF_HasTypeInfo ) return;
82622  sqlite3SelectExpand(pParse, p);
82623  if( pParse->nErr || db->mallocFailed ) return;
82624  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
82625  if( pParse->nErr || db->mallocFailed ) return;
82626  sqlite3SelectAddTypeInfo(pParse, p);
82627}
82628
82629/*
82630** Reset the aggregate accumulator.
82631**
82632** The aggregate accumulator is a set of memory cells that hold
82633** intermediate results while calculating an aggregate.  This
82634** routine simply stores NULLs in all of those memory cells.
82635*/
82636static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
82637  Vdbe *v = pParse->pVdbe;
82638  int i;
82639  struct AggInfo_func *pFunc;
82640  if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
82641    return;
82642  }
82643  for(i=0; i<pAggInfo->nColumn; i++){
82644    sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
82645  }
82646  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
82647    sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
82648    if( pFunc->iDistinct>=0 ){
82649      Expr *pE = pFunc->pExpr;
82650      assert( !ExprHasProperty(pE, EP_xIsSelect) );
82651      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
82652        sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
82653           "argument");
82654        pFunc->iDistinct = -1;
82655      }else{
82656        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
82657        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
82658                          (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
82659      }
82660    }
82661  }
82662}
82663
82664/*
82665** Invoke the OP_AggFinalize opcode for every aggregate function
82666** in the AggInfo structure.
82667*/
82668static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
82669  Vdbe *v = pParse->pVdbe;
82670  int i;
82671  struct AggInfo_func *pF;
82672  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
82673    ExprList *pList = pF->pExpr->x.pList;
82674    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
82675    sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
82676                      (void*)pF->pFunc, P4_FUNCDEF);
82677  }
82678}
82679
82680/*
82681** Update the accumulator memory cells for an aggregate based on
82682** the current cursor position.
82683*/
82684static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
82685  Vdbe *v = pParse->pVdbe;
82686  int i;
82687  struct AggInfo_func *pF;
82688  struct AggInfo_col *pC;
82689
82690  pAggInfo->directMode = 1;
82691  sqlite3ExprCacheClear(pParse);
82692  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
82693    int nArg;
82694    int addrNext = 0;
82695    int regAgg;
82696    ExprList *pList = pF->pExpr->x.pList;
82697    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
82698    if( pList ){
82699      nArg = pList->nExpr;
82700      regAgg = sqlite3GetTempRange(pParse, nArg);
82701      sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
82702    }else{
82703      nArg = 0;
82704      regAgg = 0;
82705    }
82706    if( pF->iDistinct>=0 ){
82707      addrNext = sqlite3VdbeMakeLabel(v);
82708      assert( nArg==1 );
82709      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
82710    }
82711    if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
82712      CollSeq *pColl = 0;
82713      struct ExprList_item *pItem;
82714      int j;
82715      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
82716      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
82717        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
82718      }
82719      if( !pColl ){
82720        pColl = pParse->db->pDfltColl;
82721      }
82722      sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
82723    }
82724    sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
82725                      (void*)pF->pFunc, P4_FUNCDEF);
82726    sqlite3VdbeChangeP5(v, (u8)nArg);
82727    sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
82728    sqlite3ReleaseTempRange(pParse, regAgg, nArg);
82729    if( addrNext ){
82730      sqlite3VdbeResolveLabel(v, addrNext);
82731      sqlite3ExprCacheClear(pParse);
82732    }
82733  }
82734  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
82735    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
82736  }
82737  pAggInfo->directMode = 0;
82738  sqlite3ExprCacheClear(pParse);
82739}
82740
82741/*
82742** Generate code for the SELECT statement given in the p argument.
82743**
82744** The results are distributed in various ways depending on the
82745** contents of the SelectDest structure pointed to by argument pDest
82746** as follows:
82747**
82748**     pDest->eDest    Result
82749**     ------------    -------------------------------------------
82750**     SRT_Output      Generate a row of output (using the OP_ResultRow
82751**                     opcode) for each row in the result set.
82752**
82753**     SRT_Mem         Only valid if the result is a single column.
82754**                     Store the first column of the first result row
82755**                     in register pDest->iParm then abandon the rest
82756**                     of the query.  This destination implies "LIMIT 1".
82757**
82758**     SRT_Set         The result must be a single column.  Store each
82759**                     row of result as the key in table pDest->iParm.
82760**                     Apply the affinity pDest->affinity before storing
82761**                     results.  Used to implement "IN (SELECT ...)".
82762**
82763**     SRT_Union       Store results as a key in a temporary table pDest->iParm.
82764**
82765**     SRT_Except      Remove results from the temporary table pDest->iParm.
82766**
82767**     SRT_Table       Store results in temporary table pDest->iParm.
82768**                     This is like SRT_EphemTab except that the table
82769**                     is assumed to already be open.
82770**
82771**     SRT_EphemTab    Create an temporary table pDest->iParm and store
82772**                     the result there. The cursor is left open after
82773**                     returning.  This is like SRT_Table except that
82774**                     this destination uses OP_OpenEphemeral to create
82775**                     the table first.
82776**
82777**     SRT_Coroutine   Generate a co-routine that returns a new row of
82778**                     results each time it is invoked.  The entry point
82779**                     of the co-routine is stored in register pDest->iParm.
82780**
82781**     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
82782**                     set is not empty.
82783**
82784**     SRT_Discard     Throw the results away.  This is used by SELECT
82785**                     statements within triggers whose only purpose is
82786**                     the side-effects of functions.
82787**
82788** This routine returns the number of errors.  If any errors are
82789** encountered, then an appropriate error message is left in
82790** pParse->zErrMsg.
82791**
82792** This routine does NOT free the Select structure passed in.  The
82793** calling function needs to do that.
82794*/
82795SQLITE_PRIVATE int sqlite3Select(
82796  Parse *pParse,         /* The parser context */
82797  Select *p,             /* The SELECT statement being coded. */
82798  SelectDest *pDest      /* What to do with the query results */
82799){
82800  int i, j;              /* Loop counters */
82801  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
82802  Vdbe *v;               /* The virtual machine under construction */
82803  int isAgg;             /* True for select lists like "count(*)" */
82804  ExprList *pEList;      /* List of columns to extract. */
82805  SrcList *pTabList;     /* List of tables to select from */
82806  Expr *pWhere;          /* The WHERE clause.  May be NULL */
82807  ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
82808  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
82809  Expr *pHaving;         /* The HAVING clause.  May be NULL */
82810  int isDistinct;        /* True if the DISTINCT keyword is present */
82811  int distinct;          /* Table to use for the distinct set */
82812  int rc = 1;            /* Value to return from this function */
82813  int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
82814  AggInfo sAggInfo;      /* Information used by aggregate queries */
82815  int iEnd;              /* Address of the end of the query */
82816  sqlite3 *db;           /* The database connection */
82817
82818  db = pParse->db;
82819  if( p==0 || db->mallocFailed || pParse->nErr ){
82820    return 1;
82821  }
82822  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
82823  memset(&sAggInfo, 0, sizeof(sAggInfo));
82824
82825  if( IgnorableOrderby(pDest) ){
82826    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
82827           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
82828    /* If ORDER BY makes no difference in the output then neither does
82829    ** DISTINCT so it can be removed too. */
82830    sqlite3ExprListDelete(db, p->pOrderBy);
82831    p->pOrderBy = 0;
82832    p->selFlags &= ~SF_Distinct;
82833  }
82834  sqlite3SelectPrep(pParse, p, 0);
82835  pOrderBy = p->pOrderBy;
82836  pTabList = p->pSrc;
82837  pEList = p->pEList;
82838  if( pParse->nErr || db->mallocFailed ){
82839    goto select_end;
82840  }
82841  isAgg = (p->selFlags & SF_Aggregate)!=0;
82842  assert( pEList!=0 );
82843
82844  /* Begin generating code.
82845  */
82846  v = sqlite3GetVdbe(pParse);
82847  if( v==0 ) goto select_end;
82848
82849  /* Generate code for all sub-queries in the FROM clause
82850  */
82851#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
82852  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
82853    struct SrcList_item *pItem = &pTabList->a[i];
82854    SelectDest dest;
82855    Select *pSub = pItem->pSelect;
82856    int isAggSub;
82857
82858    if( pSub==0 || pItem->isPopulated ) continue;
82859
82860    /* Increment Parse.nHeight by the height of the largest expression
82861    ** tree refered to by this, the parent select. The child select
82862    ** may contain expression trees of at most
82863    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
82864    ** more conservative than necessary, but much easier than enforcing
82865    ** an exact limit.
82866    */
82867    pParse->nHeight += sqlite3SelectExprHeight(p);
82868
82869    /* Check to see if the subquery can be absorbed into the parent. */
82870    isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
82871    if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
82872      if( isAggSub ){
82873        isAgg = 1;
82874        p->selFlags |= SF_Aggregate;
82875      }
82876      i = -1;
82877    }else{
82878      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
82879      assert( pItem->isPopulated==0 );
82880      sqlite3Select(pParse, pSub, &dest);
82881      pItem->isPopulated = 1;
82882    }
82883    if( /*pParse->nErr ||*/ db->mallocFailed ){
82884      goto select_end;
82885    }
82886    pParse->nHeight -= sqlite3SelectExprHeight(p);
82887    pTabList = p->pSrc;
82888    if( !IgnorableOrderby(pDest) ){
82889      pOrderBy = p->pOrderBy;
82890    }
82891  }
82892  pEList = p->pEList;
82893#endif
82894  pWhere = p->pWhere;
82895  pGroupBy = p->pGroupBy;
82896  pHaving = p->pHaving;
82897  isDistinct = (p->selFlags & SF_Distinct)!=0;
82898
82899#ifndef SQLITE_OMIT_COMPOUND_SELECT
82900  /* If there is are a sequence of queries, do the earlier ones first.
82901  */
82902  if( p->pPrior ){
82903    if( p->pRightmost==0 ){
82904      Select *pLoop, *pRight = 0;
82905      int cnt = 0;
82906      int mxSelect;
82907      for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
82908        pLoop->pRightmost = p;
82909        pLoop->pNext = pRight;
82910        pRight = pLoop;
82911      }
82912      mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
82913      if( mxSelect && cnt>mxSelect ){
82914        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
82915        return 1;
82916      }
82917    }
82918    return multiSelect(pParse, p, pDest);
82919  }
82920#endif
82921
82922  /* If writing to memory or generating a set
82923  ** only a single column may be output.
82924  */
82925#ifndef SQLITE_OMIT_SUBQUERY
82926  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
82927    goto select_end;
82928  }
82929#endif
82930
82931  /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
82932  ** GROUP BY might use an index, DISTINCT never does.
82933  */
82934  assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
82935  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
82936    p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
82937    pGroupBy = p->pGroupBy;
82938    p->selFlags &= ~SF_Distinct;
82939    isDistinct = 0;
82940  }
82941
82942  /* If there is an ORDER BY clause, then this sorting
82943  ** index might end up being unused if the data can be
82944  ** extracted in pre-sorted order.  If that is the case, then the
82945  ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
82946  ** we figure out that the sorting index is not needed.  The addrSortIndex
82947  ** variable is used to facilitate that change.
82948  */
82949  if( pOrderBy ){
82950    KeyInfo *pKeyInfo;
82951    pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
82952    pOrderBy->iECursor = pParse->nTab++;
82953    p->addrOpenEphm[2] = addrSortIndex =
82954      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
82955                           pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
82956                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
82957  }else{
82958    addrSortIndex = -1;
82959  }
82960
82961  /* If the output is destined for a temporary table, open that table.
82962  */
82963  if( pDest->eDest==SRT_EphemTab ){
82964    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
82965  }
82966
82967  /* Set the limiter.
82968  */
82969  iEnd = sqlite3VdbeMakeLabel(v);
82970  computeLimitRegisters(pParse, p, iEnd);
82971
82972  /* Open a virtual index to use for the distinct set.
82973  */
82974  if( isDistinct ){
82975    KeyInfo *pKeyInfo;
82976    assert( isAgg || pGroupBy );
82977    distinct = pParse->nTab++;
82978    pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
82979    sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
82980                        (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
82981  }else{
82982    distinct = -1;
82983  }
82984
82985  /* Aggregate and non-aggregate queries are handled differently */
82986  if( !isAgg && pGroupBy==0 ){
82987    /* This case is for non-aggregate queries
82988    ** Begin the database scan
82989    */
82990    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
82991    if( pWInfo==0 ) goto select_end;
82992
82993    /* If sorting index that was created by a prior OP_OpenEphemeral
82994    ** instruction ended up not being needed, then change the OP_OpenEphemeral
82995    ** into an OP_Noop.
82996    */
82997    if( addrSortIndex>=0 && pOrderBy==0 ){
82998      sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
82999      p->addrOpenEphm[2] = -1;
83000    }
83001
83002    /* Use the standard inner loop
83003    */
83004    assert(!isDistinct);
83005    selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
83006                    pWInfo->iContinue, pWInfo->iBreak);
83007
83008    /* End the database scan loop.
83009    */
83010    sqlite3WhereEnd(pWInfo);
83011  }else{
83012    /* This is the processing for aggregate queries */
83013    NameContext sNC;    /* Name context for processing aggregate information */
83014    int iAMem;          /* First Mem address for storing current GROUP BY */
83015    int iBMem;          /* First Mem address for previous GROUP BY */
83016    int iUseFlag;       /* Mem address holding flag indicating that at least
83017                        ** one row of the input to the aggregator has been
83018                        ** processed */
83019    int iAbortFlag;     /* Mem address which causes query abort if positive */
83020    int groupBySort;    /* Rows come from source in GROUP BY order */
83021    int addrEnd;        /* End of processing for this SELECT */
83022
83023    /* Remove any and all aliases between the result set and the
83024    ** GROUP BY clause.
83025    */
83026    if( pGroupBy ){
83027      int k;                        /* Loop counter */
83028      struct ExprList_item *pItem;  /* For looping over expression in a list */
83029
83030      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
83031        pItem->iAlias = 0;
83032      }
83033      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
83034        pItem->iAlias = 0;
83035      }
83036    }
83037
83038
83039    /* Create a label to jump to when we want to abort the query */
83040    addrEnd = sqlite3VdbeMakeLabel(v);
83041
83042    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
83043    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
83044    ** SELECT statement.
83045    */
83046    memset(&sNC, 0, sizeof(sNC));
83047    sNC.pParse = pParse;
83048    sNC.pSrcList = pTabList;
83049    sNC.pAggInfo = &sAggInfo;
83050    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
83051    sAggInfo.pGroupBy = pGroupBy;
83052    sqlite3ExprAnalyzeAggList(&sNC, pEList);
83053    sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
83054    if( pHaving ){
83055      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
83056    }
83057    sAggInfo.nAccumulator = sAggInfo.nColumn;
83058    for(i=0; i<sAggInfo.nFunc; i++){
83059      assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
83060      sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
83061    }
83062    if( db->mallocFailed ) goto select_end;
83063
83064    /* Processing for aggregates with GROUP BY is very different and
83065    ** much more complex than aggregates without a GROUP BY.
83066    */
83067    if( pGroupBy ){
83068      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
83069      int j1;             /* A-vs-B comparision jump */
83070      int addrOutputRow;  /* Start of subroutine that outputs a result row */
83071      int regOutputRow;   /* Return address register for output subroutine */
83072      int addrSetAbort;   /* Set the abort flag and return */
83073      int addrTopOfLoop;  /* Top of the input loop */
83074      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
83075      int addrReset;      /* Subroutine for resetting the accumulator */
83076      int regReset;       /* Return address register for reset subroutine */
83077
83078      /* If there is a GROUP BY clause we might need a sorting index to
83079      ** implement it.  Allocate that sorting index now.  If it turns out
83080      ** that we do not need it after all, the OpenEphemeral instruction
83081      ** will be converted into a Noop.
83082      */
83083      sAggInfo.sortingIdx = pParse->nTab++;
83084      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
83085      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
83086          sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
83087          0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
83088
83089      /* Initialize memory locations used by GROUP BY aggregate processing
83090      */
83091      iUseFlag = ++pParse->nMem;
83092      iAbortFlag = ++pParse->nMem;
83093      regOutputRow = ++pParse->nMem;
83094      addrOutputRow = sqlite3VdbeMakeLabel(v);
83095      regReset = ++pParse->nMem;
83096      addrReset = sqlite3VdbeMakeLabel(v);
83097      iAMem = pParse->nMem + 1;
83098      pParse->nMem += pGroupBy->nExpr;
83099      iBMem = pParse->nMem + 1;
83100      pParse->nMem += pGroupBy->nExpr;
83101      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
83102      VdbeComment((v, "clear abort flag"));
83103      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
83104      VdbeComment((v, "indicate accumulator empty"));
83105
83106      /* Begin a loop that will extract all source rows in GROUP BY order.
83107      ** This might involve two separate loops with an OP_Sort in between, or
83108      ** it might be a single loop that uses an index to extract information
83109      ** in the right order to begin with.
83110      */
83111      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
83112      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
83113      if( pWInfo==0 ) goto select_end;
83114      if( pGroupBy==0 ){
83115        /* The optimizer is able to deliver rows in group by order so
83116        ** we do not have to sort.  The OP_OpenEphemeral table will be
83117        ** cancelled later because we still need to use the pKeyInfo
83118        */
83119        pGroupBy = p->pGroupBy;
83120        groupBySort = 0;
83121      }else{
83122        /* Rows are coming out in undetermined order.  We have to push
83123        ** each row into a sorting index, terminate the first loop,
83124        ** then loop over the sorting index in order to get the output
83125        ** in sorted order
83126        */
83127        int regBase;
83128        int regRecord;
83129        int nCol;
83130        int nGroupBy;
83131
83132        groupBySort = 1;
83133        nGroupBy = pGroupBy->nExpr;
83134        nCol = nGroupBy + 1;
83135        j = nGroupBy+1;
83136        for(i=0; i<sAggInfo.nColumn; i++){
83137          if( sAggInfo.aCol[i].iSorterColumn>=j ){
83138            nCol++;
83139            j++;
83140          }
83141        }
83142        regBase = sqlite3GetTempRange(pParse, nCol);
83143        sqlite3ExprCacheClear(pParse);
83144        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
83145        sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
83146        j = nGroupBy+1;
83147        for(i=0; i<sAggInfo.nColumn; i++){
83148          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
83149          if( pCol->iSorterColumn>=j ){
83150            int r1 = j + regBase;
83151            int r2;
83152
83153            r2 = sqlite3ExprCodeGetColumn(pParse,
83154                               pCol->pTab, pCol->iColumn, pCol->iTable, r1);
83155            if( r1!=r2 ){
83156              sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
83157            }
83158            j++;
83159          }
83160        }
83161        regRecord = sqlite3GetTempReg(pParse);
83162        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
83163        sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
83164        sqlite3ReleaseTempReg(pParse, regRecord);
83165        sqlite3ReleaseTempRange(pParse, regBase, nCol);
83166        sqlite3WhereEnd(pWInfo);
83167        sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
83168        VdbeComment((v, "GROUP BY sort"));
83169        sAggInfo.useSortingIdx = 1;
83170        sqlite3ExprCacheClear(pParse);
83171      }
83172
83173      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
83174      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
83175      ** Then compare the current GROUP BY terms against the GROUP BY terms
83176      ** from the previous row currently stored in a0, a1, a2...
83177      */
83178      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
83179      sqlite3ExprCacheClear(pParse);
83180      for(j=0; j<pGroupBy->nExpr; j++){
83181        if( groupBySort ){
83182          sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
83183        }else{
83184          sAggInfo.directMode = 1;
83185          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
83186        }
83187      }
83188      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
83189                          (char*)pKeyInfo, P4_KEYINFO);
83190      j1 = sqlite3VdbeCurrentAddr(v);
83191      sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
83192
83193      /* Generate code that runs whenever the GROUP BY changes.
83194      ** Changes in the GROUP BY are detected by the previous code
83195      ** block.  If there were no changes, this block is skipped.
83196      **
83197      ** This code copies current group by terms in b0,b1,b2,...
83198      ** over to a0,a1,a2.  It then calls the output subroutine
83199      ** and resets the aggregate accumulator registers in preparation
83200      ** for the next GROUP BY batch.
83201      */
83202      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
83203      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
83204      VdbeComment((v, "output one row"));
83205      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
83206      VdbeComment((v, "check abort flag"));
83207      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
83208      VdbeComment((v, "reset accumulator"));
83209
83210      /* Update the aggregate accumulators based on the content of
83211      ** the current row
83212      */
83213      sqlite3VdbeJumpHere(v, j1);
83214      updateAccumulator(pParse, &sAggInfo);
83215      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
83216      VdbeComment((v, "indicate data in accumulator"));
83217
83218      /* End of the loop
83219      */
83220      if( groupBySort ){
83221        sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
83222      }else{
83223        sqlite3WhereEnd(pWInfo);
83224        sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
83225      }
83226
83227      /* Output the final row of result
83228      */
83229      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
83230      VdbeComment((v, "output final row"));
83231
83232      /* Jump over the subroutines
83233      */
83234      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
83235
83236      /* Generate a subroutine that outputs a single row of the result
83237      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
83238      ** is less than or equal to zero, the subroutine is a no-op.  If
83239      ** the processing calls for the query to abort, this subroutine
83240      ** increments the iAbortFlag memory location before returning in
83241      ** order to signal the caller to abort.
83242      */
83243      addrSetAbort = sqlite3VdbeCurrentAddr(v);
83244      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
83245      VdbeComment((v, "set abort flag"));
83246      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
83247      sqlite3VdbeResolveLabel(v, addrOutputRow);
83248      addrOutputRow = sqlite3VdbeCurrentAddr(v);
83249      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
83250      VdbeComment((v, "Groupby result generator entry point"));
83251      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
83252      finalizeAggFunctions(pParse, &sAggInfo);
83253      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
83254      selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
83255                      distinct, pDest,
83256                      addrOutputRow+1, addrSetAbort);
83257      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
83258      VdbeComment((v, "end groupby result generator"));
83259
83260      /* Generate a subroutine that will reset the group-by accumulator
83261      */
83262      sqlite3VdbeResolveLabel(v, addrReset);
83263      resetAccumulator(pParse, &sAggInfo);
83264      sqlite3VdbeAddOp1(v, OP_Return, regReset);
83265
83266    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
83267    else {
83268      ExprList *pDel = 0;
83269#ifndef SQLITE_OMIT_BTREECOUNT
83270      Table *pTab;
83271      if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
83272        /* If isSimpleCount() returns a pointer to a Table structure, then
83273        ** the SQL statement is of the form:
83274        **
83275        **   SELECT count(*) FROM <tbl>
83276        **
83277        ** where the Table structure returned represents table <tbl>.
83278        **
83279        ** This statement is so common that it is optimized specially. The
83280        ** OP_Count instruction is executed either on the intkey table that
83281        ** contains the data for table <tbl> or on one of its indexes. It
83282        ** is better to execute the op on an index, as indexes are almost
83283        ** always spread across less pages than their corresponding tables.
83284        */
83285        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
83286        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
83287        Index *pIdx;                         /* Iterator variable */
83288        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
83289        Index *pBest = 0;                    /* Best index found so far */
83290        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
83291
83292        sqlite3CodeVerifySchema(pParse, iDb);
83293        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
83294
83295        /* Search for the index that has the least amount of columns. If
83296        ** there is such an index, and it has less columns than the table
83297        ** does, then we can assume that it consumes less space on disk and
83298        ** will therefore be cheaper to scan to determine the query result.
83299        ** In this case set iRoot to the root page number of the index b-tree
83300        ** and pKeyInfo to the KeyInfo structure required to navigate the
83301        ** index.
83302        **
83303        ** In practice the KeyInfo structure will not be used. It is only
83304        ** passed to keep OP_OpenRead happy.
83305        */
83306        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
83307          if( !pBest || pIdx->nColumn<pBest->nColumn ){
83308            pBest = pIdx;
83309          }
83310        }
83311        if( pBest && pBest->nColumn<pTab->nCol ){
83312          iRoot = pBest->tnum;
83313          pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
83314        }
83315
83316        /* Open a read-only cursor, execute the OP_Count, close the cursor. */
83317        sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
83318        if( pKeyInfo ){
83319          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
83320        }
83321        sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
83322        sqlite3VdbeAddOp1(v, OP_Close, iCsr);
83323      }else
83324#endif /* SQLITE_OMIT_BTREECOUNT */
83325      {
83326        /* Check if the query is of one of the following forms:
83327        **
83328        **   SELECT min(x) FROM ...
83329        **   SELECT max(x) FROM ...
83330        **
83331        ** If it is, then ask the code in where.c to attempt to sort results
83332        ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
83333        ** If where.c is able to produce results sorted in this order, then
83334        ** add vdbe code to break out of the processing loop after the
83335        ** first iteration (since the first iteration of the loop is
83336        ** guaranteed to operate on the row with the minimum or maximum
83337        ** value of x, the only row required).
83338        **
83339        ** A special flag must be passed to sqlite3WhereBegin() to slightly
83340        ** modify behaviour as follows:
83341        **
83342        **   + If the query is a "SELECT min(x)", then the loop coded by
83343        **     where.c should not iterate over any values with a NULL value
83344        **     for x.
83345        **
83346        **   + The optimizer code in where.c (the thing that decides which
83347        **     index or indices to use) should place a different priority on
83348        **     satisfying the 'ORDER BY' clause than it does in other cases.
83349        **     Refer to code and comments in where.c for details.
83350        */
83351        ExprList *pMinMax = 0;
83352        u8 flag = minMaxQuery(p);
83353        if( flag ){
83354          assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
83355          pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
83356          pDel = pMinMax;
83357          if( pMinMax && !db->mallocFailed ){
83358            pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
83359            pMinMax->a[0].pExpr->op = TK_COLUMN;
83360          }
83361        }
83362
83363        /* This case runs if the aggregate has no GROUP BY clause.  The
83364        ** processing is much simpler since there is only a single row
83365        ** of output.
83366        */
83367        resetAccumulator(pParse, &sAggInfo);
83368        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
83369        if( pWInfo==0 ){
83370          sqlite3ExprListDelete(db, pDel);
83371          goto select_end;
83372        }
83373        updateAccumulator(pParse, &sAggInfo);
83374        if( !pMinMax && flag ){
83375          sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
83376          VdbeComment((v, "%s() by index",
83377                (flag==WHERE_ORDERBY_MIN?"min":"max")));
83378        }
83379        sqlite3WhereEnd(pWInfo);
83380        finalizeAggFunctions(pParse, &sAggInfo);
83381      }
83382
83383      pOrderBy = 0;
83384      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
83385      selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
83386                      pDest, addrEnd, addrEnd);
83387      sqlite3ExprListDelete(db, pDel);
83388    }
83389    sqlite3VdbeResolveLabel(v, addrEnd);
83390
83391  } /* endif aggregate query */
83392
83393  /* If there is an ORDER BY clause, then we need to sort the results
83394  ** and send them to the callback one by one.
83395  */
83396  if( pOrderBy ){
83397    generateSortTail(pParse, p, v, pEList->nExpr, pDest);
83398  }
83399
83400  /* Jump here to skip this query
83401  */
83402  sqlite3VdbeResolveLabel(v, iEnd);
83403
83404  /* The SELECT was successfully coded.   Set the return code to 0
83405  ** to indicate no errors.
83406  */
83407  rc = 0;
83408
83409  /* Control jumps to here if an error is encountered above, or upon
83410  ** successful coding of the SELECT.
83411  */
83412select_end:
83413
83414  /* Identify column names if results of the SELECT are to be output.
83415  */
83416  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
83417    generateColumnNames(pParse, pTabList, pEList);
83418  }
83419
83420  sqlite3DbFree(db, sAggInfo.aCol);
83421  sqlite3DbFree(db, sAggInfo.aFunc);
83422  return rc;
83423}
83424
83425#if defined(SQLITE_DEBUG)
83426/*
83427*******************************************************************************
83428** The following code is used for testing and debugging only.  The code
83429** that follows does not appear in normal builds.
83430**
83431** These routines are used to print out the content of all or part of a
83432** parse structures such as Select or Expr.  Such printouts are useful
83433** for helping to understand what is happening inside the code generator
83434** during the execution of complex SELECT statements.
83435**
83436** These routine are not called anywhere from within the normal
83437** code base.  Then are intended to be called from within the debugger
83438** or from temporary "printf" statements inserted for debugging.
83439*/
83440SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
83441  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
83442    sqlite3DebugPrintf("(%s", p->u.zToken);
83443  }else{
83444    sqlite3DebugPrintf("(%d", p->op);
83445  }
83446  if( p->pLeft ){
83447    sqlite3DebugPrintf(" ");
83448    sqlite3PrintExpr(p->pLeft);
83449  }
83450  if( p->pRight ){
83451    sqlite3DebugPrintf(" ");
83452    sqlite3PrintExpr(p->pRight);
83453  }
83454  sqlite3DebugPrintf(")");
83455}
83456SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
83457  int i;
83458  for(i=0; i<pList->nExpr; i++){
83459    sqlite3PrintExpr(pList->a[i].pExpr);
83460    if( i<pList->nExpr-1 ){
83461      sqlite3DebugPrintf(", ");
83462    }
83463  }
83464}
83465SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
83466  sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
83467  sqlite3PrintExprList(p->pEList);
83468  sqlite3DebugPrintf("\n");
83469  if( p->pSrc ){
83470    char *zPrefix;
83471    int i;
83472    zPrefix = "FROM";
83473    for(i=0; i<p->pSrc->nSrc; i++){
83474      struct SrcList_item *pItem = &p->pSrc->a[i];
83475      sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
83476      zPrefix = "";
83477      if( pItem->pSelect ){
83478        sqlite3DebugPrintf("(\n");
83479        sqlite3PrintSelect(pItem->pSelect, indent+10);
83480        sqlite3DebugPrintf("%*s)", indent+8, "");
83481      }else if( pItem->zName ){
83482        sqlite3DebugPrintf("%s", pItem->zName);
83483      }
83484      if( pItem->pTab ){
83485        sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
83486      }
83487      if( pItem->zAlias ){
83488        sqlite3DebugPrintf(" AS %s", pItem->zAlias);
83489      }
83490      if( i<p->pSrc->nSrc-1 ){
83491        sqlite3DebugPrintf(",");
83492      }
83493      sqlite3DebugPrintf("\n");
83494    }
83495  }
83496  if( p->pWhere ){
83497    sqlite3DebugPrintf("%*s WHERE ", indent, "");
83498    sqlite3PrintExpr(p->pWhere);
83499    sqlite3DebugPrintf("\n");
83500  }
83501  if( p->pGroupBy ){
83502    sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
83503    sqlite3PrintExprList(p->pGroupBy);
83504    sqlite3DebugPrintf("\n");
83505  }
83506  if( p->pHaving ){
83507    sqlite3DebugPrintf("%*s HAVING ", indent, "");
83508    sqlite3PrintExpr(p->pHaving);
83509    sqlite3DebugPrintf("\n");
83510  }
83511  if( p->pOrderBy ){
83512    sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
83513    sqlite3PrintExprList(p->pOrderBy);
83514    sqlite3DebugPrintf("\n");
83515  }
83516}
83517/* End of the structure debug printing code
83518*****************************************************************************/
83519#endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
83520
83521/************** End of select.c **********************************************/
83522/************** Begin file table.c *******************************************/
83523/*
83524** 2001 September 15
83525**
83526** The author disclaims copyright to this source code.  In place of
83527** a legal notice, here is a blessing:
83528**
83529**    May you do good and not evil.
83530**    May you find forgiveness for yourself and forgive others.
83531**    May you share freely, never taking more than you give.
83532**
83533*************************************************************************
83534** This file contains the sqlite3_get_table() and sqlite3_free_table()
83535** interface routines.  These are just wrappers around the main
83536** interface routine of sqlite3_exec().
83537**
83538** These routines are in a separate files so that they will not be linked
83539** if they are not used.
83540*/
83541
83542#ifndef SQLITE_OMIT_GET_TABLE
83543
83544/*
83545** This structure is used to pass data from sqlite3_get_table() through
83546** to the callback function is uses to build the result.
83547*/
83548typedef struct TabResult {
83549  char **azResult;   /* Accumulated output */
83550  char *zErrMsg;     /* Error message text, if an error occurs */
83551  int nAlloc;        /* Slots allocated for azResult[] */
83552  int nRow;          /* Number of rows in the result */
83553  int nColumn;       /* Number of columns in the result */
83554  int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
83555  int rc;            /* Return code from sqlite3_exec() */
83556} TabResult;
83557
83558/*
83559** This routine is called once for each row in the result table.  Its job
83560** is to fill in the TabResult structure appropriately, allocating new
83561** memory as necessary.
83562*/
83563static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
83564  TabResult *p = (TabResult*)pArg;  /* Result accumulator */
83565  int need;                         /* Slots needed in p->azResult[] */
83566  int i;                            /* Loop counter */
83567  char *z;                          /* A single column of result */
83568
83569  /* Make sure there is enough space in p->azResult to hold everything
83570  ** we need to remember from this invocation of the callback.
83571  */
83572  if( p->nRow==0 && argv!=0 ){
83573    need = nCol*2;
83574  }else{
83575    need = nCol;
83576  }
83577  if( p->nData + need > p->nAlloc ){
83578    char **azNew;
83579    p->nAlloc = p->nAlloc*2 + need;
83580    azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
83581    if( azNew==0 ) goto malloc_failed;
83582    p->azResult = azNew;
83583  }
83584
83585  /* If this is the first row, then generate an extra row containing
83586  ** the names of all columns.
83587  */
83588  if( p->nRow==0 ){
83589    p->nColumn = nCol;
83590    for(i=0; i<nCol; i++){
83591      z = sqlite3_mprintf("%s", colv[i]);
83592      if( z==0 ) goto malloc_failed;
83593      p->azResult[p->nData++] = z;
83594    }
83595  }else if( p->nColumn!=nCol ){
83596    sqlite3_free(p->zErrMsg);
83597    p->zErrMsg = sqlite3_mprintf(
83598       "sqlite3_get_table() called with two or more incompatible queries"
83599    );
83600    p->rc = SQLITE_ERROR;
83601    return 1;
83602  }
83603
83604  /* Copy over the row data
83605  */
83606  if( argv!=0 ){
83607    for(i=0; i<nCol; i++){
83608      if( argv[i]==0 ){
83609        z = 0;
83610      }else{
83611        int n = sqlite3Strlen30(argv[i])+1;
83612        z = sqlite3_malloc( n );
83613        if( z==0 ) goto malloc_failed;
83614        memcpy(z, argv[i], n);
83615      }
83616      p->azResult[p->nData++] = z;
83617    }
83618    p->nRow++;
83619  }
83620  return 0;
83621
83622malloc_failed:
83623  p->rc = SQLITE_NOMEM;
83624  return 1;
83625}
83626
83627/*
83628** Query the database.  But instead of invoking a callback for each row,
83629** malloc() for space to hold the result and return the entire results
83630** at the conclusion of the call.
83631**
83632** The result that is written to ***pazResult is held in memory obtained
83633** from malloc().  But the caller cannot free this memory directly.
83634** Instead, the entire table should be passed to sqlite3_free_table() when
83635** the calling procedure is finished using it.
83636*/
83637SQLITE_API int sqlite3_get_table(
83638  sqlite3 *db,                /* The database on which the SQL executes */
83639  const char *zSql,           /* The SQL to be executed */
83640  char ***pazResult,          /* Write the result table here */
83641  int *pnRow,                 /* Write the number of rows in the result here */
83642  int *pnColumn,              /* Write the number of columns of result here */
83643  char **pzErrMsg             /* Write error messages here */
83644){
83645  int rc;
83646  TabResult res;
83647
83648  *pazResult = 0;
83649  if( pnColumn ) *pnColumn = 0;
83650  if( pnRow ) *pnRow = 0;
83651  if( pzErrMsg ) *pzErrMsg = 0;
83652  res.zErrMsg = 0;
83653  res.nRow = 0;
83654  res.nColumn = 0;
83655  res.nData = 1;
83656  res.nAlloc = 20;
83657  res.rc = SQLITE_OK;
83658  res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
83659  if( res.azResult==0 ){
83660     db->errCode = SQLITE_NOMEM;
83661     return SQLITE_NOMEM;
83662  }
83663  res.azResult[0] = 0;
83664  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
83665  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
83666  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
83667  if( (rc&0xff)==SQLITE_ABORT ){
83668    sqlite3_free_table(&res.azResult[1]);
83669    if( res.zErrMsg ){
83670      if( pzErrMsg ){
83671        sqlite3_free(*pzErrMsg);
83672        *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
83673      }
83674      sqlite3_free(res.zErrMsg);
83675    }
83676    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
83677    return res.rc;
83678  }
83679  sqlite3_free(res.zErrMsg);
83680  if( rc!=SQLITE_OK ){
83681    sqlite3_free_table(&res.azResult[1]);
83682    return rc;
83683  }
83684  if( res.nAlloc>res.nData ){
83685    char **azNew;
83686    azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
83687    if( azNew==0 ){
83688      sqlite3_free_table(&res.azResult[1]);
83689      db->errCode = SQLITE_NOMEM;
83690      return SQLITE_NOMEM;
83691    }
83692    res.azResult = azNew;
83693  }
83694  *pazResult = &res.azResult[1];
83695  if( pnColumn ) *pnColumn = res.nColumn;
83696  if( pnRow ) *pnRow = res.nRow;
83697  return rc;
83698}
83699
83700/*
83701** This routine frees the space the sqlite3_get_table() malloced.
83702*/
83703SQLITE_API void sqlite3_free_table(
83704  char **azResult            /* Result returned from from sqlite3_get_table() */
83705){
83706  if( azResult ){
83707    int i, n;
83708    azResult--;
83709    assert( azResult!=0 );
83710    n = SQLITE_PTR_TO_INT(azResult[0]);
83711    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
83712    sqlite3_free(azResult);
83713  }
83714}
83715
83716#endif /* SQLITE_OMIT_GET_TABLE */
83717
83718/************** End of table.c ***********************************************/
83719/************** Begin file trigger.c *****************************************/
83720/*
83721**
83722** The author disclaims copyright to this source code.  In place of
83723** a legal notice, here is a blessing:
83724**
83725**    May you do good and not evil.
83726**    May you find forgiveness for yourself and forgive others.
83727**    May you share freely, never taking more than you give.
83728**
83729*************************************************************************
83730** This file contains the implementation for TRIGGERs
83731*/
83732
83733#ifndef SQLITE_OMIT_TRIGGER
83734/*
83735** Delete a linked list of TriggerStep structures.
83736*/
83737SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
83738  while( pTriggerStep ){
83739    TriggerStep * pTmp = pTriggerStep;
83740    pTriggerStep = pTriggerStep->pNext;
83741
83742    sqlite3ExprDelete(db, pTmp->pWhere);
83743    sqlite3ExprListDelete(db, pTmp->pExprList);
83744    sqlite3SelectDelete(db, pTmp->pSelect);
83745    sqlite3IdListDelete(db, pTmp->pIdList);
83746
83747    sqlite3DbFree(db, pTmp);
83748  }
83749}
83750
83751/*
83752** Given table pTab, return a list of all the triggers attached to
83753** the table. The list is connected by Trigger.pNext pointers.
83754**
83755** All of the triggers on pTab that are in the same database as pTab
83756** are already attached to pTab->pTrigger.  But there might be additional
83757** triggers on pTab in the TEMP schema.  This routine prepends all
83758** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
83759** and returns the combined list.
83760**
83761** To state it another way:  This routine returns a list of all triggers
83762** that fire off of pTab.  The list will include any TEMP triggers on
83763** pTab as well as the triggers lised in pTab->pTrigger.
83764*/
83765SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
83766  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
83767  Trigger *pList = 0;                  /* List of triggers to return */
83768
83769  if( pParse->disableTriggers ){
83770    return 0;
83771  }
83772
83773  if( pTmpSchema!=pTab->pSchema ){
83774    HashElem *p;
83775    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
83776      Trigger *pTrig = (Trigger *)sqliteHashData(p);
83777      if( pTrig->pTabSchema==pTab->pSchema
83778       && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
83779      ){
83780        pTrig->pNext = (pList ? pList : pTab->pTrigger);
83781        pList = pTrig;
83782      }
83783    }
83784  }
83785
83786  return (pList ? pList : pTab->pTrigger);
83787}
83788
83789/*
83790** This is called by the parser when it sees a CREATE TRIGGER statement
83791** up to the point of the BEGIN before the trigger actions.  A Trigger
83792** structure is generated based on the information available and stored
83793** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
83794** sqlite3FinishTrigger() function is called to complete the trigger
83795** construction process.
83796*/
83797SQLITE_PRIVATE void sqlite3BeginTrigger(
83798  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
83799  Token *pName1,      /* The name of the trigger */
83800  Token *pName2,      /* The name of the trigger */
83801  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
83802  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
83803  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
83804  SrcList *pTableName,/* The name of the table/view the trigger applies to */
83805  Expr *pWhen,        /* WHEN clause */
83806  int isTemp,         /* True if the TEMPORARY keyword is present */
83807  int noErr           /* Suppress errors if the trigger already exists */
83808){
83809  Trigger *pTrigger = 0;  /* The new trigger */
83810  Table *pTab;            /* Table that the trigger fires off of */
83811  char *zName = 0;        /* Name of the trigger */
83812  sqlite3 *db = pParse->db;  /* The database connection */
83813  int iDb;                /* The database to store the trigger in */
83814  Token *pName;           /* The unqualified db name */
83815  DbFixer sFix;           /* State vector for the DB fixer */
83816  int iTabDb;             /* Index of the database holding pTab */
83817
83818  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
83819  assert( pName2!=0 );
83820  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
83821  assert( op>0 && op<0xff );
83822  if( isTemp ){
83823    /* If TEMP was specified, then the trigger name may not be qualified. */
83824    if( pName2->n>0 ){
83825      sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
83826      goto trigger_cleanup;
83827    }
83828    iDb = 1;
83829    pName = pName1;
83830  }else{
83831    /* Figure out the db that the the trigger will be created in */
83832    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
83833    if( iDb<0 ){
83834      goto trigger_cleanup;
83835    }
83836  }
83837
83838  /* If the trigger name was unqualified, and the table is a temp table,
83839  ** then set iDb to 1 to create the trigger in the temporary database.
83840  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
83841  ** exist, the error is caught by the block below.
83842  */
83843  if( !pTableName || db->mallocFailed ){
83844    goto trigger_cleanup;
83845  }
83846  pTab = sqlite3SrcListLookup(pParse, pTableName);
83847  if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
83848    iDb = 1;
83849  }
83850
83851  /* Ensure the table name matches database name and that the table exists */
83852  if( db->mallocFailed ) goto trigger_cleanup;
83853  assert( pTableName->nSrc==1 );
83854  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
83855      sqlite3FixSrcList(&sFix, pTableName) ){
83856    goto trigger_cleanup;
83857  }
83858  pTab = sqlite3SrcListLookup(pParse, pTableName);
83859  if( !pTab ){
83860    /* The table does not exist. */
83861    if( db->init.iDb==1 ){
83862      /* Ticket #3810.
83863      ** Normally, whenever a table is dropped, all associated triggers are
83864      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
83865      ** and the table is dropped by a different database connection, the
83866      ** trigger is not visible to the database connection that does the
83867      ** drop so the trigger cannot be dropped.  This results in an
83868      ** "orphaned trigger" - a trigger whose associated table is missing.
83869      */
83870      db->init.orphanTrigger = 1;
83871    }
83872    goto trigger_cleanup;
83873  }
83874  if( IsVirtual(pTab) ){
83875    sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
83876    goto trigger_cleanup;
83877  }
83878
83879  /* Check that the trigger name is not reserved and that no trigger of the
83880  ** specified name exists */
83881  zName = sqlite3NameFromToken(db, pName);
83882  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
83883    goto trigger_cleanup;
83884  }
83885  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
83886                      zName, sqlite3Strlen30(zName)) ){
83887    if( !noErr ){
83888      sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
83889    }
83890    goto trigger_cleanup;
83891  }
83892
83893  /* Do not create a trigger on a system table */
83894  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
83895    sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
83896    pParse->nErr++;
83897    goto trigger_cleanup;
83898  }
83899
83900  /* INSTEAD of triggers are only for views and views only support INSTEAD
83901  ** of triggers.
83902  */
83903  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
83904    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
83905        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
83906    goto trigger_cleanup;
83907  }
83908  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
83909    sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
83910        " trigger on table: %S", pTableName, 0);
83911    goto trigger_cleanup;
83912  }
83913  iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
83914
83915#ifndef SQLITE_OMIT_AUTHORIZATION
83916  {
83917    int code = SQLITE_CREATE_TRIGGER;
83918    const char *zDb = db->aDb[iTabDb].zName;
83919    const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
83920    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
83921    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
83922      goto trigger_cleanup;
83923    }
83924    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
83925      goto trigger_cleanup;
83926    }
83927  }
83928#endif
83929
83930  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
83931  ** cannot appear on views.  So we might as well translate every
83932  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
83933  ** elsewhere.
83934  */
83935  if (tr_tm == TK_INSTEAD){
83936    tr_tm = TK_BEFORE;
83937  }
83938
83939  /* Build the Trigger object */
83940  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
83941  if( pTrigger==0 ) goto trigger_cleanup;
83942  pTrigger->zName = zName;
83943  zName = 0;
83944  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
83945  pTrigger->pSchema = db->aDb[iDb].pSchema;
83946  pTrigger->pTabSchema = pTab->pSchema;
83947  pTrigger->op = (u8)op;
83948  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
83949  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
83950  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
83951  assert( pParse->pNewTrigger==0 );
83952  pParse->pNewTrigger = pTrigger;
83953
83954trigger_cleanup:
83955  sqlite3DbFree(db, zName);
83956  sqlite3SrcListDelete(db, pTableName);
83957  sqlite3IdListDelete(db, pColumns);
83958  sqlite3ExprDelete(db, pWhen);
83959  if( !pParse->pNewTrigger ){
83960    sqlite3DeleteTrigger(db, pTrigger);
83961  }else{
83962    assert( pParse->pNewTrigger==pTrigger );
83963  }
83964}
83965
83966/*
83967** This routine is called after all of the trigger actions have been parsed
83968** in order to complete the process of building the trigger.
83969*/
83970SQLITE_PRIVATE void sqlite3FinishTrigger(
83971  Parse *pParse,          /* Parser context */
83972  TriggerStep *pStepList, /* The triggered program */
83973  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
83974){
83975  Trigger *pTrig = pParse->pNewTrigger;    /* Trigger being finished */
83976  char *zName;                             /* Name of trigger */
83977  sqlite3 *db = pParse->db;                /* The database */
83978  DbFixer sFix;
83979  int iDb;                                 /* Database containing the trigger */
83980  Token nameToken;           /* Trigger name for error reporting */
83981
83982  pTrig = pParse->pNewTrigger;
83983  pParse->pNewTrigger = 0;
83984  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
83985  zName = pTrig->zName;
83986  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
83987  pTrig->step_list = pStepList;
83988  while( pStepList ){
83989    pStepList->pTrig = pTrig;
83990    pStepList = pStepList->pNext;
83991  }
83992  nameToken.z = pTrig->zName;
83993  nameToken.n = sqlite3Strlen30(nameToken.z);
83994  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
83995          && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
83996    goto triggerfinish_cleanup;
83997  }
83998
83999  /* if we are not initializing, and this trigger is not on a TEMP table,
84000  ** build the sqlite_master entry
84001  */
84002  if( !db->init.busy ){
84003    Vdbe *v;
84004    char *z;
84005
84006    /* Make an entry in the sqlite_master table */
84007    v = sqlite3GetVdbe(pParse);
84008    if( v==0 ) goto triggerfinish_cleanup;
84009    sqlite3BeginWriteOperation(pParse, 0, iDb);
84010    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
84011    sqlite3NestedParse(pParse,
84012       "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
84013       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
84014       pTrig->table, z);
84015    sqlite3DbFree(db, z);
84016    sqlite3ChangeCookie(pParse, iDb);
84017    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
84018        db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
84019    );
84020  }
84021
84022  if( db->init.busy ){
84023    Trigger *pLink = pTrig;
84024    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
84025    pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
84026    if( pTrig ){
84027      db->mallocFailed = 1;
84028    }else if( pLink->pSchema==pLink->pTabSchema ){
84029      Table *pTab;
84030      int n = sqlite3Strlen30(pLink->table);
84031      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
84032      assert( pTab!=0 );
84033      pLink->pNext = pTab->pTrigger;
84034      pTab->pTrigger = pLink;
84035    }
84036  }
84037
84038triggerfinish_cleanup:
84039  sqlite3DeleteTrigger(db, pTrig);
84040  assert( !pParse->pNewTrigger );
84041  sqlite3DeleteTriggerStep(db, pStepList);
84042}
84043
84044/*
84045** Turn a SELECT statement (that the pSelect parameter points to) into
84046** a trigger step.  Return a pointer to a TriggerStep structure.
84047**
84048** The parser calls this routine when it finds a SELECT statement in
84049** body of a TRIGGER.
84050*/
84051SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
84052  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
84053  if( pTriggerStep==0 ) {
84054    sqlite3SelectDelete(db, pSelect);
84055    return 0;
84056  }
84057  pTriggerStep->op = TK_SELECT;
84058  pTriggerStep->pSelect = pSelect;
84059  pTriggerStep->orconf = OE_Default;
84060  return pTriggerStep;
84061}
84062
84063/*
84064** Allocate space to hold a new trigger step.  The allocated space
84065** holds both the TriggerStep object and the TriggerStep.target.z string.
84066**
84067** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
84068*/
84069static TriggerStep *triggerStepAllocate(
84070  sqlite3 *db,                /* Database connection */
84071  u8 op,                      /* Trigger opcode */
84072  Token *pName                /* The target name */
84073){
84074  TriggerStep *pTriggerStep;
84075
84076  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
84077  if( pTriggerStep ){
84078    char *z = (char*)&pTriggerStep[1];
84079    memcpy(z, pName->z, pName->n);
84080    pTriggerStep->target.z = z;
84081    pTriggerStep->target.n = pName->n;
84082    pTriggerStep->op = op;
84083  }
84084  return pTriggerStep;
84085}
84086
84087/*
84088** Build a trigger step out of an INSERT statement.  Return a pointer
84089** to the new trigger step.
84090**
84091** The parser calls this routine when it sees an INSERT inside the
84092** body of a trigger.
84093*/
84094SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
84095  sqlite3 *db,        /* The database connection */
84096  Token *pTableName,  /* Name of the table into which we insert */
84097  IdList *pColumn,    /* List of columns in pTableName to insert into */
84098  ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
84099  Select *pSelect,    /* A SELECT statement that supplies values */
84100  u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
84101){
84102  TriggerStep *pTriggerStep;
84103
84104  assert(pEList == 0 || pSelect == 0);
84105  assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
84106
84107  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
84108  if( pTriggerStep ){
84109    pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
84110    pTriggerStep->pIdList = pColumn;
84111    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
84112    pTriggerStep->orconf = orconf;
84113  }else{
84114    sqlite3IdListDelete(db, pColumn);
84115  }
84116  sqlite3ExprListDelete(db, pEList);
84117  sqlite3SelectDelete(db, pSelect);
84118
84119  return pTriggerStep;
84120}
84121
84122/*
84123** Construct a trigger step that implements an UPDATE statement and return
84124** a pointer to that trigger step.  The parser calls this routine when it
84125** sees an UPDATE statement inside the body of a CREATE TRIGGER.
84126*/
84127SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
84128  sqlite3 *db,         /* The database connection */
84129  Token *pTableName,   /* Name of the table to be updated */
84130  ExprList *pEList,    /* The SET clause: list of column and new values */
84131  Expr *pWhere,        /* The WHERE clause */
84132  u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
84133){
84134  TriggerStep *pTriggerStep;
84135
84136  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
84137  if( pTriggerStep ){
84138    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
84139    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
84140    pTriggerStep->orconf = orconf;
84141  }
84142  sqlite3ExprListDelete(db, pEList);
84143  sqlite3ExprDelete(db, pWhere);
84144  return pTriggerStep;
84145}
84146
84147/*
84148** Construct a trigger step that implements a DELETE statement and return
84149** a pointer to that trigger step.  The parser calls this routine when it
84150** sees a DELETE statement inside the body of a CREATE TRIGGER.
84151*/
84152SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
84153  sqlite3 *db,            /* Database connection */
84154  Token *pTableName,      /* The table from which rows are deleted */
84155  Expr *pWhere            /* The WHERE clause */
84156){
84157  TriggerStep *pTriggerStep;
84158
84159  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
84160  if( pTriggerStep ){
84161    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
84162    pTriggerStep->orconf = OE_Default;
84163  }
84164  sqlite3ExprDelete(db, pWhere);
84165  return pTriggerStep;
84166}
84167
84168/*
84169** Recursively delete a Trigger structure
84170*/
84171SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
84172  if( pTrigger==0 ) return;
84173  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
84174  sqlite3DbFree(db, pTrigger->zName);
84175  sqlite3DbFree(db, pTrigger->table);
84176  sqlite3ExprDelete(db, pTrigger->pWhen);
84177  sqlite3IdListDelete(db, pTrigger->pColumns);
84178  sqlite3DbFree(db, pTrigger);
84179}
84180
84181/*
84182** This function is called to drop a trigger from the database schema.
84183**
84184** This may be called directly from the parser and therefore identifies
84185** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
84186** same job as this routine except it takes a pointer to the trigger
84187** instead of the trigger name.
84188**/
84189SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
84190  Trigger *pTrigger = 0;
84191  int i;
84192  const char *zDb;
84193  const char *zName;
84194  int nName;
84195  sqlite3 *db = pParse->db;
84196
84197  if( db->mallocFailed ) goto drop_trigger_cleanup;
84198  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
84199    goto drop_trigger_cleanup;
84200  }
84201
84202  assert( pName->nSrc==1 );
84203  zDb = pName->a[0].zDatabase;
84204  zName = pName->a[0].zName;
84205  nName = sqlite3Strlen30(zName);
84206  for(i=OMIT_TEMPDB; i<db->nDb; i++){
84207    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
84208    if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
84209    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
84210    if( pTrigger ) break;
84211  }
84212  if( !pTrigger ){
84213    if( !noErr ){
84214      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
84215    }
84216    goto drop_trigger_cleanup;
84217  }
84218  sqlite3DropTriggerPtr(pParse, pTrigger);
84219
84220drop_trigger_cleanup:
84221  sqlite3SrcListDelete(db, pName);
84222}
84223
84224/*
84225** Return a pointer to the Table structure for the table that a trigger
84226** is set on.
84227*/
84228static Table *tableOfTrigger(Trigger *pTrigger){
84229  int n = sqlite3Strlen30(pTrigger->table);
84230  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
84231}
84232
84233
84234/*
84235** Drop a trigger given a pointer to that trigger.
84236*/
84237SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
84238  Table   *pTable;
84239  Vdbe *v;
84240  sqlite3 *db = pParse->db;
84241  int iDb;
84242
84243  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
84244  assert( iDb>=0 && iDb<db->nDb );
84245  pTable = tableOfTrigger(pTrigger);
84246  assert( pTable );
84247  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
84248#ifndef SQLITE_OMIT_AUTHORIZATION
84249  {
84250    int code = SQLITE_DROP_TRIGGER;
84251    const char *zDb = db->aDb[iDb].zName;
84252    const char *zTab = SCHEMA_TABLE(iDb);
84253    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
84254    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
84255      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
84256      return;
84257    }
84258  }
84259#endif
84260
84261  /* Generate code to destroy the database record of the trigger.
84262  */
84263  assert( pTable!=0 );
84264  if( (v = sqlite3GetVdbe(pParse))!=0 ){
84265    int base;
84266    static const VdbeOpList dropTrigger[] = {
84267      { OP_Rewind,     0, ADDR(9),  0},
84268      { OP_String8,    0, 1,        0}, /* 1 */
84269      { OP_Column,     0, 1,        2},
84270      { OP_Ne,         2, ADDR(8),  1},
84271      { OP_String8,    0, 1,        0}, /* 4: "trigger" */
84272      { OP_Column,     0, 0,        2},
84273      { OP_Ne,         2, ADDR(8),  1},
84274      { OP_Delete,     0, 0,        0},
84275      { OP_Next,       0, ADDR(1),  0}, /* 8 */
84276    };
84277
84278    sqlite3BeginWriteOperation(pParse, 0, iDb);
84279    sqlite3OpenMasterTable(pParse, iDb);
84280    base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
84281    sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, 0);
84282    sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
84283    sqlite3ChangeCookie(pParse, iDb);
84284    sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
84285    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
84286    if( pParse->nMem<3 ){
84287      pParse->nMem = 3;
84288    }
84289  }
84290}
84291
84292/*
84293** Remove a trigger from the hash tables of the sqlite* pointer.
84294*/
84295SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
84296  Hash *pHash = &(db->aDb[iDb].pSchema->trigHash);
84297  Trigger *pTrigger;
84298  pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
84299  if( ALWAYS(pTrigger) ){
84300    if( pTrigger->pSchema==pTrigger->pTabSchema ){
84301      Table *pTab = tableOfTrigger(pTrigger);
84302      Trigger **pp;
84303      for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
84304      *pp = (*pp)->pNext;
84305    }
84306    sqlite3DeleteTrigger(db, pTrigger);
84307    db->flags |= SQLITE_InternChanges;
84308  }
84309}
84310
84311/*
84312** pEList is the SET clause of an UPDATE statement.  Each entry
84313** in pEList is of the format <id>=<expr>.  If any of the entries
84314** in pEList have an <id> which matches an identifier in pIdList,
84315** then return TRUE.  If pIdList==NULL, then it is considered a
84316** wildcard that matches anything.  Likewise if pEList==NULL then
84317** it matches anything so always return true.  Return false only
84318** if there is no match.
84319*/
84320static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
84321  int e;
84322  if( pIdList==0 || NEVER(pEList==0) ) return 1;
84323  for(e=0; e<pEList->nExpr; e++){
84324    if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
84325  }
84326  return 0;
84327}
84328
84329/*
84330** Return a list of all triggers on table pTab if there exists at least
84331** one trigger that must be fired when an operation of type 'op' is
84332** performed on the table, and, if that operation is an UPDATE, if at
84333** least one of the columns in pChanges is being modified.
84334*/
84335SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
84336  Parse *pParse,          /* Parse context */
84337  Table *pTab,            /* The table the contains the triggers */
84338  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
84339  ExprList *pChanges,     /* Columns that change in an UPDATE statement */
84340  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
84341){
84342  int mask = 0;
84343  Trigger *pList = sqlite3TriggerList(pParse, pTab);
84344  Trigger *p;
84345  assert( pList==0 || IsVirtual(pTab)==0 );
84346  for(p=pList; p; p=p->pNext){
84347    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
84348      mask |= p->tr_tm;
84349    }
84350  }
84351  if( pMask ){
84352    *pMask = mask;
84353  }
84354  return (mask ? pList : 0);
84355}
84356
84357/*
84358** Convert the pStep->target token into a SrcList and return a pointer
84359** to that SrcList.
84360**
84361** This routine adds a specific database name, if needed, to the target when
84362** forming the SrcList.  This prevents a trigger in one database from
84363** referring to a target in another database.  An exception is when the
84364** trigger is in TEMP in which case it can refer to any other database it
84365** wants.
84366*/
84367static SrcList *targetSrcList(
84368  Parse *pParse,       /* The parsing context */
84369  TriggerStep *pStep   /* The trigger containing the target token */
84370){
84371  int iDb;             /* Index of the database to use */
84372  SrcList *pSrc;       /* SrcList to be returned */
84373
84374  pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
84375  if( pSrc ){
84376    assert( pSrc->nSrc>0 );
84377    assert( pSrc->a!=0 );
84378    iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
84379    if( iDb==0 || iDb>=2 ){
84380      sqlite3 *db = pParse->db;
84381      assert( iDb<pParse->db->nDb );
84382      pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
84383    }
84384  }
84385  return pSrc;
84386}
84387
84388/*
84389** Generate VDBE code for the statements inside the body of a single
84390** trigger.
84391*/
84392static int codeTriggerProgram(
84393  Parse *pParse,            /* The parser context */
84394  TriggerStep *pStepList,   /* List of statements inside the trigger body */
84395  int orconf                /* Conflict algorithm. (OE_Abort, etc) */
84396){
84397  TriggerStep *pStep;
84398  Vdbe *v = pParse->pVdbe;
84399  sqlite3 *db = pParse->db;
84400
84401  assert( pParse->pTriggerTab && pParse->pToplevel );
84402  assert( pStepList );
84403  assert( v!=0 );
84404  for(pStep=pStepList; pStep; pStep=pStep->pNext){
84405    /* Figure out the ON CONFLICT policy that will be used for this step
84406    ** of the trigger program. If the statement that caused this trigger
84407    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
84408    ** the ON CONFLICT policy that was specified as part of the trigger
84409    ** step statement. Example:
84410    **
84411    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
84412    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
84413    **   END;
84414    **
84415    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
84416    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
84417    */
84418    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
84419
84420    switch( pStep->op ){
84421      case TK_UPDATE: {
84422        sqlite3Update(pParse,
84423          targetSrcList(pParse, pStep),
84424          sqlite3ExprListDup(db, pStep->pExprList, 0),
84425          sqlite3ExprDup(db, pStep->pWhere, 0),
84426          pParse->eOrconf
84427        );
84428        break;
84429      }
84430      case TK_INSERT: {
84431        sqlite3Insert(pParse,
84432          targetSrcList(pParse, pStep),
84433          sqlite3ExprListDup(db, pStep->pExprList, 0),
84434          sqlite3SelectDup(db, pStep->pSelect, 0),
84435          sqlite3IdListDup(db, pStep->pIdList),
84436          pParse->eOrconf
84437        );
84438        break;
84439      }
84440      case TK_DELETE: {
84441        sqlite3DeleteFrom(pParse,
84442          targetSrcList(pParse, pStep),
84443          sqlite3ExprDup(db, pStep->pWhere, 0)
84444        );
84445        break;
84446      }
84447      default: assert( pStep->op==TK_SELECT ); {
84448        SelectDest sDest;
84449        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
84450        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
84451        sqlite3Select(pParse, pSelect, &sDest);
84452        sqlite3SelectDelete(db, pSelect);
84453        break;
84454      }
84455    }
84456    if( pStep->op!=TK_SELECT ){
84457      sqlite3VdbeAddOp0(v, OP_ResetCount);
84458    }
84459  }
84460
84461  return 0;
84462}
84463
84464#ifdef SQLITE_DEBUG
84465/*
84466** This function is used to add VdbeComment() annotations to a VDBE
84467** program. It is not used in production code, only for debugging.
84468*/
84469static const char *onErrorText(int onError){
84470  switch( onError ){
84471    case OE_Abort:    return "abort";
84472    case OE_Rollback: return "rollback";
84473    case OE_Fail:     return "fail";
84474    case OE_Replace:  return "replace";
84475    case OE_Ignore:   return "ignore";
84476    case OE_Default:  return "default";
84477  }
84478  return "n/a";
84479}
84480#endif
84481
84482/*
84483** Parse context structure pFrom has just been used to create a sub-vdbe
84484** (trigger program). If an error has occurred, transfer error information
84485** from pFrom to pTo.
84486*/
84487static void transferParseError(Parse *pTo, Parse *pFrom){
84488  assert( pFrom->zErrMsg==0 || pFrom->nErr );
84489  assert( pTo->zErrMsg==0 || pTo->nErr );
84490  if( pTo->nErr==0 ){
84491    pTo->zErrMsg = pFrom->zErrMsg;
84492    pTo->nErr = pFrom->nErr;
84493  }else{
84494    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
84495  }
84496}
84497
84498/*
84499** Create and populate a new TriggerPrg object with a sub-program
84500** implementing trigger pTrigger with ON CONFLICT policy orconf.
84501*/
84502static TriggerPrg *codeRowTrigger(
84503  Parse *pParse,       /* Current parse context */
84504  Trigger *pTrigger,   /* Trigger to code */
84505  Table *pTab,         /* The table pTrigger is attached to */
84506  int orconf           /* ON CONFLICT policy to code trigger program with */
84507){
84508  Parse *pTop = sqlite3ParseToplevel(pParse);
84509  sqlite3 *db = pParse->db;   /* Database handle */
84510  TriggerPrg *pPrg;           /* Value to return */
84511  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
84512  Vdbe *v;                    /* Temporary VM */
84513  NameContext sNC;            /* Name context for sub-vdbe */
84514  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
84515  Parse *pSubParse;           /* Parse context for sub-vdbe */
84516  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
84517
84518  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
84519
84520  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
84521  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
84522  ** list of the top-level Parse object sooner rather than later.  */
84523  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
84524  if( !pPrg ) return 0;
84525  pPrg->pNext = pTop->pTriggerPrg;
84526  pTop->pTriggerPrg = pPrg;
84527  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
84528  if( !pProgram ) return 0;
84529  pProgram->nRef = 1;
84530  pPrg->pTrigger = pTrigger;
84531  pPrg->orconf = orconf;
84532  pPrg->aColmask[0] = 0xffffffff;
84533  pPrg->aColmask[1] = 0xffffffff;
84534
84535  /* Allocate and populate a new Parse context to use for coding the
84536  ** trigger sub-program.  */
84537  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
84538  if( !pSubParse ) return 0;
84539  memset(&sNC, 0, sizeof(sNC));
84540  sNC.pParse = pSubParse;
84541  pSubParse->db = db;
84542  pSubParse->pTriggerTab = pTab;
84543  pSubParse->pToplevel = pTop;
84544  pSubParse->zAuthContext = pTrigger->zName;
84545  pSubParse->eTriggerOp = pTrigger->op;
84546
84547  v = sqlite3GetVdbe(pSubParse);
84548  if( v ){
84549    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
84550      pTrigger->zName, onErrorText(orconf),
84551      (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
84552        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
84553        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
84554        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
84555      pTab->zName
84556    ));
84557#ifndef SQLITE_OMIT_TRACE
84558    sqlite3VdbeChangeP4(v, -1,
84559      sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
84560    );
84561#endif
84562
84563    /* If one was specified, code the WHEN clause. If it evaluates to false
84564    ** (or NULL) the sub-vdbe is immediately halted by jumping to the
84565    ** OP_Halt inserted at the end of the program.  */
84566    if( pTrigger->pWhen ){
84567      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
84568      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
84569       && db->mallocFailed==0
84570      ){
84571        iEndTrigger = sqlite3VdbeMakeLabel(v);
84572        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
84573      }
84574      sqlite3ExprDelete(db, pWhen);
84575    }
84576
84577    /* Code the trigger program into the sub-vdbe. */
84578    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
84579
84580    /* Insert an OP_Halt at the end of the sub-program. */
84581    if( iEndTrigger ){
84582      sqlite3VdbeResolveLabel(v, iEndTrigger);
84583    }
84584    sqlite3VdbeAddOp0(v, OP_Halt);
84585    VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
84586
84587    transferParseError(pParse, pSubParse);
84588    if( db->mallocFailed==0 ){
84589      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
84590    }
84591    pProgram->nMem = pSubParse->nMem;
84592    pProgram->nCsr = pSubParse->nTab;
84593    pProgram->token = (void *)pTrigger;
84594    pPrg->aColmask[0] = pSubParse->oldmask;
84595    pPrg->aColmask[1] = pSubParse->newmask;
84596    sqlite3VdbeDelete(v);
84597  }
84598
84599  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
84600  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
84601  sqlite3StackFree(db, pSubParse);
84602
84603  return pPrg;
84604}
84605
84606/*
84607** Return a pointer to a TriggerPrg object containing the sub-program for
84608** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
84609** TriggerPrg object exists, a new object is allocated and populated before
84610** being returned.
84611*/
84612static TriggerPrg *getRowTrigger(
84613  Parse *pParse,       /* Current parse context */
84614  Trigger *pTrigger,   /* Trigger to code */
84615  Table *pTab,         /* The table trigger pTrigger is attached to */
84616  int orconf           /* ON CONFLICT algorithm. */
84617){
84618  Parse *pRoot = sqlite3ParseToplevel(pParse);
84619  TriggerPrg *pPrg;
84620
84621  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
84622
84623  /* It may be that this trigger has already been coded (or is in the
84624  ** process of being coded). If this is the case, then an entry with
84625  ** a matching TriggerPrg.pTrigger field will be present somewhere
84626  ** in the Parse.pTriggerPrg list. Search for such an entry.  */
84627  for(pPrg=pRoot->pTriggerPrg;
84628      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
84629      pPrg=pPrg->pNext
84630  );
84631
84632  /* If an existing TriggerPrg could not be located, create a new one. */
84633  if( !pPrg ){
84634    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
84635  }
84636
84637  return pPrg;
84638}
84639
84640/*
84641** Generate code for the trigger program associated with trigger p on
84642** table pTab. The reg, orconf and ignoreJump parameters passed to this
84643** function are the same as those described in the header function for
84644** sqlite3CodeRowTrigger()
84645*/
84646SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
84647  Parse *pParse,       /* Parse context */
84648  Trigger *p,          /* Trigger to code */
84649  Table *pTab,         /* The table to code triggers from */
84650  int reg,             /* Reg array containing OLD.* and NEW.* values */
84651  int orconf,          /* ON CONFLICT policy */
84652  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
84653){
84654  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
84655  TriggerPrg *pPrg;
84656  pPrg = getRowTrigger(pParse, p, pTab, orconf);
84657  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
84658
84659  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
84660  ** is a pointer to the sub-vdbe containing the trigger program.  */
84661  if( pPrg ){
84662    sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
84663    pPrg->pProgram->nRef++;
84664    sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
84665    VdbeComment(
84666        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
84667
84668    /* Set the P5 operand of the OP_Program instruction to non-zero if
84669    ** recursive invocation of this trigger program is disallowed. Recursive
84670    ** invocation is disallowed if (a) the sub-program is really a trigger,
84671    ** not a foreign key action, and (b) the flag to enable recursive triggers
84672    ** is clear.  */
84673    sqlite3VdbeChangeP5(v, (u8)(p->zName && !(pParse->db->flags&SQLITE_RecTriggers)));
84674  }
84675}
84676
84677/*
84678** This is called to code the required FOR EACH ROW triggers for an operation
84679** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
84680** is given by the op paramater. The tr_tm parameter determines whether the
84681** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
84682** parameter pChanges is passed the list of columns being modified.
84683**
84684** If there are no triggers that fire at the specified time for the specified
84685** operation on pTab, this function is a no-op.
84686**
84687** The reg argument is the address of the first in an array of registers
84688** that contain the values substituted for the new.* and old.* references
84689** in the trigger program. If N is the number of columns in table pTab
84690** (a copy of pTab->nCol), then registers are populated as follows:
84691**
84692**   Register       Contains
84693**   ------------------------------------------------------
84694**   reg+0          OLD.rowid
84695**   reg+1          OLD.* value of left-most column of pTab
84696**   ...            ...
84697**   reg+N          OLD.* value of right-most column of pTab
84698**   reg+N+1        NEW.rowid
84699**   reg+N+2        OLD.* value of left-most column of pTab
84700**   ...            ...
84701**   reg+N+N+1      NEW.* value of right-most column of pTab
84702**
84703** For ON DELETE triggers, the registers containing the NEW.* values will
84704** never be accessed by the trigger program, so they are not allocated or
84705** populated by the caller (there is no data to populate them with anyway).
84706** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
84707** are never accessed, and so are not allocated by the caller. So, for an
84708** ON INSERT trigger, the value passed to this function as parameter reg
84709** is not a readable register, although registers (reg+N) through
84710** (reg+N+N+1) are.
84711**
84712** Parameter orconf is the default conflict resolution algorithm for the
84713** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
84714** is the instruction that control should jump to if a trigger program
84715** raises an IGNORE exception.
84716*/
84717SQLITE_PRIVATE void sqlite3CodeRowTrigger(
84718  Parse *pParse,       /* Parse context */
84719  Trigger *pTrigger,   /* List of triggers on table pTab */
84720  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
84721  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
84722  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
84723  Table *pTab,         /* The table to code triggers from */
84724  int reg,             /* The first in an array of registers (see above) */
84725  int orconf,          /* ON CONFLICT policy */
84726  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
84727){
84728  Trigger *p;          /* Used to iterate through pTrigger list */
84729
84730  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
84731  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
84732  assert( (op==TK_UPDATE)==(pChanges!=0) );
84733
84734  for(p=pTrigger; p; p=p->pNext){
84735
84736    /* Sanity checking:  The schema for the trigger and for the table are
84737    ** always defined.  The trigger must be in the same schema as the table
84738    ** or else it must be a TEMP trigger. */
84739    assert( p->pSchema!=0 );
84740    assert( p->pTabSchema!=0 );
84741    assert( p->pSchema==p->pTabSchema
84742         || p->pSchema==pParse->db->aDb[1].pSchema );
84743
84744    /* Determine whether we should code this trigger */
84745    if( p->op==op
84746     && p->tr_tm==tr_tm
84747     && checkColumnOverlap(p->pColumns, pChanges)
84748    ){
84749      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
84750    }
84751  }
84752}
84753
84754/*
84755** Triggers may access values stored in the old.* or new.* pseudo-table.
84756** This function returns a 32-bit bitmask indicating which columns of the
84757** old.* or new.* tables actually are used by triggers. This information
84758** may be used by the caller, for example, to avoid having to load the entire
84759** old.* record into memory when executing an UPDATE or DELETE command.
84760**
84761** Bit 0 of the returned mask is set if the left-most column of the
84762** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
84763** the second leftmost column value is required, and so on. If there
84764** are more than 32 columns in the table, and at least one of the columns
84765** with an index greater than 32 may be accessed, 0xffffffff is returned.
84766**
84767** It is not possible to determine if the old.rowid or new.rowid column is
84768** accessed by triggers. The caller must always assume that it is.
84769**
84770** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
84771** applies to the old.* table. If 1, the new.* table.
84772**
84773** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
84774** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
84775** included in the returned mask if the TRIGGER_BEFORE bit is set in the
84776** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
84777** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
84778*/
84779SQLITE_PRIVATE u32 sqlite3TriggerColmask(
84780  Parse *pParse,       /* Parse context */
84781  Trigger *pTrigger,   /* List of triggers on table pTab */
84782  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
84783  int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
84784  int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
84785  Table *pTab,         /* The table to code triggers from */
84786  int orconf           /* Default ON CONFLICT policy for trigger steps */
84787){
84788  const int op = pChanges ? TK_UPDATE : TK_DELETE;
84789  u32 mask = 0;
84790  Trigger *p;
84791
84792  assert( isNew==1 || isNew==0 );
84793  for(p=pTrigger; p; p=p->pNext){
84794    if( p->op==op && (tr_tm&p->tr_tm)
84795     && checkColumnOverlap(p->pColumns,pChanges)
84796    ){
84797      TriggerPrg *pPrg;
84798      pPrg = getRowTrigger(pParse, p, pTab, orconf);
84799      if( pPrg ){
84800        mask |= pPrg->aColmask[isNew];
84801      }
84802    }
84803  }
84804
84805  return mask;
84806}
84807
84808#endif /* !defined(SQLITE_OMIT_TRIGGER) */
84809
84810/************** End of trigger.c *********************************************/
84811/************** Begin file update.c ******************************************/
84812/*
84813** 2001 September 15
84814**
84815** The author disclaims copyright to this source code.  In place of
84816** a legal notice, here is a blessing:
84817**
84818**    May you do good and not evil.
84819**    May you find forgiveness for yourself and forgive others.
84820**    May you share freely, never taking more than you give.
84821**
84822*************************************************************************
84823** This file contains C code routines that are called by the parser
84824** to handle UPDATE statements.
84825*/
84826
84827#ifndef SQLITE_OMIT_VIRTUALTABLE
84828/* Forward declaration */
84829static void updateVirtualTable(
84830  Parse *pParse,       /* The parsing context */
84831  SrcList *pSrc,       /* The virtual table to be modified */
84832  Table *pTab,         /* The virtual table */
84833  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
84834  Expr *pRowidExpr,    /* Expression used to recompute the rowid */
84835  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
84836  Expr *pWhere         /* WHERE clause of the UPDATE statement */
84837);
84838#endif /* SQLITE_OMIT_VIRTUALTABLE */
84839
84840/*
84841** The most recently coded instruction was an OP_Column to retrieve the
84842** i-th column of table pTab. This routine sets the P4 parameter of the
84843** OP_Column to the default value, if any.
84844**
84845** The default value of a column is specified by a DEFAULT clause in the
84846** column definition. This was either supplied by the user when the table
84847** was created, or added later to the table definition by an ALTER TABLE
84848** command. If the latter, then the row-records in the table btree on disk
84849** may not contain a value for the column and the default value, taken
84850** from the P4 parameter of the OP_Column instruction, is returned instead.
84851** If the former, then all row-records are guaranteed to include a value
84852** for the column and the P4 value is not required.
84853**
84854** Column definitions created by an ALTER TABLE command may only have
84855** literal default values specified: a number, null or a string. (If a more
84856** complicated default expression value was provided, it is evaluated
84857** when the ALTER TABLE is executed and one of the literal values written
84858** into the sqlite_master table.)
84859**
84860** Therefore, the P4 parameter is only required if the default value for
84861** the column is a literal number, string or null. The sqlite3ValueFromExpr()
84862** function is capable of transforming these types of expressions into
84863** sqlite3_value objects.
84864**
84865** If parameter iReg is not negative, code an OP_RealAffinity instruction
84866** on register iReg. This is used when an equivalent integer value is
84867** stored in place of an 8-byte floating point value in order to save
84868** space.
84869*/
84870SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
84871  assert( pTab!=0 );
84872  if( !pTab->pSelect ){
84873    sqlite3_value *pValue;
84874    u8 enc = ENC(sqlite3VdbeDb(v));
84875    Column *pCol = &pTab->aCol[i];
84876    VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
84877    assert( i<pTab->nCol );
84878    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
84879                         pCol->affinity, &pValue);
84880    if( pValue ){
84881      sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
84882    }
84883#ifndef SQLITE_OMIT_FLOATING_POINT
84884    if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
84885      sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
84886    }
84887#endif
84888  }
84889}
84890
84891/*
84892** Process an UPDATE statement.
84893**
84894**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
84895**          \_______/ \________/     \______/       \________________/
84896*            onError   pTabList      pChanges             pWhere
84897*/
84898SQLITE_PRIVATE void sqlite3Update(
84899  Parse *pParse,         /* The parser context */
84900  SrcList *pTabList,     /* The table in which we should change things */
84901  ExprList *pChanges,    /* Things to be changed */
84902  Expr *pWhere,          /* The WHERE clause.  May be null */
84903  int onError            /* How to handle constraint errors */
84904){
84905  int i, j;              /* Loop counters */
84906  Table *pTab;           /* The table to be updated */
84907  int addr = 0;          /* VDBE instruction address of the start of the loop */
84908  WhereInfo *pWInfo;     /* Information about the WHERE clause */
84909  Vdbe *v;               /* The virtual database engine */
84910  Index *pIdx;           /* For looping over indices */
84911  int nIdx;              /* Number of indices that need updating */
84912  int iCur;              /* VDBE Cursor number of pTab */
84913  sqlite3 *db;           /* The database structure */
84914  int *aRegIdx = 0;      /* One register assigned to each index to be updated */
84915  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
84916                         ** an expression for the i-th column of the table.
84917                         ** aXRef[i]==-1 if the i-th column is not changed. */
84918  int chngRowid;         /* True if the record number is being changed */
84919  Expr *pRowidExpr = 0;  /* Expression defining the new record number */
84920  int openAll = 0;       /* True if all indices need to be opened */
84921  AuthContext sContext;  /* The authorization context */
84922  NameContext sNC;       /* The name-context to resolve expressions in */
84923  int iDb;               /* Database containing the table being updated */
84924  int okOnePass;         /* True for one-pass algorithm without the FIFO */
84925  int hasFK;             /* True if foreign key processing is required */
84926
84927#ifndef SQLITE_OMIT_TRIGGER
84928  int isView;            /* True when updating a view (INSTEAD OF trigger) */
84929  Trigger *pTrigger;     /* List of triggers on pTab, if required */
84930  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
84931#endif
84932  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
84933
84934  /* Register Allocations */
84935  int regRowCount = 0;   /* A count of rows changed */
84936  int regOldRowid;       /* The old rowid */
84937  int regNewRowid;       /* The new rowid */
84938  int regNew;
84939  int regOld = 0;
84940  int regRowSet = 0;     /* Rowset of rows to be updated */
84941  int regRec;            /* Register used for new table record to insert */
84942
84943  memset(&sContext, 0, sizeof(sContext));
84944  db = pParse->db;
84945  if( pParse->nErr || db->mallocFailed ){
84946    goto update_cleanup;
84947  }
84948  assert( pTabList->nSrc==1 );
84949
84950  /* Locate the table which we want to update.
84951  */
84952  pTab = sqlite3SrcListLookup(pParse, pTabList);
84953  if( pTab==0 ) goto update_cleanup;
84954  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84955
84956  /* Figure out if we have any triggers and if the table being
84957  ** updated is a view.
84958  */
84959#ifndef SQLITE_OMIT_TRIGGER
84960  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
84961  isView = pTab->pSelect!=0;
84962  assert( pTrigger || tmask==0 );
84963#else
84964# define pTrigger 0
84965# define isView 0
84966# define tmask 0
84967#endif
84968#ifdef SQLITE_OMIT_VIEW
84969# undef isView
84970# define isView 0
84971#endif
84972
84973  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
84974    goto update_cleanup;
84975  }
84976  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
84977    goto update_cleanup;
84978  }
84979  aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
84980  if( aXRef==0 ) goto update_cleanup;
84981  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
84982
84983  /* Allocate a cursors for the main database table and for all indices.
84984  ** The index cursors might not be used, but if they are used they
84985  ** need to occur right after the database cursor.  So go ahead and
84986  ** allocate enough space, just in case.
84987  */
84988  pTabList->a[0].iCursor = iCur = pParse->nTab++;
84989  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84990    pParse->nTab++;
84991  }
84992
84993  /* Initialize the name-context */
84994  memset(&sNC, 0, sizeof(sNC));
84995  sNC.pParse = pParse;
84996  sNC.pSrcList = pTabList;
84997
84998  /* Resolve the column names in all the expressions of the
84999  ** of the UPDATE statement.  Also find the column index
85000  ** for each column to be updated in the pChanges array.  For each
85001  ** column to be updated, make sure we have authorization to change
85002  ** that column.
85003  */
85004  chngRowid = 0;
85005  for(i=0; i<pChanges->nExpr; i++){
85006    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
85007      goto update_cleanup;
85008    }
85009    for(j=0; j<pTab->nCol; j++){
85010      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
85011        if( j==pTab->iPKey ){
85012          chngRowid = 1;
85013          pRowidExpr = pChanges->a[i].pExpr;
85014        }
85015        aXRef[j] = i;
85016        break;
85017      }
85018    }
85019    if( j>=pTab->nCol ){
85020      if( sqlite3IsRowid(pChanges->a[i].zName) ){
85021        chngRowid = 1;
85022        pRowidExpr = pChanges->a[i].pExpr;
85023      }else{
85024        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
85025        goto update_cleanup;
85026      }
85027    }
85028#ifndef SQLITE_OMIT_AUTHORIZATION
85029    {
85030      int rc;
85031      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
85032                           pTab->aCol[j].zName, db->aDb[iDb].zName);
85033      if( rc==SQLITE_DENY ){
85034        goto update_cleanup;
85035      }else if( rc==SQLITE_IGNORE ){
85036        aXRef[j] = -1;
85037      }
85038    }
85039#endif
85040  }
85041
85042  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
85043
85044  /* Allocate memory for the array aRegIdx[].  There is one entry in the
85045  ** array for each index associated with table being updated.  Fill in
85046  ** the value with a register number for indices that are to be used
85047  ** and with zero for unused indices.
85048  */
85049  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
85050  if( nIdx>0 ){
85051    aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
85052    if( aRegIdx==0 ) goto update_cleanup;
85053  }
85054  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
85055    int reg;
85056    if( chngRowid ){
85057      reg = ++pParse->nMem;
85058    }else{
85059      reg = 0;
85060      for(i=0; i<pIdx->nColumn; i++){
85061        if( aXRef[pIdx->aiColumn[i]]>=0 ){
85062          reg = ++pParse->nMem;
85063          break;
85064        }
85065      }
85066    }
85067    aRegIdx[j] = reg;
85068  }
85069
85070  /* Begin generating code. */
85071  v = sqlite3GetVdbe(pParse);
85072  if( v==0 ) goto update_cleanup;
85073  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
85074  sqlite3BeginWriteOperation(pParse, 1, iDb);
85075
85076#ifndef SQLITE_OMIT_VIRTUALTABLE
85077  /* Virtual tables must be handled separately */
85078  if( IsVirtual(pTab) ){
85079    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
85080                       pWhere);
85081    pWhere = 0;
85082    pTabList = 0;
85083    goto update_cleanup;
85084  }
85085#endif
85086
85087  /* Allocate required registers. */
85088  regOldRowid = regNewRowid = ++pParse->nMem;
85089  if( pTrigger || hasFK ){
85090    regOld = pParse->nMem + 1;
85091    pParse->nMem += pTab->nCol;
85092  }
85093  if( chngRowid || pTrigger || hasFK ){
85094    regNewRowid = ++pParse->nMem;
85095  }
85096  regNew = pParse->nMem + 1;
85097  pParse->nMem += pTab->nCol;
85098  regRec = ++pParse->nMem;
85099
85100  /* Start the view context. */
85101  if( isView ){
85102    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
85103  }
85104
85105  /* If we are trying to update a view, realize that view into
85106  ** a ephemeral table.
85107  */
85108#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
85109  if( isView ){
85110    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
85111  }
85112#endif
85113
85114  /* Resolve the column names in all the expressions in the
85115  ** WHERE clause.
85116  */
85117  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
85118    goto update_cleanup;
85119  }
85120
85121  /* Begin the database scan
85122  */
85123  sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
85124  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
85125  if( pWInfo==0 ) goto update_cleanup;
85126  okOnePass = pWInfo->okOnePass;
85127
85128  /* Remember the rowid of every item to be updated.
85129  */
85130  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
85131  if( !okOnePass ){
85132    regRowSet = ++pParse->nMem;
85133    sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
85134  }
85135
85136  /* End the database scan loop.
85137  */
85138  sqlite3WhereEnd(pWInfo);
85139
85140  /* Initialize the count of updated rows
85141  */
85142  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
85143    regRowCount = ++pParse->nMem;
85144    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
85145  }
85146
85147  if( !isView ){
85148    /*
85149    ** Open every index that needs updating.  Note that if any
85150    ** index could potentially invoke a REPLACE conflict resolution
85151    ** action, then we need to open all indices because we might need
85152    ** to be deleting some records.
85153    */
85154    if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
85155    if( onError==OE_Replace ){
85156      openAll = 1;
85157    }else{
85158      openAll = 0;
85159      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85160        if( pIdx->onError==OE_Replace ){
85161          openAll = 1;
85162          break;
85163        }
85164      }
85165    }
85166    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
85167      if( openAll || aRegIdx[i]>0 ){
85168        KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
85169        sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
85170                       (char*)pKey, P4_KEYINFO_HANDOFF);
85171        assert( pParse->nTab>iCur+i+1 );
85172      }
85173    }
85174  }
85175
85176  /* Top of the update loop */
85177  if( okOnePass ){
85178    int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
85179    addr = sqlite3VdbeAddOp0(v, OP_Goto);
85180    sqlite3VdbeJumpHere(v, a1);
85181  }else{
85182    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
85183  }
85184
85185  /* Make cursor iCur point to the record that is being updated. If
85186  ** this record does not exist for some reason (deleted by a trigger,
85187  ** for example, then jump to the next iteration of the RowSet loop.  */
85188  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
85189
85190  /* If the record number will change, set register regNewRowid to
85191  ** contain the new value. If the record number is not being modified,
85192  ** then regNewRowid is the same register as regOldRowid, which is
85193  ** already populated.  */
85194  assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
85195  if( chngRowid ){
85196    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
85197    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
85198  }
85199
85200  /* If there are triggers on this table, populate an array of registers
85201  ** with the required old.* column data.  */
85202  if( hasFK || pTrigger ){
85203    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
85204    oldmask |= sqlite3TriggerColmask(pParse,
85205        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
85206    );
85207    for(i=0; i<pTab->nCol; i++){
85208      if( aXRef[i]<0 || oldmask==0xffffffff || (oldmask & (1<<i)) ){
85209        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regOld+i);
85210        sqlite3ColumnDefault(v, pTab, i, regOld+i);
85211      }else{
85212        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
85213      }
85214    }
85215    if( chngRowid==0 ){
85216      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
85217    }
85218  }
85219
85220  /* Populate the array of registers beginning at regNew with the new
85221  ** row data. This array is used to check constaints, create the new
85222  ** table and index records, and as the values for any new.* references
85223  ** made by triggers.
85224  **
85225  ** If there are one or more BEFORE triggers, then do not populate the
85226  ** registers associated with columns that are (a) not modified by
85227  ** this UPDATE statement and (b) not accessed by new.* references. The
85228  ** values for registers not modified by the UPDATE must be reloaded from
85229  ** the database after the BEFORE triggers are fired anyway (as the trigger
85230  ** may have modified them). So not loading those that are not going to
85231  ** be used eliminates some redundant opcodes.
85232  */
85233  newmask = sqlite3TriggerColmask(
85234      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
85235  );
85236  for(i=0; i<pTab->nCol; i++){
85237    if( i==pTab->iPKey ){
85238      sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
85239    }else{
85240      j = aXRef[i];
85241      if( j>=0 ){
85242        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
85243      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
85244        /* This branch loads the value of a column that will not be changed
85245        ** into a register. This is done if there are no BEFORE triggers, or
85246        ** if there are one or more BEFORE triggers that use this value via
85247        ** a new.* reference in a trigger program.
85248        */
85249        testcase( i==31 );
85250        testcase( i==32 );
85251        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
85252        sqlite3ColumnDefault(v, pTab, i, regNew+i);
85253      }
85254    }
85255  }
85256
85257  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
85258  ** verified. One could argue that this is wrong.
85259  */
85260  if( tmask&TRIGGER_BEFORE ){
85261    sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
85262    sqlite3TableAffinityStr(v, pTab);
85263    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
85264        TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
85265
85266    /* The row-trigger may have deleted the row being updated. In this
85267    ** case, jump to the next row. No updates or AFTER triggers are
85268    ** required. This behaviour - what happens when the row being updated
85269    ** is deleted or renamed by a BEFORE trigger - is left undefined in the
85270    ** documentation.
85271    */
85272    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
85273
85274    /* If it did not delete it, the row-trigger may still have modified
85275    ** some of the columns of the row being updated. Load the values for
85276    ** all columns not modified by the update statement into their
85277    ** registers in case this has happened.
85278    */
85279    for(i=0; i<pTab->nCol; i++){
85280      if( aXRef[i]<0 && i!=pTab->iPKey ){
85281        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
85282        sqlite3ColumnDefault(v, pTab, i, regNew+i);
85283      }
85284    }
85285  }
85286
85287  if( !isView ){
85288    int j1;                       /* Address of jump instruction */
85289
85290    /* Do constraint checks. */
85291    sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
85292        aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
85293
85294    /* Do FK constraint checks. */
85295    if( hasFK ){
85296      sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
85297    }
85298
85299    /* Delete the index entries associated with the current record.  */
85300    j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
85301    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
85302
85303    /* If changing the record number, delete the old record.  */
85304    if( hasFK || chngRowid ){
85305      sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
85306    }
85307    sqlite3VdbeJumpHere(v, j1);
85308
85309    if( hasFK ){
85310      sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
85311    }
85312
85313    /* Insert the new index entries and the new record. */
85314    sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
85315
85316    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
85317    ** handle rows (possibly in other tables) that refer via a foreign key
85318    ** to the row just updated. */
85319    if( hasFK ){
85320      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
85321    }
85322  }
85323
85324  /* Increment the row counter
85325  */
85326  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
85327    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
85328  }
85329
85330  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
85331      TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
85332
85333  /* Repeat the above with the next record to be updated, until
85334  ** all record selected by the WHERE clause have been updated.
85335  */
85336  sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
85337  sqlite3VdbeJumpHere(v, addr);
85338
85339  /* Close all tables */
85340  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
85341    if( openAll || aRegIdx[i]>0 ){
85342      sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
85343    }
85344  }
85345  sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
85346
85347  /* Update the sqlite_sequence table by storing the content of the
85348  ** maximum rowid counter values recorded while inserting into
85349  ** autoincrement tables.
85350  */
85351  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
85352    sqlite3AutoincrementEnd(pParse);
85353  }
85354
85355  /*
85356  ** Return the number of rows that were changed. If this routine is
85357  ** generating code because of a call to sqlite3NestedParse(), do not
85358  ** invoke the callback function.
85359  */
85360  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
85361    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
85362    sqlite3VdbeSetNumCols(v, 1);
85363    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
85364  }
85365
85366update_cleanup:
85367  sqlite3AuthContextPop(&sContext);
85368  sqlite3DbFree(db, aRegIdx);
85369  sqlite3DbFree(db, aXRef);
85370  sqlite3SrcListDelete(db, pTabList);
85371  sqlite3ExprListDelete(db, pChanges);
85372  sqlite3ExprDelete(db, pWhere);
85373  return;
85374}
85375/* Make sure "isView" and other macros defined above are undefined. Otherwise
85376** thely may interfere with compilation of other functions in this file
85377** (or in another file, if this file becomes part of the amalgamation).  */
85378#ifdef isView
85379 #undef isView
85380#endif
85381#ifdef pTrigger
85382 #undef pTrigger
85383#endif
85384
85385#ifndef SQLITE_OMIT_VIRTUALTABLE
85386/*
85387** Generate code for an UPDATE of a virtual table.
85388**
85389** The strategy is that we create an ephemerial table that contains
85390** for each row to be changed:
85391**
85392**   (A)  The original rowid of that row.
85393**   (B)  The revised rowid for the row. (note1)
85394**   (C)  The content of every column in the row.
85395**
85396** Then we loop over this ephemeral table and for each row in
85397** the ephermeral table call VUpdate.
85398**
85399** When finished, drop the ephemeral table.
85400**
85401** (note1) Actually, if we know in advance that (A) is always the same
85402** as (B) we only store (A), then duplicate (A) when pulling
85403** it out of the ephemeral table before calling VUpdate.
85404*/
85405static void updateVirtualTable(
85406  Parse *pParse,       /* The parsing context */
85407  SrcList *pSrc,       /* The virtual table to be modified */
85408  Table *pTab,         /* The virtual table */
85409  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
85410  Expr *pRowid,        /* Expression used to recompute the rowid */
85411  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
85412  Expr *pWhere         /* WHERE clause of the UPDATE statement */
85413){
85414  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
85415  ExprList *pEList = 0;     /* The result set of the SELECT statement */
85416  Select *pSelect = 0;      /* The SELECT statement */
85417  Expr *pExpr;              /* Temporary expression */
85418  int ephemTab;             /* Table holding the result of the SELECT */
85419  int i;                    /* Loop counter */
85420  int addr;                 /* Address of top of loop */
85421  int iReg;                 /* First register in set passed to OP_VUpdate */
85422  sqlite3 *db = pParse->db; /* Database connection */
85423  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
85424  SelectDest dest;
85425
85426  /* Construct the SELECT statement that will find the new values for
85427  ** all updated rows.
85428  */
85429  pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
85430  if( pRowid ){
85431    pEList = sqlite3ExprListAppend(pParse, pEList,
85432                                   sqlite3ExprDup(db, pRowid, 0));
85433  }
85434  assert( pTab->iPKey<0 );
85435  for(i=0; i<pTab->nCol; i++){
85436    if( aXRef[i]>=0 ){
85437      pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
85438    }else{
85439      pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
85440    }
85441    pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
85442  }
85443  pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
85444
85445  /* Create the ephemeral table into which the update results will
85446  ** be stored.
85447  */
85448  assert( v );
85449  ephemTab = pParse->nTab++;
85450  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
85451
85452  /* fill the ephemeral table
85453  */
85454  sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
85455  sqlite3Select(pParse, pSelect, &dest);
85456
85457  /* Generate code to scan the ephemeral table and call VUpdate. */
85458  iReg = ++pParse->nMem;
85459  pParse->nMem += pTab->nCol+1;
85460  addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
85461  sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
85462  sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
85463  for(i=0; i<pTab->nCol; i++){
85464    sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
85465  }
85466  sqlite3VtabMakeWritable(pParse, pTab);
85467  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
85468  sqlite3MayAbort(pParse);
85469  sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
85470  sqlite3VdbeJumpHere(v, addr);
85471  sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
85472
85473  /* Cleanup */
85474  sqlite3SelectDelete(db, pSelect);
85475}
85476#endif /* SQLITE_OMIT_VIRTUALTABLE */
85477
85478/************** End of update.c **********************************************/
85479/************** Begin file vacuum.c ******************************************/
85480/*
85481** 2003 April 6
85482**
85483** The author disclaims copyright to this source code.  In place of
85484** a legal notice, here is a blessing:
85485**
85486**    May you do good and not evil.
85487**    May you find forgiveness for yourself and forgive others.
85488**    May you share freely, never taking more than you give.
85489**
85490*************************************************************************
85491** This file contains code used to implement the VACUUM command.
85492**
85493** Most of the code in this file may be omitted by defining the
85494** SQLITE_OMIT_VACUUM macro.
85495*/
85496
85497#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
85498/*
85499** Finalize a prepared statement.  If there was an error, store the
85500** text of the error message in *pzErrMsg.  Return the result code.
85501*/
85502static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
85503  int rc;
85504  rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
85505  if( rc ){
85506    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
85507  }
85508  return rc;
85509}
85510
85511/*
85512** Execute zSql on database db. Return an error code.
85513*/
85514static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
85515  sqlite3_stmt *pStmt;
85516  VVA_ONLY( int rc; )
85517  if( !zSql ){
85518    return SQLITE_NOMEM;
85519  }
85520  if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
85521    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
85522    return sqlite3_errcode(db);
85523  }
85524  VVA_ONLY( rc = ) sqlite3_step(pStmt);
85525  assert( rc!=SQLITE_ROW );
85526  return vacuumFinalize(db, pStmt, pzErrMsg);
85527}
85528
85529/*
85530** Execute zSql on database db. The statement returns exactly
85531** one column. Execute this as SQL on the same database.
85532*/
85533static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
85534  sqlite3_stmt *pStmt;
85535  int rc;
85536
85537  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
85538  if( rc!=SQLITE_OK ) return rc;
85539
85540  while( SQLITE_ROW==sqlite3_step(pStmt) ){
85541    rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
85542    if( rc!=SQLITE_OK ){
85543      vacuumFinalize(db, pStmt, pzErrMsg);
85544      return rc;
85545    }
85546  }
85547
85548  return vacuumFinalize(db, pStmt, pzErrMsg);
85549}
85550
85551/*
85552** The non-standard VACUUM command is used to clean up the database,
85553** collapse free space, etc.  It is modelled after the VACUUM command
85554** in PostgreSQL.
85555**
85556** In version 1.0.x of SQLite, the VACUUM command would call
85557** gdbm_reorganize() on all the database tables.  But beginning
85558** with 2.0.0, SQLite no longer uses GDBM so this command has
85559** become a no-op.
85560*/
85561SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
85562  Vdbe *v = sqlite3GetVdbe(pParse);
85563  if( v ){
85564    sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
85565  }
85566  return;
85567}
85568
85569/*
85570** This routine implements the OP_Vacuum opcode of the VDBE.
85571*/
85572SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
85573  int rc = SQLITE_OK;     /* Return code from service routines */
85574  Btree *pMain;           /* The database being vacuumed */
85575  Btree *pTemp;           /* The temporary database we vacuum into */
85576  char *zSql = 0;         /* SQL statements */
85577  int saved_flags;        /* Saved value of the db->flags */
85578  int saved_nChange;      /* Saved value of db->nChange */
85579  int saved_nTotalChange; /* Saved value of db->nTotalChange */
85580  void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
85581  Db *pDb = 0;            /* Database to detach at end of vacuum */
85582  int isMemDb;            /* True if vacuuming a :memory: database */
85583  int nRes;
85584
85585  if( !db->autoCommit ){
85586    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
85587    return SQLITE_ERROR;
85588  }
85589
85590  /* Save the current value of the database flags so that it can be
85591  ** restored before returning. Then set the writable-schema flag, and
85592  ** disable CHECK and foreign key constraints.  */
85593  saved_flags = db->flags;
85594  saved_nChange = db->nChange;
85595  saved_nTotalChange = db->nTotalChange;
85596  saved_xTrace = db->xTrace;
85597  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
85598  db->flags &= ~SQLITE_ForeignKeys;
85599  db->xTrace = 0;
85600
85601  pMain = db->aDb[0].pBt;
85602  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
85603
85604  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
85605  ** can be set to 'off' for this file, as it is not recovered if a crash
85606  ** occurs anyway. The integrity of the database is maintained by a
85607  ** (possibly synchronous) transaction opened on the main database before
85608  ** sqlite3BtreeCopyFile() is called.
85609  **
85610  ** An optimisation would be to use a non-journaled pager.
85611  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
85612  ** that actually made the VACUUM run slower.  Very little journalling
85613  ** actually occurs when doing a vacuum since the vacuum_db is initially
85614  ** empty.  Only the journal header is written.  Apparently it takes more
85615  ** time to parse and run the PRAGMA to turn journalling off than it does
85616  ** to write the journal header file.
85617  */
85618  if( sqlite3TempInMemory(db) ){
85619    zSql = "ATTACH ':memory:' AS vacuum_db;";
85620  }else{
85621    zSql = "ATTACH '' AS vacuum_db;";
85622  }
85623  rc = execSql(db, pzErrMsg, zSql);
85624  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85625  pDb = &db->aDb[db->nDb-1];
85626  assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
85627  pTemp = db->aDb[db->nDb-1].pBt;
85628
85629  /* The call to execSql() to attach the temp database has left the file
85630  ** locked (as there was more than one active statement when the transaction
85631  ** to read the schema was concluded. Unlock it here so that this doesn't
85632  ** cause problems for the call to BtreeSetPageSize() below.  */
85633  sqlite3BtreeCommit(pTemp);
85634
85635  nRes = sqlite3BtreeGetReserve(pMain);
85636
85637  /* A VACUUM cannot change the pagesize of an encrypted database. */
85638#ifdef SQLITE_HAS_CODEC
85639  if( db->nextPagesize ){
85640    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
85641    int nKey;
85642    char *zKey;
85643    sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
85644    if( nKey ) db->nextPagesize = 0;
85645  }
85646#endif
85647
85648  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
85649   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
85650   || NEVER(db->mallocFailed)
85651  ){
85652    rc = SQLITE_NOMEM;
85653    goto end_of_vacuum;
85654  }
85655  rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
85656  if( rc!=SQLITE_OK ){
85657    goto end_of_vacuum;
85658  }
85659
85660#ifndef SQLITE_OMIT_AUTOVACUUM
85661  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
85662                                           sqlite3BtreeGetAutoVacuum(pMain));
85663#endif
85664
85665  /* Begin a transaction */
85666  rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
85667  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85668
85669  /* Query the schema of the main database. Create a mirror schema
85670  ** in the temporary database.
85671  */
85672  rc = execExecSql(db, pzErrMsg,
85673      "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
85674      "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
85675      "   AND rootpage>0"
85676  );
85677  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85678  rc = execExecSql(db, pzErrMsg,
85679      "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
85680      "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
85681  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85682  rc = execExecSql(db, pzErrMsg,
85683      "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
85684      "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
85685  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85686
85687  /* Loop through the tables in the main database. For each, do
85688  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
85689  ** the contents to the temporary database.
85690  */
85691  rc = execExecSql(db, pzErrMsg,
85692      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
85693      "|| ' SELECT * FROM main.' || quote(name) || ';'"
85694      "FROM main.sqlite_master "
85695      "WHERE type = 'table' AND name!='sqlite_sequence' "
85696      "  AND rootpage>0"
85697  );
85698  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85699
85700  /* Copy over the sequence table
85701  */
85702  rc = execExecSql(db, pzErrMsg,
85703      "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
85704      "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
85705  );
85706  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85707  rc = execExecSql(db, pzErrMsg,
85708      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
85709      "|| ' SELECT * FROM main.' || quote(name) || ';' "
85710      "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
85711  );
85712  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85713
85714
85715  /* Copy the triggers, views, and virtual tables from the main database
85716  ** over to the temporary database.  None of these objects has any
85717  ** associated storage, so all we have to do is copy their entries
85718  ** from the SQLITE_MASTER table.
85719  */
85720  rc = execSql(db, pzErrMsg,
85721      "INSERT INTO vacuum_db.sqlite_master "
85722      "  SELECT type, name, tbl_name, rootpage, sql"
85723      "    FROM main.sqlite_master"
85724      "   WHERE type='view' OR type='trigger'"
85725      "      OR (type='table' AND rootpage=0)"
85726  );
85727  if( rc ) goto end_of_vacuum;
85728
85729  /* At this point, unless the main db was completely empty, there is now a
85730  ** transaction open on the vacuum database, but not on the main database.
85731  ** Open a btree level transaction on the main database. This allows a
85732  ** call to sqlite3BtreeCopyFile(). The main database btree level
85733  ** transaction is then committed, so the SQL level never knows it was
85734  ** opened for writing. This way, the SQL transaction used to create the
85735  ** temporary database never needs to be committed.
85736  */
85737  {
85738    u32 meta;
85739    int i;
85740
85741    /* This array determines which meta meta values are preserved in the
85742    ** vacuum.  Even entries are the meta value number and odd entries
85743    ** are an increment to apply to the meta value after the vacuum.
85744    ** The increment is used to increase the schema cookie so that other
85745    ** connections to the same database will know to reread the schema.
85746    */
85747    static const unsigned char aCopy[] = {
85748       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
85749       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
85750       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
85751       BTREE_USER_VERSION,       0,  /* Preserve the user version */
85752    };
85753
85754    assert( 1==sqlite3BtreeIsInTrans(pTemp) );
85755    assert( 1==sqlite3BtreeIsInTrans(pMain) );
85756
85757    /* Copy Btree meta values */
85758    for(i=0; i<ArraySize(aCopy); i+=2){
85759      /* GetMeta() and UpdateMeta() cannot fail in this context because
85760      ** we already have page 1 loaded into cache and marked dirty. */
85761      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
85762      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
85763      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
85764    }
85765
85766    rc = sqlite3BtreeCopyFile(pMain, pTemp);
85767    if( rc!=SQLITE_OK ) goto end_of_vacuum;
85768    rc = sqlite3BtreeCommit(pTemp);
85769    if( rc!=SQLITE_OK ) goto end_of_vacuum;
85770#ifndef SQLITE_OMIT_AUTOVACUUM
85771    sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
85772#endif
85773  }
85774
85775  assert( rc==SQLITE_OK );
85776  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
85777
85778end_of_vacuum:
85779  /* Restore the original value of db->flags */
85780  db->flags = saved_flags;
85781  db->nChange = saved_nChange;
85782  db->nTotalChange = saved_nTotalChange;
85783  db->xTrace = saved_xTrace;
85784
85785  /* Currently there is an SQL level transaction open on the vacuum
85786  ** database. No locks are held on any other files (since the main file
85787  ** was committed at the btree level). So it safe to end the transaction
85788  ** by manually setting the autoCommit flag to true and detaching the
85789  ** vacuum database. The vacuum_db journal file is deleted when the pager
85790  ** is closed by the DETACH.
85791  */
85792  db->autoCommit = 1;
85793
85794  if( pDb ){
85795    sqlite3BtreeClose(pDb->pBt);
85796    pDb->pBt = 0;
85797    pDb->pSchema = 0;
85798  }
85799
85800  sqlite3ResetInternalSchema(db, 0);
85801
85802  return rc;
85803}
85804#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
85805
85806/************** End of vacuum.c **********************************************/
85807/************** Begin file vtab.c ********************************************/
85808/*
85809** 2006 June 10
85810**
85811** The author disclaims copyright to this source code.  In place of
85812** a legal notice, here is a blessing:
85813**
85814**    May you do good and not evil.
85815**    May you find forgiveness for yourself and forgive others.
85816**    May you share freely, never taking more than you give.
85817**
85818*************************************************************************
85819** This file contains code used to help implement virtual tables.
85820*/
85821#ifndef SQLITE_OMIT_VIRTUALTABLE
85822
85823/*
85824** The actual function that does the work of creating a new module.
85825** This function implements the sqlite3_create_module() and
85826** sqlite3_create_module_v2() interfaces.
85827*/
85828static int createModule(
85829  sqlite3 *db,                    /* Database in which module is registered */
85830  const char *zName,              /* Name assigned to this module */
85831  const sqlite3_module *pModule,  /* The definition of the module */
85832  void *pAux,                     /* Context pointer for xCreate/xConnect */
85833  void (*xDestroy)(void *)        /* Module destructor function */
85834){
85835  int rc, nName;
85836  Module *pMod;
85837
85838  sqlite3_mutex_enter(db->mutex);
85839  nName = sqlite3Strlen30(zName);
85840  pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
85841  if( pMod ){
85842    Module *pDel;
85843    char *zCopy = (char *)(&pMod[1]);
85844    memcpy(zCopy, zName, nName+1);
85845    pMod->zName = zCopy;
85846    pMod->pModule = pModule;
85847    pMod->pAux = pAux;
85848    pMod->xDestroy = xDestroy;
85849    pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
85850    if( pDel && pDel->xDestroy ){
85851      pDel->xDestroy(pDel->pAux);
85852    }
85853    sqlite3DbFree(db, pDel);
85854    if( pDel==pMod ){
85855      db->mallocFailed = 1;
85856    }
85857    sqlite3ResetInternalSchema(db, 0);
85858  }else if( xDestroy ){
85859    xDestroy(pAux);
85860  }
85861  rc = sqlite3ApiExit(db, SQLITE_OK);
85862  sqlite3_mutex_leave(db->mutex);
85863  return rc;
85864}
85865
85866
85867/*
85868** External API function used to create a new virtual-table module.
85869*/
85870SQLITE_API int sqlite3_create_module(
85871  sqlite3 *db,                    /* Database in which module is registered */
85872  const char *zName,              /* Name assigned to this module */
85873  const sqlite3_module *pModule,  /* The definition of the module */
85874  void *pAux                      /* Context pointer for xCreate/xConnect */
85875){
85876  return createModule(db, zName, pModule, pAux, 0);
85877}
85878
85879/*
85880** External API function used to create a new virtual-table module.
85881*/
85882SQLITE_API int sqlite3_create_module_v2(
85883  sqlite3 *db,                    /* Database in which module is registered */
85884  const char *zName,              /* Name assigned to this module */
85885  const sqlite3_module *pModule,  /* The definition of the module */
85886  void *pAux,                     /* Context pointer for xCreate/xConnect */
85887  void (*xDestroy)(void *)        /* Module destructor function */
85888){
85889  return createModule(db, zName, pModule, pAux, xDestroy);
85890}
85891
85892/*
85893** Lock the virtual table so that it cannot be disconnected.
85894** Locks nest.  Every lock should have a corresponding unlock.
85895** If an unlock is omitted, resources leaks will occur.
85896**
85897** If a disconnect is attempted while a virtual table is locked,
85898** the disconnect is deferred until all locks have been removed.
85899*/
85900SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
85901  pVTab->nRef++;
85902}
85903
85904
85905/*
85906** pTab is a pointer to a Table structure representing a virtual-table.
85907** Return a pointer to the VTable object used by connection db to access
85908** this virtual-table, if one has been created, or NULL otherwise.
85909*/
85910SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
85911  VTable *pVtab;
85912  assert( IsVirtual(pTab) );
85913  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
85914  return pVtab;
85915}
85916
85917/*
85918** Decrement the ref-count on a virtual table object. When the ref-count
85919** reaches zero, call the xDisconnect() method to delete the object.
85920*/
85921SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
85922  sqlite3 *db = pVTab->db;
85923
85924  assert( db );
85925  assert( pVTab->nRef>0 );
85926  assert( sqlite3SafetyCheckOk(db) );
85927
85928  pVTab->nRef--;
85929  if( pVTab->nRef==0 ){
85930    sqlite3_vtab *p = pVTab->pVtab;
85931    if( p ){
85932      p->pModule->xDisconnect(p);
85933    }
85934    sqlite3DbFree(db, pVTab);
85935  }
85936}
85937
85938/*
85939** Table p is a virtual table. This function moves all elements in the
85940** p->pVTable list to the sqlite3.pDisconnect lists of their associated
85941** database connections to be disconnected at the next opportunity.
85942** Except, if argument db is not NULL, then the entry associated with
85943** connection db is left in the p->pVTable list.
85944*/
85945static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
85946  VTable *pRet = 0;
85947  VTable *pVTable = p->pVTable;
85948  p->pVTable = 0;
85949
85950  /* Assert that the mutex (if any) associated with the BtShared database
85951  ** that contains table p is held by the caller. See header comments
85952  ** above function sqlite3VtabUnlockList() for an explanation of why
85953  ** this makes it safe to access the sqlite3.pDisconnect list of any
85954  ** database connection that may have an entry in the p->pVTable list.  */
85955  assert( db==0 ||
85956    sqlite3BtreeHoldsMutex(db->aDb[sqlite3SchemaToIndex(db, p->pSchema)].pBt)
85957  );
85958
85959  while( pVTable ){
85960    sqlite3 *db2 = pVTable->db;
85961    VTable *pNext = pVTable->pNext;
85962    assert( db2 );
85963    if( db2==db ){
85964      pRet = pVTable;
85965      p->pVTable = pRet;
85966      pRet->pNext = 0;
85967    }else{
85968      pVTable->pNext = db2->pDisconnect;
85969      db2->pDisconnect = pVTable;
85970    }
85971    pVTable = pNext;
85972  }
85973
85974  assert( !db || pRet );
85975  return pRet;
85976}
85977
85978
85979/*
85980** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
85981**
85982** This function may only be called when the mutexes associated with all
85983** shared b-tree databases opened using connection db are held by the
85984** caller. This is done to protect the sqlite3.pDisconnect list. The
85985** sqlite3.pDisconnect list is accessed only as follows:
85986**
85987**   1) By this function. In this case, all BtShared mutexes and the mutex
85988**      associated with the database handle itself must be held.
85989**
85990**   2) By function vtabDisconnectAll(), when it adds a VTable entry to
85991**      the sqlite3.pDisconnect list. In this case either the BtShared mutex
85992**      associated with the database the virtual table is stored in is held
85993**      or, if the virtual table is stored in a non-sharable database, then
85994**      the database handle mutex is held.
85995**
85996** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
85997** by multiple threads. It is thread-safe.
85998*/
85999SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
86000  VTable *p = db->pDisconnect;
86001  db->pDisconnect = 0;
86002
86003  assert( sqlite3BtreeHoldsAllMutexes(db) );
86004  assert( sqlite3_mutex_held(db->mutex) );
86005
86006  if( p ){
86007    sqlite3ExpirePreparedStatements(db);
86008    do {
86009      VTable *pNext = p->pNext;
86010      sqlite3VtabUnlock(p);
86011      p = pNext;
86012    }while( p );
86013  }
86014}
86015
86016/*
86017** Clear any and all virtual-table information from the Table record.
86018** This routine is called, for example, just before deleting the Table
86019** record.
86020**
86021** Since it is a virtual-table, the Table structure contains a pointer
86022** to the head of a linked list of VTable structures. Each VTable
86023** structure is associated with a single sqlite3* user of the schema.
86024** The reference count of the VTable structure associated with database
86025** connection db is decremented immediately (which may lead to the
86026** structure being xDisconnected and free). Any other VTable structures
86027** in the list are moved to the sqlite3.pDisconnect list of the associated
86028** database connection.
86029*/
86030SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
86031  vtabDisconnectAll(0, p);
86032  if( p->azModuleArg ){
86033    int i;
86034    for(i=0; i<p->nModuleArg; i++){
86035      sqlite3DbFree(p->dbMem, p->azModuleArg[i]);
86036    }
86037    sqlite3DbFree(p->dbMem, p->azModuleArg);
86038  }
86039}
86040
86041/*
86042** Add a new module argument to pTable->azModuleArg[].
86043** The string is not copied - the pointer is stored.  The
86044** string will be freed automatically when the table is
86045** deleted.
86046*/
86047static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
86048  int i = pTable->nModuleArg++;
86049  int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
86050  char **azModuleArg;
86051  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
86052  if( azModuleArg==0 ){
86053    int j;
86054    for(j=0; j<i; j++){
86055      sqlite3DbFree(db, pTable->azModuleArg[j]);
86056    }
86057    sqlite3DbFree(db, zArg);
86058    sqlite3DbFree(db, pTable->azModuleArg);
86059    pTable->nModuleArg = 0;
86060  }else{
86061    azModuleArg[i] = zArg;
86062    azModuleArg[i+1] = 0;
86063  }
86064  pTable->azModuleArg = azModuleArg;
86065}
86066
86067/*
86068** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
86069** statement.  The module name has been parsed, but the optional list
86070** of parameters that follow the module name are still pending.
86071*/
86072SQLITE_PRIVATE void sqlite3VtabBeginParse(
86073  Parse *pParse,        /* Parsing context */
86074  Token *pName1,        /* Name of new table, or database name */
86075  Token *pName2,        /* Name of new table or NULL */
86076  Token *pModuleName    /* Name of the module for the virtual table */
86077){
86078  int iDb;              /* The database the table is being created in */
86079  Table *pTable;        /* The new virtual table */
86080  sqlite3 *db;          /* Database connection */
86081
86082  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
86083  pTable = pParse->pNewTable;
86084  if( pTable==0 ) return;
86085  assert( 0==pTable->pIndex );
86086
86087  db = pParse->db;
86088  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
86089  assert( iDb>=0 );
86090
86091  pTable->tabFlags |= TF_Virtual;
86092  pTable->nModuleArg = 0;
86093  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
86094  addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
86095  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
86096  pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
86097
86098#ifndef SQLITE_OMIT_AUTHORIZATION
86099  /* Creating a virtual table invokes the authorization callback twice.
86100  ** The first invocation, to obtain permission to INSERT a row into the
86101  ** sqlite_master table, has already been made by sqlite3StartTable().
86102  ** The second call, to obtain permission to create the table, is made now.
86103  */
86104  if( pTable->azModuleArg ){
86105    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
86106            pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
86107  }
86108#endif
86109}
86110
86111/*
86112** This routine takes the module argument that has been accumulating
86113** in pParse->zArg[] and appends it to the list of arguments on the
86114** virtual table currently under construction in pParse->pTable.
86115*/
86116static void addArgumentToVtab(Parse *pParse){
86117  if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
86118    const char *z = (const char*)pParse->sArg.z;
86119    int n = pParse->sArg.n;
86120    sqlite3 *db = pParse->db;
86121    addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
86122  }
86123}
86124
86125/*
86126** The parser calls this routine after the CREATE VIRTUAL TABLE statement
86127** has been completely parsed.
86128*/
86129SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
86130  Table *pTab = pParse->pNewTable;  /* The table being constructed */
86131  sqlite3 *db = pParse->db;         /* The database connection */
86132
86133  if( pTab==0 ) return;
86134  addArgumentToVtab(pParse);
86135  pParse->sArg.z = 0;
86136  if( pTab->nModuleArg<1 ) return;
86137
86138  /* If the CREATE VIRTUAL TABLE statement is being entered for the
86139  ** first time (in other words if the virtual table is actually being
86140  ** created now instead of just being read out of sqlite_master) then
86141  ** do additional initialization work and store the statement text
86142  ** in the sqlite_master table.
86143  */
86144  if( !db->init.busy ){
86145    char *zStmt;
86146    char *zWhere;
86147    int iDb;
86148    Vdbe *v;
86149
86150    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
86151    if( pEnd ){
86152      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
86153    }
86154    zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
86155
86156    /* A slot for the record has already been allocated in the
86157    ** SQLITE_MASTER table.  We just need to update that slot with all
86158    ** the information we've collected.
86159    **
86160    ** The VM register number pParse->regRowid holds the rowid of an
86161    ** entry in the sqlite_master table tht was created for this vtab
86162    ** by sqlite3StartTable().
86163    */
86164    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
86165    sqlite3NestedParse(pParse,
86166      "UPDATE %Q.%s "
86167         "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
86168       "WHERE rowid=#%d",
86169      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
86170      pTab->zName,
86171      pTab->zName,
86172      zStmt,
86173      pParse->regRowid
86174    );
86175    sqlite3DbFree(db, zStmt);
86176    v = sqlite3GetVdbe(pParse);
86177    sqlite3ChangeCookie(pParse, iDb);
86178
86179    sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
86180    zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
86181    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
86182    sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
86183                         pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
86184  }
86185
86186  /* If we are rereading the sqlite_master table create the in-memory
86187  ** record of the table. The xConnect() method is not called until
86188  ** the first time the virtual table is used in an SQL statement. This
86189  ** allows a schema that contains virtual tables to be loaded before
86190  ** the required virtual table implementations are registered.  */
86191  else {
86192    Table *pOld;
86193    Schema *pSchema = pTab->pSchema;
86194    const char *zName = pTab->zName;
86195    int nName = sqlite3Strlen30(zName);
86196    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
86197    if( pOld ){
86198      db->mallocFailed = 1;
86199      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
86200      return;
86201    }
86202    pSchema->db = pParse->db;
86203    pParse->pNewTable = 0;
86204  }
86205}
86206
86207/*
86208** The parser calls this routine when it sees the first token
86209** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
86210*/
86211SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
86212  addArgumentToVtab(pParse);
86213  pParse->sArg.z = 0;
86214  pParse->sArg.n = 0;
86215}
86216
86217/*
86218** The parser calls this routine for each token after the first token
86219** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
86220*/
86221SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
86222  Token *pArg = &pParse->sArg;
86223  if( pArg->z==0 ){
86224    pArg->z = p->z;
86225    pArg->n = p->n;
86226  }else{
86227    assert(pArg->z < p->z);
86228    pArg->n = (int)(&p->z[p->n] - pArg->z);
86229  }
86230}
86231
86232/*
86233** Invoke a virtual table constructor (either xCreate or xConnect). The
86234** pointer to the function to invoke is passed as the fourth parameter
86235** to this procedure.
86236*/
86237static int vtabCallConstructor(
86238  sqlite3 *db,
86239  Table *pTab,
86240  Module *pMod,
86241  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
86242  char **pzErr
86243){
86244  VTable *pVTable;
86245  int rc;
86246  const char *const*azArg = (const char *const*)pTab->azModuleArg;
86247  int nArg = pTab->nModuleArg;
86248  char *zErr = 0;
86249  char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
86250
86251  if( !zModuleName ){
86252    return SQLITE_NOMEM;
86253  }
86254
86255  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
86256  if( !pVTable ){
86257    sqlite3DbFree(db, zModuleName);
86258    return SQLITE_NOMEM;
86259  }
86260  pVTable->db = db;
86261  pVTable->pMod = pMod;
86262
86263  assert( !db->pVTab );
86264  assert( xConstruct );
86265  db->pVTab = pTab;
86266
86267  /* Invoke the virtual table constructor */
86268  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
86269  if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
86270
86271  if( SQLITE_OK!=rc ){
86272    if( zErr==0 ){
86273      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
86274    }else {
86275      *pzErr = sqlite3MPrintf(db, "%s", zErr);
86276      sqlite3DbFree(db, zErr);
86277    }
86278    sqlite3DbFree(db, pVTable);
86279  }else if( ALWAYS(pVTable->pVtab) ){
86280    /* Justification of ALWAYS():  A correct vtab constructor must allocate
86281    ** the sqlite3_vtab object if successful.  */
86282    pVTable->pVtab->pModule = pMod->pModule;
86283    pVTable->nRef = 1;
86284    if( db->pVTab ){
86285      const char *zFormat = "vtable constructor did not declare schema: %s";
86286      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
86287      sqlite3VtabUnlock(pVTable);
86288      rc = SQLITE_ERROR;
86289    }else{
86290      int iCol;
86291      /* If everything went according to plan, link the new VTable structure
86292      ** into the linked list headed by pTab->pVTable. Then loop through the
86293      ** columns of the table to see if any of them contain the token "hidden".
86294      ** If so, set the Column.isHidden flag and remove the token from
86295      ** the type string.  */
86296      pVTable->pNext = pTab->pVTable;
86297      pTab->pVTable = pVTable;
86298
86299      for(iCol=0; iCol<pTab->nCol; iCol++){
86300        char *zType = pTab->aCol[iCol].zType;
86301        int nType;
86302        int i = 0;
86303        if( !zType ) continue;
86304        nType = sqlite3Strlen30(zType);
86305        if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
86306          for(i=0; i<nType; i++){
86307            if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
86308             && (zType[i+7]=='\0' || zType[i+7]==' ')
86309            ){
86310              i++;
86311              break;
86312            }
86313          }
86314        }
86315        if( i<nType ){
86316          int j;
86317          int nDel = 6 + (zType[i+6] ? 1 : 0);
86318          for(j=i; (j+nDel)<=nType; j++){
86319            zType[j] = zType[j+nDel];
86320          }
86321          if( zType[i]=='\0' && i>0 ){
86322            assert(zType[i-1]==' ');
86323            zType[i-1] = '\0';
86324          }
86325          pTab->aCol[iCol].isHidden = 1;
86326        }
86327      }
86328    }
86329  }
86330
86331  sqlite3DbFree(db, zModuleName);
86332  db->pVTab = 0;
86333  return rc;
86334}
86335
86336/*
86337** This function is invoked by the parser to call the xConnect() method
86338** of the virtual table pTab. If an error occurs, an error code is returned
86339** and an error left in pParse.
86340**
86341** This call is a no-op if table pTab is not a virtual table.
86342*/
86343SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
86344  sqlite3 *db = pParse->db;
86345  const char *zMod;
86346  Module *pMod;
86347  int rc;
86348
86349  assert( pTab );
86350  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
86351    return SQLITE_OK;
86352  }
86353
86354  /* Locate the required virtual table module */
86355  zMod = pTab->azModuleArg[0];
86356  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
86357
86358  if( !pMod ){
86359    const char *zModule = pTab->azModuleArg[0];
86360    sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
86361    rc = SQLITE_ERROR;
86362  }else{
86363    char *zErr = 0;
86364    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
86365    if( rc!=SQLITE_OK ){
86366      sqlite3ErrorMsg(pParse, "%s", zErr);
86367    }
86368    sqlite3DbFree(db, zErr);
86369  }
86370
86371  return rc;
86372}
86373
86374/*
86375** Add the virtual table pVTab to the array sqlite3.aVTrans[].
86376*/
86377static int addToVTrans(sqlite3 *db, VTable *pVTab){
86378  const int ARRAY_INCR = 5;
86379
86380  /* Grow the sqlite3.aVTrans array if required */
86381  if( (db->nVTrans%ARRAY_INCR)==0 ){
86382    VTable **aVTrans;
86383    int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
86384    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
86385    if( !aVTrans ){
86386      return SQLITE_NOMEM;
86387    }
86388    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
86389    db->aVTrans = aVTrans;
86390  }
86391
86392  /* Add pVtab to the end of sqlite3.aVTrans */
86393  db->aVTrans[db->nVTrans++] = pVTab;
86394  sqlite3VtabLock(pVTab);
86395  return SQLITE_OK;
86396}
86397
86398/*
86399** This function is invoked by the vdbe to call the xCreate method
86400** of the virtual table named zTab in database iDb.
86401**
86402** If an error occurs, *pzErr is set to point an an English language
86403** description of the error and an SQLITE_XXX error code is returned.
86404** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
86405*/
86406SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
86407  int rc = SQLITE_OK;
86408  Table *pTab;
86409  Module *pMod;
86410  const char *zMod;
86411
86412  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
86413  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
86414
86415  /* Locate the required virtual table module */
86416  zMod = pTab->azModuleArg[0];
86417  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
86418
86419  /* If the module has been registered and includes a Create method,
86420  ** invoke it now. If the module has not been registered, return an
86421  ** error. Otherwise, do nothing.
86422  */
86423  if( !pMod ){
86424    *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
86425    rc = SQLITE_ERROR;
86426  }else{
86427    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
86428  }
86429
86430  /* Justification of ALWAYS():  The xConstructor method is required to
86431  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
86432  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
86433      rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
86434  }
86435
86436  return rc;
86437}
86438
86439/*
86440** This function is used to set the schema of a virtual table.  It is only
86441** valid to call this function from within the xCreate() or xConnect() of a
86442** virtual table module.
86443*/
86444SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
86445  Parse *pParse;
86446
86447  int rc = SQLITE_OK;
86448  Table *pTab;
86449  char *zErr = 0;
86450
86451  sqlite3_mutex_enter(db->mutex);
86452  pTab = db->pVTab;
86453  if( !pTab ){
86454    sqlite3Error(db, SQLITE_MISUSE, 0);
86455    sqlite3_mutex_leave(db->mutex);
86456    return SQLITE_MISUSE_BKPT;
86457  }
86458  assert( (pTab->tabFlags & TF_Virtual)!=0 );
86459
86460  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
86461  if( pParse==0 ){
86462    rc = SQLITE_NOMEM;
86463  }else{
86464    pParse->declareVtab = 1;
86465    pParse->db = db;
86466
86467    if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
86468     && pParse->pNewTable
86469     && !db->mallocFailed
86470     && !pParse->pNewTable->pSelect
86471     && (pParse->pNewTable->tabFlags & TF_Virtual)==0
86472    ){
86473      if( !pTab->aCol ){
86474        pTab->aCol = pParse->pNewTable->aCol;
86475        pTab->nCol = pParse->pNewTable->nCol;
86476        pParse->pNewTable->nCol = 0;
86477        pParse->pNewTable->aCol = 0;
86478      }
86479      db->pVTab = 0;
86480    }else{
86481      sqlite3Error(db, SQLITE_ERROR, zErr);
86482      sqlite3DbFree(db, zErr);
86483      rc = SQLITE_ERROR;
86484    }
86485    pParse->declareVtab = 0;
86486
86487    if( pParse->pVdbe ){
86488      sqlite3VdbeFinalize(pParse->pVdbe);
86489    }
86490    sqlite3DeleteTable(pParse->pNewTable);
86491    sqlite3StackFree(db, pParse);
86492  }
86493
86494  assert( (rc&0xff)==rc );
86495  rc = sqlite3ApiExit(db, rc);
86496  sqlite3_mutex_leave(db->mutex);
86497  return rc;
86498}
86499
86500/*
86501** This function is invoked by the vdbe to call the xDestroy method
86502** of the virtual table named zTab in database iDb. This occurs
86503** when a DROP TABLE is mentioned.
86504**
86505** This call is a no-op if zTab is not a virtual table.
86506*/
86507SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
86508  int rc = SQLITE_OK;
86509  Table *pTab;
86510
86511  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
86512  if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
86513    VTable *p = vtabDisconnectAll(db, pTab);
86514
86515    assert( rc==SQLITE_OK );
86516    rc = p->pMod->pModule->xDestroy(p->pVtab);
86517
86518    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
86519    if( rc==SQLITE_OK ){
86520      assert( pTab->pVTable==p && p->pNext==0 );
86521      p->pVtab = 0;
86522      pTab->pVTable = 0;
86523      sqlite3VtabUnlock(p);
86524    }
86525  }
86526
86527  return rc;
86528}
86529
86530/*
86531** This function invokes either the xRollback or xCommit method
86532** of each of the virtual tables in the sqlite3.aVTrans array. The method
86533** called is identified by the second argument, "offset", which is
86534** the offset of the method to call in the sqlite3_module structure.
86535**
86536** The array is cleared after invoking the callbacks.
86537*/
86538static void callFinaliser(sqlite3 *db, int offset){
86539  int i;
86540  if( db->aVTrans ){
86541    for(i=0; i<db->nVTrans; i++){
86542      VTable *pVTab = db->aVTrans[i];
86543      sqlite3_vtab *p = pVTab->pVtab;
86544      if( p ){
86545        int (*x)(sqlite3_vtab *);
86546        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
86547        if( x ) x(p);
86548      }
86549      sqlite3VtabUnlock(pVTab);
86550    }
86551    sqlite3DbFree(db, db->aVTrans);
86552    db->nVTrans = 0;
86553    db->aVTrans = 0;
86554  }
86555}
86556
86557/*
86558** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
86559** array. Return the error code for the first error that occurs, or
86560** SQLITE_OK if all xSync operations are successful.
86561**
86562** Set *pzErrmsg to point to a buffer that should be released using
86563** sqlite3DbFree() containing an error message, if one is available.
86564*/
86565SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
86566  int i;
86567  int rc = SQLITE_OK;
86568  VTable **aVTrans = db->aVTrans;
86569
86570  db->aVTrans = 0;
86571  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
86572    int (*x)(sqlite3_vtab *);
86573    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
86574    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
86575      rc = x(pVtab);
86576      sqlite3DbFree(db, *pzErrmsg);
86577      *pzErrmsg = pVtab->zErrMsg;
86578      pVtab->zErrMsg = 0;
86579    }
86580  }
86581  db->aVTrans = aVTrans;
86582  return rc;
86583}
86584
86585/*
86586** Invoke the xRollback method of all virtual tables in the
86587** sqlite3.aVTrans array. Then clear the array itself.
86588*/
86589SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
86590  callFinaliser(db, offsetof(sqlite3_module,xRollback));
86591  return SQLITE_OK;
86592}
86593
86594/*
86595** Invoke the xCommit method of all virtual tables in the
86596** sqlite3.aVTrans array. Then clear the array itself.
86597*/
86598SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
86599  callFinaliser(db, offsetof(sqlite3_module,xCommit));
86600  return SQLITE_OK;
86601}
86602
86603/*
86604** If the virtual table pVtab supports the transaction interface
86605** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
86606** not currently open, invoke the xBegin method now.
86607**
86608** If the xBegin call is successful, place the sqlite3_vtab pointer
86609** in the sqlite3.aVTrans array.
86610*/
86611SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
86612  int rc = SQLITE_OK;
86613  const sqlite3_module *pModule;
86614
86615  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
86616  ** than zero, then this function is being called from within a
86617  ** virtual module xSync() callback. It is illegal to write to
86618  ** virtual module tables in this case, so return SQLITE_LOCKED.
86619  */
86620  if( sqlite3VtabInSync(db) ){
86621    return SQLITE_LOCKED;
86622  }
86623  if( !pVTab ){
86624    return SQLITE_OK;
86625  }
86626  pModule = pVTab->pVtab->pModule;
86627
86628  if( pModule->xBegin ){
86629    int i;
86630
86631
86632    /* If pVtab is already in the aVTrans array, return early */
86633    for(i=0; i<db->nVTrans; i++){
86634      if( db->aVTrans[i]==pVTab ){
86635        return SQLITE_OK;
86636      }
86637    }
86638
86639    /* Invoke the xBegin method */
86640    rc = pModule->xBegin(pVTab->pVtab);
86641    if( rc==SQLITE_OK ){
86642      rc = addToVTrans(db, pVTab);
86643    }
86644  }
86645  return rc;
86646}
86647
86648/*
86649** The first parameter (pDef) is a function implementation.  The
86650** second parameter (pExpr) is the first argument to this function.
86651** If pExpr is a column in a virtual table, then let the virtual
86652** table implementation have an opportunity to overload the function.
86653**
86654** This routine is used to allow virtual table implementations to
86655** overload MATCH, LIKE, GLOB, and REGEXP operators.
86656**
86657** Return either the pDef argument (indicating no change) or a
86658** new FuncDef structure that is marked as ephemeral using the
86659** SQLITE_FUNC_EPHEM flag.
86660*/
86661SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
86662  sqlite3 *db,    /* Database connection for reporting malloc problems */
86663  FuncDef *pDef,  /* Function to possibly overload */
86664  int nArg,       /* Number of arguments to the function */
86665  Expr *pExpr     /* First argument to the function */
86666){
86667  Table *pTab;
86668  sqlite3_vtab *pVtab;
86669  sqlite3_module *pMod;
86670  void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
86671  void *pArg = 0;
86672  FuncDef *pNew;
86673  int rc = 0;
86674  char *zLowerName;
86675  unsigned char *z;
86676
86677
86678  /* Check to see the left operand is a column in a virtual table */
86679  if( NEVER(pExpr==0) ) return pDef;
86680  if( pExpr->op!=TK_COLUMN ) return pDef;
86681  pTab = pExpr->pTab;
86682  if( NEVER(pTab==0) ) return pDef;
86683  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
86684  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
86685  assert( pVtab!=0 );
86686  assert( pVtab->pModule!=0 );
86687  pMod = (sqlite3_module *)pVtab->pModule;
86688  if( pMod->xFindFunction==0 ) return pDef;
86689
86690  /* Call the xFindFunction method on the virtual table implementation
86691  ** to see if the implementation wants to overload this function
86692  */
86693  zLowerName = sqlite3DbStrDup(db, pDef->zName);
86694  if( zLowerName ){
86695    for(z=(unsigned char*)zLowerName; *z; z++){
86696      *z = sqlite3UpperToLower[*z];
86697    }
86698    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
86699    sqlite3DbFree(db, zLowerName);
86700  }
86701  if( rc==0 ){
86702    return pDef;
86703  }
86704
86705  /* Create a new ephemeral function definition for the overloaded
86706  ** function */
86707  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
86708                             + sqlite3Strlen30(pDef->zName) + 1);
86709  if( pNew==0 ){
86710    return pDef;
86711  }
86712  *pNew = *pDef;
86713  pNew->zName = (char *)&pNew[1];
86714  memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
86715  pNew->xFunc = xFunc;
86716  pNew->pUserData = pArg;
86717  pNew->flags |= SQLITE_FUNC_EPHEM;
86718  return pNew;
86719}
86720
86721/*
86722** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
86723** array so that an OP_VBegin will get generated for it.  Add pTab to the
86724** array if it is missing.  If pTab is already in the array, this routine
86725** is a no-op.
86726*/
86727SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
86728  Parse *pToplevel = sqlite3ParseToplevel(pParse);
86729  int i, n;
86730  Table **apVtabLock;
86731
86732  assert( IsVirtual(pTab) );
86733  for(i=0; i<pToplevel->nVtabLock; i++){
86734    if( pTab==pToplevel->apVtabLock[i] ) return;
86735  }
86736  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
86737  apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
86738  if( apVtabLock ){
86739    pToplevel->apVtabLock = apVtabLock;
86740    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
86741  }else{
86742    pToplevel->db->mallocFailed = 1;
86743  }
86744}
86745
86746#endif /* SQLITE_OMIT_VIRTUALTABLE */
86747
86748/************** End of vtab.c ************************************************/
86749/************** Begin file where.c *******************************************/
86750/*
86751** 2001 September 15
86752**
86753** The author disclaims copyright to this source code.  In place of
86754** a legal notice, here is a blessing:
86755**
86756**    May you do good and not evil.
86757**    May you find forgiveness for yourself and forgive others.
86758**    May you share freely, never taking more than you give.
86759**
86760*************************************************************************
86761** This module contains C code that generates VDBE code used to process
86762** the WHERE clause of SQL statements.  This module is responsible for
86763** generating the code that loops through a table looking for applicable
86764** rows.  Indices are selected and used to speed the search when doing
86765** so is applicable.  Because this module is responsible for selecting
86766** indices, you might also think of this module as the "query optimizer".
86767*/
86768
86769/*
86770** Trace output macros
86771*/
86772#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
86773SQLITE_PRIVATE int sqlite3WhereTrace = 0;
86774#endif
86775#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
86776# define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
86777#else
86778# define WHERETRACE(X)
86779#endif
86780
86781/* Forward reference
86782*/
86783typedef struct WhereClause WhereClause;
86784typedef struct WhereMaskSet WhereMaskSet;
86785typedef struct WhereOrInfo WhereOrInfo;
86786typedef struct WhereAndInfo WhereAndInfo;
86787typedef struct WhereCost WhereCost;
86788
86789/*
86790** The query generator uses an array of instances of this structure to
86791** help it analyze the subexpressions of the WHERE clause.  Each WHERE
86792** clause subexpression is separated from the others by AND operators,
86793** usually, or sometimes subexpressions separated by OR.
86794**
86795** All WhereTerms are collected into a single WhereClause structure.
86796** The following identity holds:
86797**
86798**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
86799**
86800** When a term is of the form:
86801**
86802**              X <op> <expr>
86803**
86804** where X is a column name and <op> is one of certain operators,
86805** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
86806** cursor number and column number for X.  WhereTerm.eOperator records
86807** the <op> using a bitmask encoding defined by WO_xxx below.  The
86808** use of a bitmask encoding for the operator allows us to search
86809** quickly for terms that match any of several different operators.
86810**
86811** A WhereTerm might also be two or more subterms connected by OR:
86812**
86813**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
86814**
86815** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
86816** and the WhereTerm.u.pOrInfo field points to auxiliary information that
86817** is collected about the
86818**
86819** If a term in the WHERE clause does not match either of the two previous
86820** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
86821** to the original subexpression content and wtFlags is set up appropriately
86822** but no other fields in the WhereTerm object are meaningful.
86823**
86824** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
86825** but they do so indirectly.  A single WhereMaskSet structure translates
86826** cursor number into bits and the translated bit is stored in the prereq
86827** fields.  The translation is used in order to maximize the number of
86828** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
86829** spread out over the non-negative integers.  For example, the cursor
86830** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
86831** translates these sparse cursor numbers into consecutive integers
86832** beginning with 0 in order to make the best possible use of the available
86833** bits in the Bitmask.  So, in the example above, the cursor numbers
86834** would be mapped into integers 0 through 7.
86835**
86836** The number of terms in a join is limited by the number of bits
86837** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
86838** is only able to process joins with 64 or fewer tables.
86839*/
86840typedef struct WhereTerm WhereTerm;
86841struct WhereTerm {
86842  Expr *pExpr;            /* Pointer to the subexpression that is this term */
86843  int iParent;            /* Disable pWC->a[iParent] when this term disabled */
86844  int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
86845  union {
86846    int leftColumn;         /* Column number of X in "X <op> <expr>" */
86847    WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
86848    WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
86849  } u;
86850  u16 eOperator;          /* A WO_xx value describing <op> */
86851  u8 wtFlags;             /* TERM_xxx bit flags.  See below */
86852  u8 nChild;              /* Number of children that must disable us */
86853  WhereClause *pWC;       /* The clause this term is part of */
86854  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
86855  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
86856};
86857
86858/*
86859** Allowed values of WhereTerm.wtFlags
86860*/
86861#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
86862#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
86863#define TERM_CODED      0x04   /* This term is already coded */
86864#define TERM_COPIED     0x08   /* Has a child */
86865#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
86866#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
86867#define TERM_OR_OK      0x40   /* Used during OR-clause processing */
86868
86869/*
86870** An instance of the following structure holds all information about a
86871** WHERE clause.  Mostly this is a container for one or more WhereTerms.
86872*/
86873struct WhereClause {
86874  Parse *pParse;           /* The parser context */
86875  WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
86876  Bitmask vmask;           /* Bitmask identifying virtual table cursors */
86877  u8 op;                   /* Split operator.  TK_AND or TK_OR */
86878  int nTerm;               /* Number of terms */
86879  int nSlot;               /* Number of entries in a[] */
86880  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
86881#if defined(SQLITE_SMALL_STACK)
86882  WhereTerm aStatic[1];    /* Initial static space for a[] */
86883#else
86884  WhereTerm aStatic[8];    /* Initial static space for a[] */
86885#endif
86886};
86887
86888/*
86889** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
86890** a dynamically allocated instance of the following structure.
86891*/
86892struct WhereOrInfo {
86893  WhereClause wc;          /* Decomposition into subterms */
86894  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
86895};
86896
86897/*
86898** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
86899** a dynamically allocated instance of the following structure.
86900*/
86901struct WhereAndInfo {
86902  WhereClause wc;          /* The subexpression broken out */
86903};
86904
86905/*
86906** An instance of the following structure keeps track of a mapping
86907** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
86908**
86909** The VDBE cursor numbers are small integers contained in
86910** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
86911** clause, the cursor numbers might not begin with 0 and they might
86912** contain gaps in the numbering sequence.  But we want to make maximum
86913** use of the bits in our bitmasks.  This structure provides a mapping
86914** from the sparse cursor numbers into consecutive integers beginning
86915** with 0.
86916**
86917** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
86918** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
86919**
86920** For example, if the WHERE clause expression used these VDBE
86921** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
86922** would map those cursor numbers into bits 0 through 5.
86923**
86924** Note that the mapping is not necessarily ordered.  In the example
86925** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
86926** 57->5, 73->4.  Or one of 719 other combinations might be used. It
86927** does not really matter.  What is important is that sparse cursor
86928** numbers all get mapped into bit numbers that begin with 0 and contain
86929** no gaps.
86930*/
86931struct WhereMaskSet {
86932  int n;                        /* Number of assigned cursor values */
86933  int ix[BMS];                  /* Cursor assigned to each bit */
86934};
86935
86936/*
86937** A WhereCost object records a lookup strategy and the estimated
86938** cost of pursuing that strategy.
86939*/
86940struct WhereCost {
86941  WherePlan plan;    /* The lookup strategy */
86942  double rCost;      /* Overall cost of pursuing this search strategy */
86943  double nRow;       /* Estimated number of output rows */
86944  Bitmask used;      /* Bitmask of cursors used by this plan */
86945};
86946
86947/*
86948** Bitmasks for the operators that indices are able to exploit.  An
86949** OR-ed combination of these values can be used when searching for
86950** terms in the where clause.
86951*/
86952#define WO_IN     0x001
86953#define WO_EQ     0x002
86954#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
86955#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
86956#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
86957#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
86958#define WO_MATCH  0x040
86959#define WO_ISNULL 0x080
86960#define WO_OR     0x100       /* Two or more OR-connected terms */
86961#define WO_AND    0x200       /* Two or more AND-connected terms */
86962
86963#define WO_ALL    0xfff       /* Mask of all possible WO_* values */
86964#define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
86965
86966/*
86967** Value for wsFlags returned by bestIndex() and stored in
86968** WhereLevel.wsFlags.  These flags determine which search
86969** strategies are appropriate.
86970**
86971** The least significant 12 bits is reserved as a mask for WO_ values above.
86972** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
86973** But if the table is the right table of a left join, WhereLevel.wsFlags
86974** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
86975** the "op" parameter to findTerm when we are resolving equality constraints.
86976** ISNULL constraints will then not be used on the right table of a left
86977** join.  Tickets #2177 and #2189.
86978*/
86979#define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
86980#define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
86981#define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
86982#define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
86983#define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
86984#define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
86985#define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
86986#define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
86987#define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
86988#define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
86989#define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
86990#define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
86991#define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
86992#define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
86993#define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
86994#define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
86995
86996/*
86997** Initialize a preallocated WhereClause structure.
86998*/
86999static void whereClauseInit(
87000  WhereClause *pWC,        /* The WhereClause to be initialized */
87001  Parse *pParse,           /* The parsing context */
87002  WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
87003){
87004  pWC->pParse = pParse;
87005  pWC->pMaskSet = pMaskSet;
87006  pWC->nTerm = 0;
87007  pWC->nSlot = ArraySize(pWC->aStatic);
87008  pWC->a = pWC->aStatic;
87009  pWC->vmask = 0;
87010}
87011
87012/* Forward reference */
87013static void whereClauseClear(WhereClause*);
87014
87015/*
87016** Deallocate all memory associated with a WhereOrInfo object.
87017*/
87018static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
87019  whereClauseClear(&p->wc);
87020  sqlite3DbFree(db, p);
87021}
87022
87023/*
87024** Deallocate all memory associated with a WhereAndInfo object.
87025*/
87026static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
87027  whereClauseClear(&p->wc);
87028  sqlite3DbFree(db, p);
87029}
87030
87031/*
87032** Deallocate a WhereClause structure.  The WhereClause structure
87033** itself is not freed.  This routine is the inverse of whereClauseInit().
87034*/
87035static void whereClauseClear(WhereClause *pWC){
87036  int i;
87037  WhereTerm *a;
87038  sqlite3 *db = pWC->pParse->db;
87039  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
87040    if( a->wtFlags & TERM_DYNAMIC ){
87041      sqlite3ExprDelete(db, a->pExpr);
87042    }
87043    if( a->wtFlags & TERM_ORINFO ){
87044      whereOrInfoDelete(db, a->u.pOrInfo);
87045    }else if( a->wtFlags & TERM_ANDINFO ){
87046      whereAndInfoDelete(db, a->u.pAndInfo);
87047    }
87048  }
87049  if( pWC->a!=pWC->aStatic ){
87050    sqlite3DbFree(db, pWC->a);
87051  }
87052}
87053
87054/*
87055** Add a single new WhereTerm entry to the WhereClause object pWC.
87056** The new WhereTerm object is constructed from Expr p and with wtFlags.
87057** The index in pWC->a[] of the new WhereTerm is returned on success.
87058** 0 is returned if the new WhereTerm could not be added due to a memory
87059** allocation error.  The memory allocation failure will be recorded in
87060** the db->mallocFailed flag so that higher-level functions can detect it.
87061**
87062** This routine will increase the size of the pWC->a[] array as necessary.
87063**
87064** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
87065** for freeing the expression p is assumed by the WhereClause object pWC.
87066** This is true even if this routine fails to allocate a new WhereTerm.
87067**
87068** WARNING:  This routine might reallocate the space used to store
87069** WhereTerms.  All pointers to WhereTerms should be invalidated after
87070** calling this routine.  Such pointers may be reinitialized by referencing
87071** the pWC->a[] array.
87072*/
87073static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
87074  WhereTerm *pTerm;
87075  int idx;
87076  if( pWC->nTerm>=pWC->nSlot ){
87077    WhereTerm *pOld = pWC->a;
87078    sqlite3 *db = pWC->pParse->db;
87079    pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
87080    if( pWC->a==0 ){
87081      if( wtFlags & TERM_DYNAMIC ){
87082        sqlite3ExprDelete(db, p);
87083      }
87084      pWC->a = pOld;
87085      return 0;
87086    }
87087    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
87088    if( pOld!=pWC->aStatic ){
87089      sqlite3DbFree(db, pOld);
87090    }
87091    pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
87092  }
87093  pTerm = &pWC->a[idx = pWC->nTerm++];
87094  pTerm->pExpr = p;
87095  pTerm->wtFlags = wtFlags;
87096  pTerm->pWC = pWC;
87097  pTerm->iParent = -1;
87098  return idx;
87099}
87100
87101/*
87102** This routine identifies subexpressions in the WHERE clause where
87103** each subexpression is separated by the AND operator or some other
87104** operator specified in the op parameter.  The WhereClause structure
87105** is filled with pointers to subexpressions.  For example:
87106**
87107**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
87108**           \________/     \_______________/     \________________/
87109**            slot[0]            slot[1]               slot[2]
87110**
87111** The original WHERE clause in pExpr is unaltered.  All this routine
87112** does is make slot[] entries point to substructure within pExpr.
87113**
87114** In the previous sentence and in the diagram, "slot[]" refers to
87115** the WhereClause.a[] array.  The slot[] array grows as needed to contain
87116** all terms of the WHERE clause.
87117*/
87118static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
87119  pWC->op = (u8)op;
87120  if( pExpr==0 ) return;
87121  if( pExpr->op!=op ){
87122    whereClauseInsert(pWC, pExpr, 0);
87123  }else{
87124    whereSplit(pWC, pExpr->pLeft, op);
87125    whereSplit(pWC, pExpr->pRight, op);
87126  }
87127}
87128
87129/*
87130** Initialize an expression mask set (a WhereMaskSet object)
87131*/
87132#define initMaskSet(P)  memset(P, 0, sizeof(*P))
87133
87134/*
87135** Return the bitmask for the given cursor number.  Return 0 if
87136** iCursor is not in the set.
87137*/
87138static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
87139  int i;
87140  assert( pMaskSet->n<=sizeof(Bitmask)*8 );
87141  for(i=0; i<pMaskSet->n; i++){
87142    if( pMaskSet->ix[i]==iCursor ){
87143      return ((Bitmask)1)<<i;
87144    }
87145  }
87146  return 0;
87147}
87148
87149/*
87150** Create a new mask for cursor iCursor.
87151**
87152** There is one cursor per table in the FROM clause.  The number of
87153** tables in the FROM clause is limited by a test early in the
87154** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
87155** array will never overflow.
87156*/
87157static void createMask(WhereMaskSet *pMaskSet, int iCursor){
87158  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
87159  pMaskSet->ix[pMaskSet->n++] = iCursor;
87160}
87161
87162/*
87163** This routine walks (recursively) an expression tree and generates
87164** a bitmask indicating which tables are used in that expression
87165** tree.
87166**
87167** In order for this routine to work, the calling function must have
87168** previously invoked sqlite3ResolveExprNames() on the expression.  See
87169** the header comment on that routine for additional information.
87170** The sqlite3ResolveExprNames() routines looks for column names and
87171** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
87172** the VDBE cursor number of the table.  This routine just has to
87173** translate the cursor numbers into bitmask values and OR all
87174** the bitmasks together.
87175*/
87176static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
87177static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
87178static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
87179  Bitmask mask = 0;
87180  if( p==0 ) return 0;
87181  if( p->op==TK_COLUMN ){
87182    mask = getMask(pMaskSet, p->iTable);
87183    return mask;
87184  }
87185  mask = exprTableUsage(pMaskSet, p->pRight);
87186  mask |= exprTableUsage(pMaskSet, p->pLeft);
87187  if( ExprHasProperty(p, EP_xIsSelect) ){
87188    mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
87189  }else{
87190    mask |= exprListTableUsage(pMaskSet, p->x.pList);
87191  }
87192  return mask;
87193}
87194static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
87195  int i;
87196  Bitmask mask = 0;
87197  if( pList ){
87198    for(i=0; i<pList->nExpr; i++){
87199      mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
87200    }
87201  }
87202  return mask;
87203}
87204static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
87205  Bitmask mask = 0;
87206  while( pS ){
87207    mask |= exprListTableUsage(pMaskSet, pS->pEList);
87208    mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
87209    mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
87210    mask |= exprTableUsage(pMaskSet, pS->pWhere);
87211    mask |= exprTableUsage(pMaskSet, pS->pHaving);
87212    pS = pS->pPrior;
87213  }
87214  return mask;
87215}
87216
87217/*
87218** Return TRUE if the given operator is one of the operators that is
87219** allowed for an indexable WHERE clause term.  The allowed operators are
87220** "=", "<", ">", "<=", ">=", and "IN".
87221*/
87222static int allowedOp(int op){
87223  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
87224  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
87225  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
87226  assert( TK_GE==TK_EQ+4 );
87227  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
87228}
87229
87230/*
87231** Swap two objects of type TYPE.
87232*/
87233#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
87234
87235/*
87236** Commute a comparison operator.  Expressions of the form "X op Y"
87237** are converted into "Y op X".
87238**
87239** If a collation sequence is associated with either the left or right
87240** side of the comparison, it remains associated with the same side after
87241** the commutation. So "Y collate NOCASE op X" becomes
87242** "X collate NOCASE op Y". This is because any collation sequence on
87243** the left hand side of a comparison overrides any collation sequence
87244** attached to the right. For the same reason the EP_ExpCollate flag
87245** is not commuted.
87246*/
87247static void exprCommute(Parse *pParse, Expr *pExpr){
87248  u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
87249  u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
87250  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
87251  pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
87252  pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
87253  SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
87254  pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
87255  pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
87256  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
87257  if( pExpr->op>=TK_GT ){
87258    assert( TK_LT==TK_GT+2 );
87259    assert( TK_GE==TK_LE+2 );
87260    assert( TK_GT>TK_EQ );
87261    assert( TK_GT<TK_LE );
87262    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
87263    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
87264  }
87265}
87266
87267/*
87268** Translate from TK_xx operator to WO_xx bitmask.
87269*/
87270static u16 operatorMask(int op){
87271  u16 c;
87272  assert( allowedOp(op) );
87273  if( op==TK_IN ){
87274    c = WO_IN;
87275  }else if( op==TK_ISNULL ){
87276    c = WO_ISNULL;
87277  }else{
87278    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
87279    c = (u16)(WO_EQ<<(op-TK_EQ));
87280  }
87281  assert( op!=TK_ISNULL || c==WO_ISNULL );
87282  assert( op!=TK_IN || c==WO_IN );
87283  assert( op!=TK_EQ || c==WO_EQ );
87284  assert( op!=TK_LT || c==WO_LT );
87285  assert( op!=TK_LE || c==WO_LE );
87286  assert( op!=TK_GT || c==WO_GT );
87287  assert( op!=TK_GE || c==WO_GE );
87288  return c;
87289}
87290
87291/*
87292** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
87293** where X is a reference to the iColumn of table iCur and <op> is one of
87294** the WO_xx operator codes specified by the op parameter.
87295** Return a pointer to the term.  Return 0 if not found.
87296*/
87297static WhereTerm *findTerm(
87298  WhereClause *pWC,     /* The WHERE clause to be searched */
87299  int iCur,             /* Cursor number of LHS */
87300  int iColumn,          /* Column number of LHS */
87301  Bitmask notReady,     /* RHS must not overlap with this mask */
87302  u32 op,               /* Mask of WO_xx values describing operator */
87303  Index *pIdx           /* Must be compatible with this index, if not NULL */
87304){
87305  WhereTerm *pTerm;
87306  int k;
87307  assert( iCur>=0 );
87308  op &= WO_ALL;
87309  for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
87310    if( pTerm->leftCursor==iCur
87311       && (pTerm->prereqRight & notReady)==0
87312       && pTerm->u.leftColumn==iColumn
87313       && (pTerm->eOperator & op)!=0
87314    ){
87315      if( pIdx && pTerm->eOperator!=WO_ISNULL ){
87316        Expr *pX = pTerm->pExpr;
87317        CollSeq *pColl;
87318        char idxaff;
87319        int j;
87320        Parse *pParse = pWC->pParse;
87321
87322        idxaff = pIdx->pTable->aCol[iColumn].affinity;
87323        if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
87324
87325        /* Figure out the collation sequence required from an index for
87326        ** it to be useful for optimising expression pX. Store this
87327        ** value in variable pColl.
87328        */
87329        assert(pX->pLeft);
87330        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
87331        assert(pColl || pParse->nErr);
87332
87333        for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
87334          if( NEVER(j>=pIdx->nColumn) ) return 0;
87335        }
87336        if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
87337      }
87338      return pTerm;
87339    }
87340  }
87341  return 0;
87342}
87343
87344/* Forward reference */
87345static void exprAnalyze(SrcList*, WhereClause*, int);
87346
87347/*
87348** Call exprAnalyze on all terms in a WHERE clause.
87349**
87350**
87351*/
87352static void exprAnalyzeAll(
87353  SrcList *pTabList,       /* the FROM clause */
87354  WhereClause *pWC         /* the WHERE clause to be analyzed */
87355){
87356  int i;
87357  for(i=pWC->nTerm-1; i>=0; i--){
87358    exprAnalyze(pTabList, pWC, i);
87359  }
87360}
87361
87362#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
87363/*
87364** Check to see if the given expression is a LIKE or GLOB operator that
87365** can be optimized using inequality constraints.  Return TRUE if it is
87366** so and false if not.
87367**
87368** In order for the operator to be optimizible, the RHS must be a string
87369** literal that does not begin with a wildcard.
87370*/
87371static int isLikeOrGlob(
87372  Parse *pParse,    /* Parsing and code generating context */
87373  Expr *pExpr,      /* Test this expression */
87374  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
87375  int *pisComplete, /* True if the only wildcard is % in the last character */
87376  int *pnoCase      /* True if uppercase is equivalent to lowercase */
87377){
87378  const char *z = 0;         /* String on RHS of LIKE operator */
87379  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
87380  ExprList *pList;           /* List of operands to the LIKE operator */
87381  int c;                     /* One character in z[] */
87382  int cnt;                   /* Number of non-wildcard prefix characters */
87383  char wc[3];                /* Wildcard characters */
87384  CollSeq *pColl;            /* Collating sequence for LHS */
87385  sqlite3 *db = pParse->db;  /* Database connection */
87386  sqlite3_value *pVal = 0;
87387  int op;                    /* Opcode of pRight */
87388
87389  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
87390    return 0;
87391  }
87392#ifdef SQLITE_EBCDIC
87393  if( *pnoCase ) return 0;
87394#endif
87395  pList = pExpr->x.pList;
87396  pLeft = pList->a[1].pExpr;
87397  if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
87398    /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
87399    ** be the name of an indexed column with TEXT affinity. */
87400    return 0;
87401  }
87402  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
87403  pColl = sqlite3ExprCollSeq(pParse, pLeft);
87404  assert( pColl!=0 );  /* Every non-IPK column has a collating sequence */
87405  if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
87406      (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
87407    /* IMP: R-09003-32046 For the GLOB operator, the column must use the
87408    ** default BINARY collating sequence.
87409    ** IMP: R-41408-28306 For the LIKE operator, if case_sensitive_like mode
87410    ** is enabled then the column must use the default BINARY collating
87411    ** sequence, or if case_sensitive_like mode is disabled then the column
87412    ** must use the built-in NOCASE collating sequence.
87413    */
87414    return 0;
87415  }
87416
87417  pRight = pList->a[0].pExpr;
87418  op = pRight->op;
87419  if( op==TK_REGISTER ){
87420    op = pRight->op2;
87421  }
87422  if( op==TK_VARIABLE ){
87423    Vdbe *pReprepare = pParse->pReprepare;
87424    pVal = sqlite3VdbeGetValue(pReprepare, pRight->iColumn, SQLITE_AFF_NONE);
87425    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
87426      z = (char *)sqlite3_value_text(pVal);
87427    }
87428    sqlite3VdbeSetVarmask(pParse->pVdbe, pRight->iColumn);
87429    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
87430  }else if( op==TK_STRING ){
87431    z = pRight->u.zToken;
87432  }
87433  if( z ){
87434    cnt = 0;
87435    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
87436      cnt++;
87437    }
87438    if( cnt!=0 && c!=0 && 255!=(u8)z[cnt-1] ){
87439      Expr *pPrefix;
87440      *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
87441      pPrefix = sqlite3Expr(db, TK_STRING, z);
87442      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
87443      *ppPrefix = pPrefix;
87444      if( op==TK_VARIABLE ){
87445        Vdbe *v = pParse->pVdbe;
87446        sqlite3VdbeSetVarmask(v, pRight->iColumn);
87447        if( *pisComplete && pRight->u.zToken[1] ){
87448          /* If the rhs of the LIKE expression is a variable, and the current
87449          ** value of the variable means there is no need to invoke the LIKE
87450          ** function, then no OP_Variable will be added to the program.
87451          ** This causes problems for the sqlite3_bind_parameter_name()
87452          ** API. To workaround them, add a dummy OP_Variable here.
87453          */
87454          int r1 = sqlite3GetTempReg(pParse);
87455          sqlite3ExprCodeTarget(pParse, pRight, r1);
87456          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
87457          sqlite3ReleaseTempReg(pParse, r1);
87458        }
87459      }
87460    }else{
87461      z = 0;
87462    }
87463  }
87464
87465  sqlite3ValueFree(pVal);
87466  return (z!=0);
87467}
87468#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
87469
87470
87471#ifndef SQLITE_OMIT_VIRTUALTABLE
87472/*
87473** Check to see if the given expression is of the form
87474**
87475**         column MATCH expr
87476**
87477** If it is then return TRUE.  If not, return FALSE.
87478*/
87479static int isMatchOfColumn(
87480  Expr *pExpr      /* Test this expression */
87481){
87482  ExprList *pList;
87483
87484  if( pExpr->op!=TK_FUNCTION ){
87485    return 0;
87486  }
87487  if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
87488    return 0;
87489  }
87490  pList = pExpr->x.pList;
87491  if( pList->nExpr!=2 ){
87492    return 0;
87493  }
87494  if( pList->a[1].pExpr->op != TK_COLUMN ){
87495    return 0;
87496  }
87497  return 1;
87498}
87499#endif /* SQLITE_OMIT_VIRTUALTABLE */
87500
87501/*
87502** If the pBase expression originated in the ON or USING clause of
87503** a join, then transfer the appropriate markings over to derived.
87504*/
87505static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
87506  pDerived->flags |= pBase->flags & EP_FromJoin;
87507  pDerived->iRightJoinTable = pBase->iRightJoinTable;
87508}
87509
87510#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
87511/*
87512** Analyze a term that consists of two or more OR-connected
87513** subterms.  So in:
87514**
87515**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
87516**                          ^^^^^^^^^^^^^^^^^^^^
87517**
87518** This routine analyzes terms such as the middle term in the above example.
87519** A WhereOrTerm object is computed and attached to the term under
87520** analysis, regardless of the outcome of the analysis.  Hence:
87521**
87522**     WhereTerm.wtFlags   |=  TERM_ORINFO
87523**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
87524**
87525** The term being analyzed must have two or more of OR-connected subterms.
87526** A single subterm might be a set of AND-connected sub-subterms.
87527** Examples of terms under analysis:
87528**
87529**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
87530**     (B)     x=expr1 OR expr2=x OR x=expr3
87531**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
87532**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
87533**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
87534**
87535** CASE 1:
87536**
87537** If all subterms are of the form T.C=expr for some single column of C
87538** a single table T (as shown in example B above) then create a new virtual
87539** term that is an equivalent IN expression.  In other words, if the term
87540** being analyzed is:
87541**
87542**      x = expr1  OR  expr2 = x  OR  x = expr3
87543**
87544** then create a new virtual term like this:
87545**
87546**      x IN (expr1,expr2,expr3)
87547**
87548** CASE 2:
87549**
87550** If all subterms are indexable by a single table T, then set
87551**
87552**     WhereTerm.eOperator              =  WO_OR
87553**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
87554**
87555** A subterm is "indexable" if it is of the form
87556** "T.C <op> <expr>" where C is any column of table T and
87557** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
87558** A subterm is also indexable if it is an AND of two or more
87559** subsubterms at least one of which is indexable.  Indexable AND
87560** subterms have their eOperator set to WO_AND and they have
87561** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
87562**
87563** From another point of view, "indexable" means that the subterm could
87564** potentially be used with an index if an appropriate index exists.
87565** This analysis does not consider whether or not the index exists; that
87566** is something the bestIndex() routine will determine.  This analysis
87567** only looks at whether subterms appropriate for indexing exist.
87568**
87569** All examples A through E above all satisfy case 2.  But if a term
87570** also statisfies case 1 (such as B) we know that the optimizer will
87571** always prefer case 1, so in that case we pretend that case 2 is not
87572** satisfied.
87573**
87574** It might be the case that multiple tables are indexable.  For example,
87575** (E) above is indexable on tables P, Q, and R.
87576**
87577** Terms that satisfy case 2 are candidates for lookup by using
87578** separate indices to find rowids for each subterm and composing
87579** the union of all rowids using a RowSet object.  This is similar
87580** to "bitmap indices" in other database engines.
87581**
87582** OTHERWISE:
87583**
87584** If neither case 1 nor case 2 apply, then leave the eOperator set to
87585** zero.  This term is not useful for search.
87586*/
87587static void exprAnalyzeOrTerm(
87588  SrcList *pSrc,            /* the FROM clause */
87589  WhereClause *pWC,         /* the complete WHERE clause */
87590  int idxTerm               /* Index of the OR-term to be analyzed */
87591){
87592  Parse *pParse = pWC->pParse;            /* Parser context */
87593  sqlite3 *db = pParse->db;               /* Database connection */
87594  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
87595  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
87596  WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
87597  int i;                                  /* Loop counters */
87598  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
87599  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
87600  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
87601  Bitmask chngToIN;         /* Tables that might satisfy case 1 */
87602  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
87603
87604  /*
87605  ** Break the OR clause into its separate subterms.  The subterms are
87606  ** stored in a WhereClause structure containing within the WhereOrInfo
87607  ** object that is attached to the original OR clause term.
87608  */
87609  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
87610  assert( pExpr->op==TK_OR );
87611  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
87612  if( pOrInfo==0 ) return;
87613  pTerm->wtFlags |= TERM_ORINFO;
87614  pOrWc = &pOrInfo->wc;
87615  whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
87616  whereSplit(pOrWc, pExpr, TK_OR);
87617  exprAnalyzeAll(pSrc, pOrWc);
87618  if( db->mallocFailed ) return;
87619  assert( pOrWc->nTerm>=2 );
87620
87621  /*
87622  ** Compute the set of tables that might satisfy cases 1 or 2.
87623  */
87624  indexable = ~(Bitmask)0;
87625  chngToIN = ~(pWC->vmask);
87626  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
87627    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
87628      WhereAndInfo *pAndInfo;
87629      assert( pOrTerm->eOperator==0 );
87630      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
87631      chngToIN = 0;
87632      pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
87633      if( pAndInfo ){
87634        WhereClause *pAndWC;
87635        WhereTerm *pAndTerm;
87636        int j;
87637        Bitmask b = 0;
87638        pOrTerm->u.pAndInfo = pAndInfo;
87639        pOrTerm->wtFlags |= TERM_ANDINFO;
87640        pOrTerm->eOperator = WO_AND;
87641        pAndWC = &pAndInfo->wc;
87642        whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
87643        whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
87644        exprAnalyzeAll(pSrc, pAndWC);
87645        testcase( db->mallocFailed );
87646        if( !db->mallocFailed ){
87647          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
87648            assert( pAndTerm->pExpr );
87649            if( allowedOp(pAndTerm->pExpr->op) ){
87650              b |= getMask(pMaskSet, pAndTerm->leftCursor);
87651            }
87652          }
87653        }
87654        indexable &= b;
87655      }
87656    }else if( pOrTerm->wtFlags & TERM_COPIED ){
87657      /* Skip this term for now.  We revisit it when we process the
87658      ** corresponding TERM_VIRTUAL term */
87659    }else{
87660      Bitmask b;
87661      b = getMask(pMaskSet, pOrTerm->leftCursor);
87662      if( pOrTerm->wtFlags & TERM_VIRTUAL ){
87663        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
87664        b |= getMask(pMaskSet, pOther->leftCursor);
87665      }
87666      indexable &= b;
87667      if( pOrTerm->eOperator!=WO_EQ ){
87668        chngToIN = 0;
87669      }else{
87670        chngToIN &= b;
87671      }
87672    }
87673  }
87674
87675  /*
87676  ** Record the set of tables that satisfy case 2.  The set might be
87677  ** empty.
87678  */
87679  pOrInfo->indexable = indexable;
87680  pTerm->eOperator = indexable==0 ? 0 : WO_OR;
87681
87682  /*
87683  ** chngToIN holds a set of tables that *might* satisfy case 1.  But
87684  ** we have to do some additional checking to see if case 1 really
87685  ** is satisfied.
87686  **
87687  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
87688  ** that there is no possibility of transforming the OR clause into an
87689  ** IN operator because one or more terms in the OR clause contain
87690  ** something other than == on a column in the single table.  The 1-bit
87691  ** case means that every term of the OR clause is of the form
87692  ** "table.column=expr" for some single table.  The one bit that is set
87693  ** will correspond to the common table.  We still need to check to make
87694  ** sure the same column is used on all terms.  The 2-bit case is when
87695  ** the all terms are of the form "table1.column=table2.column".  It
87696  ** might be possible to form an IN operator with either table1.column
87697  ** or table2.column as the LHS if either is common to every term of
87698  ** the OR clause.
87699  **
87700  ** Note that terms of the form "table.column1=table.column2" (the
87701  ** same table on both sizes of the ==) cannot be optimized.
87702  */
87703  if( chngToIN ){
87704    int okToChngToIN = 0;     /* True if the conversion to IN is valid */
87705    int iColumn = -1;         /* Column index on lhs of IN operator */
87706    int iCursor = -1;         /* Table cursor common to all terms */
87707    int j = 0;                /* Loop counter */
87708
87709    /* Search for a table and column that appears on one side or the
87710    ** other of the == operator in every subterm.  That table and column
87711    ** will be recorded in iCursor and iColumn.  There might not be any
87712    ** such table and column.  Set okToChngToIN if an appropriate table
87713    ** and column is found but leave okToChngToIN false if not found.
87714    */
87715    for(j=0; j<2 && !okToChngToIN; j++){
87716      pOrTerm = pOrWc->a;
87717      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
87718        assert( pOrTerm->eOperator==WO_EQ );
87719        pOrTerm->wtFlags &= ~TERM_OR_OK;
87720        if( pOrTerm->leftCursor==iCursor ){
87721          /* This is the 2-bit case and we are on the second iteration and
87722          ** current term is from the first iteration.  So skip this term. */
87723          assert( j==1 );
87724          continue;
87725        }
87726        if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
87727          /* This term must be of the form t1.a==t2.b where t2 is in the
87728          ** chngToIN set but t1 is not.  This term will be either preceeded
87729          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
87730          ** and use its inversion. */
87731          testcase( pOrTerm->wtFlags & TERM_COPIED );
87732          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
87733          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
87734          continue;
87735        }
87736        iColumn = pOrTerm->u.leftColumn;
87737        iCursor = pOrTerm->leftCursor;
87738        break;
87739      }
87740      if( i<0 ){
87741        /* No candidate table+column was found.  This can only occur
87742        ** on the second iteration */
87743        assert( j==1 );
87744        assert( (chngToIN&(chngToIN-1))==0 );
87745        assert( chngToIN==getMask(pMaskSet, iCursor) );
87746        break;
87747      }
87748      testcase( j==1 );
87749
87750      /* We have found a candidate table and column.  Check to see if that
87751      ** table and column is common to every term in the OR clause */
87752      okToChngToIN = 1;
87753      for(; i>=0 && okToChngToIN; i--, pOrTerm++){
87754        assert( pOrTerm->eOperator==WO_EQ );
87755        if( pOrTerm->leftCursor!=iCursor ){
87756          pOrTerm->wtFlags &= ~TERM_OR_OK;
87757        }else if( pOrTerm->u.leftColumn!=iColumn ){
87758          okToChngToIN = 0;
87759        }else{
87760          int affLeft, affRight;
87761          /* If the right-hand side is also a column, then the affinities
87762          ** of both right and left sides must be such that no type
87763          ** conversions are required on the right.  (Ticket #2249)
87764          */
87765          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
87766          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
87767          if( affRight!=0 && affRight!=affLeft ){
87768            okToChngToIN = 0;
87769          }else{
87770            pOrTerm->wtFlags |= TERM_OR_OK;
87771          }
87772        }
87773      }
87774    }
87775
87776    /* At this point, okToChngToIN is true if original pTerm satisfies
87777    ** case 1.  In that case, construct a new virtual term that is
87778    ** pTerm converted into an IN operator.
87779    */
87780    if( okToChngToIN ){
87781      Expr *pDup;            /* A transient duplicate expression */
87782      ExprList *pList = 0;   /* The RHS of the IN operator */
87783      Expr *pLeft = 0;       /* The LHS of the IN operator */
87784      Expr *pNew;            /* The complete IN operator */
87785
87786      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
87787        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
87788        assert( pOrTerm->eOperator==WO_EQ );
87789        assert( pOrTerm->leftCursor==iCursor );
87790        assert( pOrTerm->u.leftColumn==iColumn );
87791        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
87792        pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
87793        pLeft = pOrTerm->pExpr->pLeft;
87794      }
87795      assert( pLeft!=0 );
87796      pDup = sqlite3ExprDup(db, pLeft, 0);
87797      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
87798      if( pNew ){
87799        int idxNew;
87800        transferJoinMarkings(pNew, pExpr);
87801        assert( !ExprHasProperty(pNew, EP_xIsSelect) );
87802        pNew->x.pList = pList;
87803        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
87804        testcase( idxNew==0 );
87805        exprAnalyze(pSrc, pWC, idxNew);
87806        pTerm = &pWC->a[idxTerm];
87807        pWC->a[idxNew].iParent = idxTerm;
87808        pTerm->nChild = 1;
87809      }else{
87810        sqlite3ExprListDelete(db, pList);
87811      }
87812      pTerm->eOperator = 0;  /* case 1 trumps case 2 */
87813    }
87814  }
87815}
87816#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
87817
87818
87819/*
87820** The input to this routine is an WhereTerm structure with only the
87821** "pExpr" field filled in.  The job of this routine is to analyze the
87822** subexpression and populate all the other fields of the WhereTerm
87823** structure.
87824**
87825** If the expression is of the form "<expr> <op> X" it gets commuted
87826** to the standard form of "X <op> <expr>".
87827**
87828** If the expression is of the form "X <op> Y" where both X and Y are
87829** columns, then the original expression is unchanged and a new virtual
87830** term of the form "Y <op> X" is added to the WHERE clause and
87831** analyzed separately.  The original term is marked with TERM_COPIED
87832** and the new term is marked with TERM_DYNAMIC (because it's pExpr
87833** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
87834** is a commuted copy of a prior term.)  The original term has nChild=1
87835** and the copy has idxParent set to the index of the original term.
87836*/
87837static void exprAnalyze(
87838  SrcList *pSrc,            /* the FROM clause */
87839  WhereClause *pWC,         /* the WHERE clause */
87840  int idxTerm               /* Index of the term to be analyzed */
87841){
87842  WhereTerm *pTerm;                /* The term to be analyzed */
87843  WhereMaskSet *pMaskSet;          /* Set of table index masks */
87844  Expr *pExpr;                     /* The expression to be analyzed */
87845  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
87846  Bitmask prereqAll;               /* Prerequesites of pExpr */
87847  Bitmask extraRight = 0;          /* */
87848  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
87849  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
87850  int noCase = 0;                  /* LIKE/GLOB distinguishes case */
87851  int op;                          /* Top-level operator.  pExpr->op */
87852  Parse *pParse = pWC->pParse;     /* Parsing context */
87853  sqlite3 *db = pParse->db;        /* Database connection */
87854
87855  if( db->mallocFailed ){
87856    return;
87857  }
87858  pTerm = &pWC->a[idxTerm];
87859  pMaskSet = pWC->pMaskSet;
87860  pExpr = pTerm->pExpr;
87861  prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
87862  op = pExpr->op;
87863  if( op==TK_IN ){
87864    assert( pExpr->pRight==0 );
87865    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
87866      pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
87867    }else{
87868      pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
87869    }
87870  }else if( op==TK_ISNULL ){
87871    pTerm->prereqRight = 0;
87872  }else{
87873    pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
87874  }
87875  prereqAll = exprTableUsage(pMaskSet, pExpr);
87876  if( ExprHasProperty(pExpr, EP_FromJoin) ){
87877    Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
87878    prereqAll |= x;
87879    extraRight = x-1;  /* ON clause terms may not be used with an index
87880                       ** on left table of a LEFT JOIN.  Ticket #3015 */
87881  }
87882  pTerm->prereqAll = prereqAll;
87883  pTerm->leftCursor = -1;
87884  pTerm->iParent = -1;
87885  pTerm->eOperator = 0;
87886  if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
87887    Expr *pLeft = pExpr->pLeft;
87888    Expr *pRight = pExpr->pRight;
87889    if( pLeft->op==TK_COLUMN ){
87890      pTerm->leftCursor = pLeft->iTable;
87891      pTerm->u.leftColumn = pLeft->iColumn;
87892      pTerm->eOperator = operatorMask(op);
87893    }
87894    if( pRight && pRight->op==TK_COLUMN ){
87895      WhereTerm *pNew;
87896      Expr *pDup;
87897      if( pTerm->leftCursor>=0 ){
87898        int idxNew;
87899        pDup = sqlite3ExprDup(db, pExpr, 0);
87900        if( db->mallocFailed ){
87901          sqlite3ExprDelete(db, pDup);
87902          return;
87903        }
87904        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
87905        if( idxNew==0 ) return;
87906        pNew = &pWC->a[idxNew];
87907        pNew->iParent = idxTerm;
87908        pTerm = &pWC->a[idxTerm];
87909        pTerm->nChild = 1;
87910        pTerm->wtFlags |= TERM_COPIED;
87911      }else{
87912        pDup = pExpr;
87913        pNew = pTerm;
87914      }
87915      exprCommute(pParse, pDup);
87916      pLeft = pDup->pLeft;
87917      pNew->leftCursor = pLeft->iTable;
87918      pNew->u.leftColumn = pLeft->iColumn;
87919      pNew->prereqRight = prereqLeft;
87920      pNew->prereqAll = prereqAll;
87921      pNew->eOperator = operatorMask(pDup->op);
87922    }
87923  }
87924
87925#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
87926  /* If a term is the BETWEEN operator, create two new virtual terms
87927  ** that define the range that the BETWEEN implements.  For example:
87928  **
87929  **      a BETWEEN b AND c
87930  **
87931  ** is converted into:
87932  **
87933  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
87934  **
87935  ** The two new terms are added onto the end of the WhereClause object.
87936  ** The new terms are "dynamic" and are children of the original BETWEEN
87937  ** term.  That means that if the BETWEEN term is coded, the children are
87938  ** skipped.  Or, if the children are satisfied by an index, the original
87939  ** BETWEEN term is skipped.
87940  */
87941  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
87942    ExprList *pList = pExpr->x.pList;
87943    int i;
87944    static const u8 ops[] = {TK_GE, TK_LE};
87945    assert( pList!=0 );
87946    assert( pList->nExpr==2 );
87947    for(i=0; i<2; i++){
87948      Expr *pNewExpr;
87949      int idxNew;
87950      pNewExpr = sqlite3PExpr(pParse, ops[i],
87951                             sqlite3ExprDup(db, pExpr->pLeft, 0),
87952                             sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
87953      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
87954      testcase( idxNew==0 );
87955      exprAnalyze(pSrc, pWC, idxNew);
87956      pTerm = &pWC->a[idxTerm];
87957      pWC->a[idxNew].iParent = idxTerm;
87958    }
87959    pTerm->nChild = 2;
87960  }
87961#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
87962
87963#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
87964  /* Analyze a term that is composed of two or more subterms connected by
87965  ** an OR operator.
87966  */
87967  else if( pExpr->op==TK_OR ){
87968    assert( pWC->op==TK_AND );
87969    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
87970    pTerm = &pWC->a[idxTerm];
87971  }
87972#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
87973
87974#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
87975  /* Add constraints to reduce the search space on a LIKE or GLOB
87976  ** operator.
87977  **
87978  ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
87979  **
87980  **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
87981  **
87982  ** The last character of the prefix "abc" is incremented to form the
87983  ** termination condition "abd".
87984  */
87985  if( pWC->op==TK_AND
87986   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
87987  ){
87988    Expr *pLeft;       /* LHS of LIKE/GLOB operator */
87989    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
87990    Expr *pNewExpr1;
87991    Expr *pNewExpr2;
87992    int idxNew1;
87993    int idxNew2;
87994
87995    pLeft = pExpr->x.pList->a[1].pExpr;
87996    pStr2 = sqlite3ExprDup(db, pStr1, 0);
87997    if( !db->mallocFailed ){
87998      u8 c, *pC;       /* Last character before the first wildcard */
87999      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
88000      c = *pC;
88001      if( noCase ){
88002        /* The point is to increment the last character before the first
88003        ** wildcard.  But if we increment '@', that will push it into the
88004        ** alphabetic range where case conversions will mess up the
88005        ** inequality.  To avoid this, make sure to also run the full
88006        ** LIKE on all candidate expressions by clearing the isComplete flag
88007        */
88008        if( c=='A'-1 ) isComplete = 0;
88009
88010        c = sqlite3UpperToLower[c];
88011      }
88012      *pC = c + 1;
88013    }
88014    pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft,0),pStr1,0);
88015    idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
88016    testcase( idxNew1==0 );
88017    exprAnalyze(pSrc, pWC, idxNew1);
88018    pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft,0),pStr2,0);
88019    idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
88020    testcase( idxNew2==0 );
88021    exprAnalyze(pSrc, pWC, idxNew2);
88022    pTerm = &pWC->a[idxTerm];
88023    if( isComplete ){
88024      pWC->a[idxNew1].iParent = idxTerm;
88025      pWC->a[idxNew2].iParent = idxTerm;
88026      pTerm->nChild = 2;
88027    }
88028  }
88029#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
88030
88031#ifndef SQLITE_OMIT_VIRTUALTABLE
88032  /* Add a WO_MATCH auxiliary term to the constraint set if the
88033  ** current expression is of the form:  column MATCH expr.
88034  ** This information is used by the xBestIndex methods of
88035  ** virtual tables.  The native query optimizer does not attempt
88036  ** to do anything with MATCH functions.
88037  */
88038  if( isMatchOfColumn(pExpr) ){
88039    int idxNew;
88040    Expr *pRight, *pLeft;
88041    WhereTerm *pNewTerm;
88042    Bitmask prereqColumn, prereqExpr;
88043
88044    pRight = pExpr->x.pList->a[0].pExpr;
88045    pLeft = pExpr->x.pList->a[1].pExpr;
88046    prereqExpr = exprTableUsage(pMaskSet, pRight);
88047    prereqColumn = exprTableUsage(pMaskSet, pLeft);
88048    if( (prereqExpr & prereqColumn)==0 ){
88049      Expr *pNewExpr;
88050      pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
88051                              0, sqlite3ExprDup(db, pRight, 0), 0);
88052      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
88053      testcase( idxNew==0 );
88054      pNewTerm = &pWC->a[idxNew];
88055      pNewTerm->prereqRight = prereqExpr;
88056      pNewTerm->leftCursor = pLeft->iTable;
88057      pNewTerm->u.leftColumn = pLeft->iColumn;
88058      pNewTerm->eOperator = WO_MATCH;
88059      pNewTerm->iParent = idxTerm;
88060      pTerm = &pWC->a[idxTerm];
88061      pTerm->nChild = 1;
88062      pTerm->wtFlags |= TERM_COPIED;
88063      pNewTerm->prereqAll = pTerm->prereqAll;
88064    }
88065  }
88066#endif /* SQLITE_OMIT_VIRTUALTABLE */
88067
88068  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
88069  ** an index for tables to the left of the join.
88070  */
88071  pTerm->prereqRight |= extraRight;
88072}
88073
88074/*
88075** Return TRUE if any of the expressions in pList->a[iFirst...] contain
88076** a reference to any table other than the iBase table.
88077*/
88078static int referencesOtherTables(
88079  ExprList *pList,          /* Search expressions in ths list */
88080  WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
88081  int iFirst,               /* Be searching with the iFirst-th expression */
88082  int iBase                 /* Ignore references to this table */
88083){
88084  Bitmask allowed = ~getMask(pMaskSet, iBase);
88085  while( iFirst<pList->nExpr ){
88086    if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
88087      return 1;
88088    }
88089  }
88090  return 0;
88091}
88092
88093
88094/*
88095** This routine decides if pIdx can be used to satisfy the ORDER BY
88096** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
88097** ORDER BY clause, this routine returns 0.
88098**
88099** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
88100** left-most table in the FROM clause of that same SELECT statement and
88101** the table has a cursor number of "base".  pIdx is an index on pTab.
88102**
88103** nEqCol is the number of columns of pIdx that are used as equality
88104** constraints.  Any of these columns may be missing from the ORDER BY
88105** clause and the match can still be a success.
88106**
88107** All terms of the ORDER BY that match against the index must be either
88108** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
88109** index do not need to satisfy this constraint.)  The *pbRev value is
88110** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
88111** the ORDER BY clause is all ASC.
88112*/
88113static int isSortingIndex(
88114  Parse *pParse,          /* Parsing context */
88115  WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
88116  Index *pIdx,            /* The index we are testing */
88117  int base,               /* Cursor number for the table to be sorted */
88118  ExprList *pOrderBy,     /* The ORDER BY clause */
88119  int nEqCol,             /* Number of index columns with == constraints */
88120  int *pbRev              /* Set to 1 if ORDER BY is DESC */
88121){
88122  int i, j;                       /* Loop counters */
88123  int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
88124  int nTerm;                      /* Number of ORDER BY terms */
88125  struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
88126  sqlite3 *db = pParse->db;
88127
88128  assert( pOrderBy!=0 );
88129  nTerm = pOrderBy->nExpr;
88130  assert( nTerm>0 );
88131
88132  /* Argument pIdx must either point to a 'real' named index structure,
88133  ** or an index structure allocated on the stack by bestBtreeIndex() to
88134  ** represent the rowid index that is part of every table.  */
88135  assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
88136
88137  /* Match terms of the ORDER BY clause against columns of
88138  ** the index.
88139  **
88140  ** Note that indices have pIdx->nColumn regular columns plus
88141  ** one additional column containing the rowid.  The rowid column
88142  ** of the index is also allowed to match against the ORDER BY
88143  ** clause.
88144  */
88145  for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
88146    Expr *pExpr;       /* The expression of the ORDER BY pTerm */
88147    CollSeq *pColl;    /* The collating sequence of pExpr */
88148    int termSortOrder; /* Sort order for this term */
88149    int iColumn;       /* The i-th column of the index.  -1 for rowid */
88150    int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
88151    const char *zColl; /* Name of the collating sequence for i-th index term */
88152
88153    pExpr = pTerm->pExpr;
88154    if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
88155      /* Can not use an index sort on anything that is not a column in the
88156      ** left-most table of the FROM clause */
88157      break;
88158    }
88159    pColl = sqlite3ExprCollSeq(pParse, pExpr);
88160    if( !pColl ){
88161      pColl = db->pDfltColl;
88162    }
88163    if( pIdx->zName && i<pIdx->nColumn ){
88164      iColumn = pIdx->aiColumn[i];
88165      if( iColumn==pIdx->pTable->iPKey ){
88166        iColumn = -1;
88167      }
88168      iSortOrder = pIdx->aSortOrder[i];
88169      zColl = pIdx->azColl[i];
88170    }else{
88171      iColumn = -1;
88172      iSortOrder = 0;
88173      zColl = pColl->zName;
88174    }
88175    if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
88176      /* Term j of the ORDER BY clause does not match column i of the index */
88177      if( i<nEqCol ){
88178        /* If an index column that is constrained by == fails to match an
88179        ** ORDER BY term, that is OK.  Just ignore that column of the index
88180        */
88181        continue;
88182      }else if( i==pIdx->nColumn ){
88183        /* Index column i is the rowid.  All other terms match. */
88184        break;
88185      }else{
88186        /* If an index column fails to match and is not constrained by ==
88187        ** then the index cannot satisfy the ORDER BY constraint.
88188        */
88189        return 0;
88190      }
88191    }
88192    assert( pIdx->aSortOrder!=0 || iColumn==-1 );
88193    assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
88194    assert( iSortOrder==0 || iSortOrder==1 );
88195    termSortOrder = iSortOrder ^ pTerm->sortOrder;
88196    if( i>nEqCol ){
88197      if( termSortOrder!=sortOrder ){
88198        /* Indices can only be used if all ORDER BY terms past the
88199        ** equality constraints are all either DESC or ASC. */
88200        return 0;
88201      }
88202    }else{
88203      sortOrder = termSortOrder;
88204    }
88205    j++;
88206    pTerm++;
88207    if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
88208      /* If the indexed column is the primary key and everything matches
88209      ** so far and none of the ORDER BY terms to the right reference other
88210      ** tables in the join, then we are assured that the index can be used
88211      ** to sort because the primary key is unique and so none of the other
88212      ** columns will make any difference
88213      */
88214      j = nTerm;
88215    }
88216  }
88217
88218  *pbRev = sortOrder!=0;
88219  if( j>=nTerm ){
88220    /* All terms of the ORDER BY clause are covered by this index so
88221    ** this index can be used for sorting. */
88222    return 1;
88223  }
88224  if( pIdx->onError!=OE_None && i==pIdx->nColumn
88225      && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
88226    /* All terms of this index match some prefix of the ORDER BY clause
88227    ** and the index is UNIQUE and no terms on the tail of the ORDER BY
88228    ** clause reference other tables in a join.  If this is all true then
88229    ** the order by clause is superfluous. */
88230    return 1;
88231  }
88232  return 0;
88233}
88234
88235/*
88236** Prepare a crude estimate of the logarithm of the input value.
88237** The results need not be exact.  This is only used for estimating
88238** the total cost of performing operations with O(logN) or O(NlogN)
88239** complexity.  Because N is just a guess, it is no great tragedy if
88240** logN is a little off.
88241*/
88242static double estLog(double N){
88243  double logN = 1;
88244  double x = 10;
88245  while( N>x ){
88246    logN += 1;
88247    x *= 10;
88248  }
88249  return logN;
88250}
88251
88252/*
88253** Two routines for printing the content of an sqlite3_index_info
88254** structure.  Used for testing and debugging only.  If neither
88255** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
88256** are no-ops.
88257*/
88258#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
88259static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
88260  int i;
88261  if( !sqlite3WhereTrace ) return;
88262  for(i=0; i<p->nConstraint; i++){
88263    sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
88264       i,
88265       p->aConstraint[i].iColumn,
88266       p->aConstraint[i].iTermOffset,
88267       p->aConstraint[i].op,
88268       p->aConstraint[i].usable);
88269  }
88270  for(i=0; i<p->nOrderBy; i++){
88271    sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
88272       i,
88273       p->aOrderBy[i].iColumn,
88274       p->aOrderBy[i].desc);
88275  }
88276}
88277static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
88278  int i;
88279  if( !sqlite3WhereTrace ) return;
88280  for(i=0; i<p->nConstraint; i++){
88281    sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
88282       i,
88283       p->aConstraintUsage[i].argvIndex,
88284       p->aConstraintUsage[i].omit);
88285  }
88286  sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
88287  sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
88288  sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
88289  sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
88290}
88291#else
88292#define TRACE_IDX_INPUTS(A)
88293#define TRACE_IDX_OUTPUTS(A)
88294#endif
88295
88296/*
88297** Required because bestIndex() is called by bestOrClauseIndex()
88298*/
88299static void bestIndex(
88300    Parse*, WhereClause*, struct SrcList_item*, Bitmask, ExprList*, WhereCost*);
88301
88302/*
88303** This routine attempts to find an scanning strategy that can be used
88304** to optimize an 'OR' expression that is part of a WHERE clause.
88305**
88306** The table associated with FROM clause term pSrc may be either a
88307** regular B-Tree table or a virtual table.
88308*/
88309static void bestOrClauseIndex(
88310  Parse *pParse,              /* The parsing context */
88311  WhereClause *pWC,           /* The WHERE clause */
88312  struct SrcList_item *pSrc,  /* The FROM clause term to search */
88313  Bitmask notReady,           /* Mask of cursors that are not available */
88314  ExprList *pOrderBy,         /* The ORDER BY clause */
88315  WhereCost *pCost            /* Lowest cost query plan */
88316){
88317#ifndef SQLITE_OMIT_OR_OPTIMIZATION
88318  const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
88319  const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
88320  WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
88321  WhereTerm *pTerm;                 /* A single term of the WHERE clause */
88322
88323  /* Search the WHERE clause terms for a usable WO_OR term. */
88324  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
88325    if( pTerm->eOperator==WO_OR
88326     && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
88327     && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
88328    ){
88329      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
88330      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
88331      WhereTerm *pOrTerm;
88332      int flags = WHERE_MULTI_OR;
88333      double rTotal = 0;
88334      double nRow = 0;
88335      Bitmask used = 0;
88336
88337      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
88338        WhereCost sTermCost;
88339        WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
88340          (pOrTerm - pOrWC->a), (pTerm - pWC->a)
88341        ));
88342        if( pOrTerm->eOperator==WO_AND ){
88343          WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
88344          bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost);
88345        }else if( pOrTerm->leftCursor==iCur ){
88346          WhereClause tempWC;
88347          tempWC.pParse = pWC->pParse;
88348          tempWC.pMaskSet = pWC->pMaskSet;
88349          tempWC.op = TK_AND;
88350          tempWC.a = pOrTerm;
88351          tempWC.nTerm = 1;
88352          bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost);
88353        }else{
88354          continue;
88355        }
88356        rTotal += sTermCost.rCost;
88357        nRow += sTermCost.nRow;
88358        used |= sTermCost.used;
88359        if( rTotal>=pCost->rCost ) break;
88360      }
88361
88362      /* If there is an ORDER BY clause, increase the scan cost to account
88363      ** for the cost of the sort. */
88364      if( pOrderBy!=0 ){
88365        rTotal += nRow*estLog(nRow);
88366        WHERETRACE(("... sorting increases OR cost to %.9g\n", rTotal));
88367      }
88368
88369      /* If the cost of scanning using this OR term for optimization is
88370      ** less than the current cost stored in pCost, replace the contents
88371      ** of pCost. */
88372      WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
88373      if( rTotal<pCost->rCost ){
88374        pCost->rCost = rTotal;
88375        pCost->nRow = nRow;
88376        pCost->used = used;
88377        pCost->plan.wsFlags = flags;
88378        pCost->plan.u.pTerm = pTerm;
88379      }
88380    }
88381  }
88382#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
88383}
88384
88385#ifndef SQLITE_OMIT_VIRTUALTABLE
88386/*
88387** Allocate and populate an sqlite3_index_info structure. It is the
88388** responsibility of the caller to eventually release the structure
88389** by passing the pointer returned by this function to sqlite3_free().
88390*/
88391static sqlite3_index_info *allocateIndexInfo(
88392  Parse *pParse,
88393  WhereClause *pWC,
88394  struct SrcList_item *pSrc,
88395  ExprList *pOrderBy
88396){
88397  int i, j;
88398  int nTerm;
88399  struct sqlite3_index_constraint *pIdxCons;
88400  struct sqlite3_index_orderby *pIdxOrderBy;
88401  struct sqlite3_index_constraint_usage *pUsage;
88402  WhereTerm *pTerm;
88403  int nOrderBy;
88404  sqlite3_index_info *pIdxInfo;
88405
88406  WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
88407
88408  /* Count the number of possible WHERE clause constraints referring
88409  ** to this virtual table */
88410  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
88411    if( pTerm->leftCursor != pSrc->iCursor ) continue;
88412    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
88413    testcase( pTerm->eOperator==WO_IN );
88414    testcase( pTerm->eOperator==WO_ISNULL );
88415    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
88416    nTerm++;
88417  }
88418
88419  /* If the ORDER BY clause contains only columns in the current
88420  ** virtual table then allocate space for the aOrderBy part of
88421  ** the sqlite3_index_info structure.
88422  */
88423  nOrderBy = 0;
88424  if( pOrderBy ){
88425    for(i=0; i<pOrderBy->nExpr; i++){
88426      Expr *pExpr = pOrderBy->a[i].pExpr;
88427      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
88428    }
88429    if( i==pOrderBy->nExpr ){
88430      nOrderBy = pOrderBy->nExpr;
88431    }
88432  }
88433
88434  /* Allocate the sqlite3_index_info structure
88435  */
88436  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
88437                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
88438                           + sizeof(*pIdxOrderBy)*nOrderBy );
88439  if( pIdxInfo==0 ){
88440    sqlite3ErrorMsg(pParse, "out of memory");
88441    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
88442    return 0;
88443  }
88444
88445  /* Initialize the structure.  The sqlite3_index_info structure contains
88446  ** many fields that are declared "const" to prevent xBestIndex from
88447  ** changing them.  We have to do some funky casting in order to
88448  ** initialize those fields.
88449  */
88450  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
88451  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
88452  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
88453  *(int*)&pIdxInfo->nConstraint = nTerm;
88454  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
88455  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
88456  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
88457  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
88458                                                                   pUsage;
88459
88460  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
88461    if( pTerm->leftCursor != pSrc->iCursor ) continue;
88462    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
88463    testcase( pTerm->eOperator==WO_IN );
88464    testcase( pTerm->eOperator==WO_ISNULL );
88465    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
88466    pIdxCons[j].iColumn = pTerm->u.leftColumn;
88467    pIdxCons[j].iTermOffset = i;
88468    pIdxCons[j].op = (u8)pTerm->eOperator;
88469    /* The direct assignment in the previous line is possible only because
88470    ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
88471    ** following asserts verify this fact. */
88472    assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
88473    assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
88474    assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
88475    assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
88476    assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
88477    assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
88478    assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
88479    j++;
88480  }
88481  for(i=0; i<nOrderBy; i++){
88482    Expr *pExpr = pOrderBy->a[i].pExpr;
88483    pIdxOrderBy[i].iColumn = pExpr->iColumn;
88484    pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
88485  }
88486
88487  return pIdxInfo;
88488}
88489
88490/*
88491** The table object reference passed as the second argument to this function
88492** must represent a virtual table. This function invokes the xBestIndex()
88493** method of the virtual table with the sqlite3_index_info pointer passed
88494** as the argument.
88495**
88496** If an error occurs, pParse is populated with an error message and a
88497** non-zero value is returned. Otherwise, 0 is returned and the output
88498** part of the sqlite3_index_info structure is left populated.
88499**
88500** Whether or not an error is returned, it is the responsibility of the
88501** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
88502** that this is required.
88503*/
88504static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
88505  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
88506  int i;
88507  int rc;
88508
88509  WHERETRACE(("xBestIndex for %s\n", pTab->zName));
88510  TRACE_IDX_INPUTS(p);
88511  rc = pVtab->pModule->xBestIndex(pVtab, p);
88512  TRACE_IDX_OUTPUTS(p);
88513
88514  if( rc!=SQLITE_OK ){
88515    if( rc==SQLITE_NOMEM ){
88516      pParse->db->mallocFailed = 1;
88517    }else if( !pVtab->zErrMsg ){
88518      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
88519    }else{
88520      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
88521    }
88522  }
88523  sqlite3DbFree(pParse->db, pVtab->zErrMsg);
88524  pVtab->zErrMsg = 0;
88525
88526  for(i=0; i<p->nConstraint; i++){
88527    if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
88528      sqlite3ErrorMsg(pParse,
88529          "table %s: xBestIndex returned an invalid plan", pTab->zName);
88530    }
88531  }
88532
88533  return pParse->nErr;
88534}
88535
88536
88537/*
88538** Compute the best index for a virtual table.
88539**
88540** The best index is computed by the xBestIndex method of the virtual
88541** table module.  This routine is really just a wrapper that sets up
88542** the sqlite3_index_info structure that is used to communicate with
88543** xBestIndex.
88544**
88545** In a join, this routine might be called multiple times for the
88546** same virtual table.  The sqlite3_index_info structure is created
88547** and initialized on the first invocation and reused on all subsequent
88548** invocations.  The sqlite3_index_info structure is also used when
88549** code is generated to access the virtual table.  The whereInfoDelete()
88550** routine takes care of freeing the sqlite3_index_info structure after
88551** everybody has finished with it.
88552*/
88553static void bestVirtualIndex(
88554  Parse *pParse,                  /* The parsing context */
88555  WhereClause *pWC,               /* The WHERE clause */
88556  struct SrcList_item *pSrc,      /* The FROM clause term to search */
88557  Bitmask notReady,               /* Mask of cursors that are not available */
88558  ExprList *pOrderBy,             /* The order by clause */
88559  WhereCost *pCost,               /* Lowest cost query plan */
88560  sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
88561){
88562  Table *pTab = pSrc->pTab;
88563  sqlite3_index_info *pIdxInfo;
88564  struct sqlite3_index_constraint *pIdxCons;
88565  struct sqlite3_index_constraint_usage *pUsage;
88566  WhereTerm *pTerm;
88567  int i, j;
88568  int nOrderBy;
88569
88570  /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
88571  ** malloc in allocateIndexInfo() fails and this function returns leaving
88572  ** wsFlags in an uninitialized state, the caller may behave unpredictably.
88573  */
88574  memset(pCost, 0, sizeof(*pCost));
88575  pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
88576
88577  /* If the sqlite3_index_info structure has not been previously
88578  ** allocated and initialized, then allocate and initialize it now.
88579  */
88580  pIdxInfo = *ppIdxInfo;
88581  if( pIdxInfo==0 ){
88582    *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
88583  }
88584  if( pIdxInfo==0 ){
88585    return;
88586  }
88587
88588  /* At this point, the sqlite3_index_info structure that pIdxInfo points
88589  ** to will have been initialized, either during the current invocation or
88590  ** during some prior invocation.  Now we just have to customize the
88591  ** details of pIdxInfo for the current invocation and pass it to
88592  ** xBestIndex.
88593  */
88594
88595  /* The module name must be defined. Also, by this point there must
88596  ** be a pointer to an sqlite3_vtab structure. Otherwise
88597  ** sqlite3ViewGetColumnNames() would have picked up the error.
88598  */
88599  assert( pTab->azModuleArg && pTab->azModuleArg[0] );
88600  assert( sqlite3GetVTable(pParse->db, pTab) );
88601
88602  /* Set the aConstraint[].usable fields and initialize all
88603  ** output variables to zero.
88604  **
88605  ** aConstraint[].usable is true for constraints where the right-hand
88606  ** side contains only references to tables to the left of the current
88607  ** table.  In other words, if the constraint is of the form:
88608  **
88609  **           column = expr
88610  **
88611  ** and we are evaluating a join, then the constraint on column is
88612  ** only valid if all tables referenced in expr occur to the left
88613  ** of the table containing column.
88614  **
88615  ** The aConstraints[] array contains entries for all constraints
88616  ** on the current table.  That way we only have to compute it once
88617  ** even though we might try to pick the best index multiple times.
88618  ** For each attempt at picking an index, the order of tables in the
88619  ** join might be different so we have to recompute the usable flag
88620  ** each time.
88621  */
88622  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
88623  pUsage = pIdxInfo->aConstraintUsage;
88624  for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
88625    j = pIdxCons->iTermOffset;
88626    pTerm = &pWC->a[j];
88627    pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
88628  }
88629  memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
88630  if( pIdxInfo->needToFreeIdxStr ){
88631    sqlite3_free(pIdxInfo->idxStr);
88632  }
88633  pIdxInfo->idxStr = 0;
88634  pIdxInfo->idxNum = 0;
88635  pIdxInfo->needToFreeIdxStr = 0;
88636  pIdxInfo->orderByConsumed = 0;
88637  /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
88638  pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
88639  nOrderBy = pIdxInfo->nOrderBy;
88640  if( !pOrderBy ){
88641    pIdxInfo->nOrderBy = 0;
88642  }
88643
88644  if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
88645    return;
88646  }
88647
88648  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
88649  for(i=0; i<pIdxInfo->nConstraint; i++){
88650    if( pUsage[i].argvIndex>0 ){
88651      pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
88652    }
88653  }
88654
88655  /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
88656  ** inital value of lowestCost in this loop. If it is, then the
88657  ** (cost<lowestCost) test below will never be true.
88658  **
88659  ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
88660  ** is defined.
88661  */
88662  if( (SQLITE_BIG_DBL/((double)2))<pIdxInfo->estimatedCost ){
88663    pCost->rCost = (SQLITE_BIG_DBL/((double)2));
88664  }else{
88665    pCost->rCost = pIdxInfo->estimatedCost;
88666  }
88667  pCost->plan.u.pVtabIdx = pIdxInfo;
88668  if( pIdxInfo->orderByConsumed ){
88669    pCost->plan.wsFlags |= WHERE_ORDERBY;
88670  }
88671  pCost->plan.nEq = 0;
88672  pIdxInfo->nOrderBy = nOrderBy;
88673
88674  /* Try to find a more efficient access pattern by using multiple indexes
88675  ** to optimize an OR expression within the WHERE clause.
88676  */
88677  bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
88678}
88679#endif /* SQLITE_OMIT_VIRTUALTABLE */
88680
88681/*
88682** Argument pIdx is a pointer to an index structure that has an array of
88683** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
88684** stored in Index.aSample. The domain of values stored in said column
88685** may be thought of as divided into (SQLITE_INDEX_SAMPLES+1) regions.
88686** Region 0 contains all values smaller than the first sample value. Region
88687** 1 contains values larger than or equal to the value of the first sample,
88688** but smaller than the value of the second. And so on.
88689**
88690** If successful, this function determines which of the regions value
88691** pVal lies in, sets *piRegion to the region index (a value between 0
88692** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
88693** Or, if an OOM occurs while converting text values between encodings,
88694** SQLITE_NOMEM is returned and *piRegion is undefined.
88695*/
88696#ifdef SQLITE_ENABLE_STAT2
88697static int whereRangeRegion(
88698  Parse *pParse,              /* Database connection */
88699  Index *pIdx,                /* Index to consider domain of */
88700  sqlite3_value *pVal,        /* Value to consider */
88701  int *piRegion               /* OUT: Region of domain in which value lies */
88702){
88703  if( ALWAYS(pVal) ){
88704    IndexSample *aSample = pIdx->aSample;
88705    int i = 0;
88706    int eType = sqlite3_value_type(pVal);
88707
88708    if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
88709      double r = sqlite3_value_double(pVal);
88710      for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
88711        if( aSample[i].eType==SQLITE_NULL ) continue;
88712        if( aSample[i].eType>=SQLITE_TEXT || aSample[i].u.r>r ) break;
88713      }
88714    }else{
88715      sqlite3 *db = pParse->db;
88716      CollSeq *pColl;
88717      const u8 *z;
88718      int n;
88719
88720      /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
88721      assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
88722
88723      if( eType==SQLITE_BLOB ){
88724        z = (const u8 *)sqlite3_value_blob(pVal);
88725        pColl = db->pDfltColl;
88726        assert( pColl->enc==SQLITE_UTF8 );
88727      }else{
88728        pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
88729        if( pColl==0 ){
88730          sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
88731                          *pIdx->azColl);
88732          return SQLITE_ERROR;
88733        }
88734        z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
88735        if( !z ){
88736          return SQLITE_NOMEM;
88737        }
88738        assert( z && pColl && pColl->xCmp );
88739      }
88740      n = sqlite3ValueBytes(pVal, pColl->enc);
88741
88742      for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
88743        int r;
88744        int eSampletype = aSample[i].eType;
88745        if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
88746        if( (eSampletype!=eType) ) break;
88747#ifndef SQLITE_OMIT_UTF16
88748        if( pColl->enc!=SQLITE_UTF8 ){
88749          int nSample;
88750          char *zSample = sqlite3Utf8to16(
88751              db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
88752          );
88753          if( !zSample ){
88754            assert( db->mallocFailed );
88755            return SQLITE_NOMEM;
88756          }
88757          r = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
88758          sqlite3DbFree(db, zSample);
88759        }else
88760#endif
88761        {
88762          r = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
88763        }
88764        if( r>0 ) break;
88765      }
88766    }
88767
88768    assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
88769    *piRegion = i;
88770  }
88771  return SQLITE_OK;
88772}
88773#endif   /* #ifdef SQLITE_ENABLE_STAT2 */
88774
88775/*
88776** If expression pExpr represents a literal value, set *pp to point to
88777** an sqlite3_value structure containing the same value, with affinity
88778** aff applied to it, before returning. It is the responsibility of the
88779** caller to eventually release this structure by passing it to
88780** sqlite3ValueFree().
88781**
88782** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
88783** is an SQL variable that currently has a non-NULL value bound to it,
88784** create an sqlite3_value structure containing this value, again with
88785** affinity aff applied to it, instead.
88786**
88787** If neither of the above apply, set *pp to NULL.
88788**
88789** If an error occurs, return an error code. Otherwise, SQLITE_OK.
88790*/
88791#ifdef SQLITE_ENABLE_STAT2
88792static int valueFromExpr(
88793  Parse *pParse,
88794  Expr *pExpr,
88795  u8 aff,
88796  sqlite3_value **pp
88797){
88798  /* The evalConstExpr() function will have already converted any TK_VARIABLE
88799  ** expression involved in an comparison into a TK_REGISTER. */
88800  assert( pExpr->op!=TK_VARIABLE );
88801  if( pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE ){
88802    int iVar = pExpr->iColumn;
88803    sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
88804    *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
88805    return SQLITE_OK;
88806  }
88807  return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
88808}
88809#endif
88810
88811/*
88812** This function is used to estimate the number of rows that will be visited
88813** by scanning an index for a range of values. The range may have an upper
88814** bound, a lower bound, or both. The WHERE clause terms that set the upper
88815** and lower bounds are represented by pLower and pUpper respectively. For
88816** example, assuming that index p is on t1(a):
88817**
88818**   ... FROM t1 WHERE a > ? AND a < ? ...
88819**                    |_____|   |_____|
88820**                       |         |
88821**                     pLower    pUpper
88822**
88823** If either of the upper or lower bound is not present, then NULL is passed in
88824** place of the corresponding WhereTerm.
88825**
88826** The nEq parameter is passed the index of the index column subject to the
88827** range constraint. Or, equivalently, the number of equality constraints
88828** optimized by the proposed index scan. For example, assuming index p is
88829** on t1(a, b), and the SQL query is:
88830**
88831**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
88832**
88833** then nEq should be passed the value 1 (as the range restricted column,
88834** b, is the second left-most column of the index). Or, if the query is:
88835**
88836**   ... FROM t1 WHERE a > ? AND a < ? ...
88837**
88838** then nEq should be passed 0.
88839**
88840** The returned value is an integer between 1 and 100, inclusive. A return
88841** value of 1 indicates that the proposed range scan is expected to visit
88842** approximately 1/100th (1%) of the rows selected by the nEq equality
88843** constraints (if any). A return value of 100 indicates that it is expected
88844** that the range scan will visit every row (100%) selected by the equality
88845** constraints.
88846**
88847** In the absence of sqlite_stat2 ANALYZE data, each range inequality
88848** reduces the search space by 2/3rds.  Hence a single constraint (x>?)
88849** results in a return of 33 and a range constraint (x>? AND x<?) results
88850** in a return of 11.
88851*/
88852static int whereRangeScanEst(
88853  Parse *pParse,       /* Parsing & code generating context */
88854  Index *p,            /* The index containing the range-compared column; "x" */
88855  int nEq,             /* index into p->aCol[] of the range-compared column */
88856  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
88857  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
88858  int *piEst           /* OUT: Return value */
88859){
88860  int rc = SQLITE_OK;
88861
88862#ifdef SQLITE_ENABLE_STAT2
88863
88864  if( nEq==0 && p->aSample ){
88865    sqlite3_value *pLowerVal = 0;
88866    sqlite3_value *pUpperVal = 0;
88867    int iEst;
88868    int iLower = 0;
88869    int iUpper = SQLITE_INDEX_SAMPLES;
88870    u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
88871
88872    if( pLower ){
88873      Expr *pExpr = pLower->pExpr->pRight;
88874      rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
88875    }
88876    if( rc==SQLITE_OK && pUpper ){
88877      Expr *pExpr = pUpper->pExpr->pRight;
88878      rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
88879    }
88880
88881    if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
88882      sqlite3ValueFree(pLowerVal);
88883      sqlite3ValueFree(pUpperVal);
88884      goto range_est_fallback;
88885    }else if( pLowerVal==0 ){
88886      rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
88887      if( pLower ) iLower = iUpper/2;
88888    }else if( pUpperVal==0 ){
88889      rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
88890      if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
88891    }else{
88892      rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
88893      if( rc==SQLITE_OK ){
88894        rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
88895      }
88896    }
88897
88898    iEst = iUpper - iLower;
88899    testcase( iEst==SQLITE_INDEX_SAMPLES );
88900    assert( iEst<=SQLITE_INDEX_SAMPLES );
88901    if( iEst<1 ){
88902      iEst = 1;
88903    }
88904
88905    sqlite3ValueFree(pLowerVal);
88906    sqlite3ValueFree(pUpperVal);
88907    *piEst = (iEst * 100)/SQLITE_INDEX_SAMPLES;
88908    return rc;
88909  }
88910range_est_fallback:
88911#else
88912  UNUSED_PARAMETER(pParse);
88913  UNUSED_PARAMETER(p);
88914  UNUSED_PARAMETER(nEq);
88915#endif
88916  assert( pLower || pUpper );
88917  if( pLower && pUpper ){
88918    *piEst = 11;
88919  }else{
88920    *piEst = 33;
88921  }
88922  return rc;
88923}
88924
88925
88926/*
88927** Find the query plan for accessing a particular table.  Write the
88928** best query plan and its cost into the WhereCost object supplied as the
88929** last parameter.
88930**
88931** The lowest cost plan wins.  The cost is an estimate of the amount of
88932** CPU and disk I/O need to process the request using the selected plan.
88933** Factors that influence cost include:
88934**
88935**    *  The estimated number of rows that will be retrieved.  (The
88936**       fewer the better.)
88937**
88938**    *  Whether or not sorting must occur.
88939**
88940**    *  Whether or not there must be separate lookups in the
88941**       index and in the main table.
88942**
88943** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
88944** the SQL statement, then this function only considers plans using the
88945** named index. If no such plan is found, then the returned cost is
88946** SQLITE_BIG_DBL. If a plan is found that uses the named index,
88947** then the cost is calculated in the usual way.
88948**
88949** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
88950** in the SELECT statement, then no indexes are considered. However, the
88951** selected plan may still take advantage of the tables built-in rowid
88952** index.
88953*/
88954static void bestBtreeIndex(
88955  Parse *pParse,              /* The parsing context */
88956  WhereClause *pWC,           /* The WHERE clause */
88957  struct SrcList_item *pSrc,  /* The FROM clause term to search */
88958  Bitmask notReady,           /* Mask of cursors that are not available */
88959  ExprList *pOrderBy,         /* The ORDER BY clause */
88960  WhereCost *pCost            /* Lowest cost query plan */
88961){
88962  int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
88963  Index *pProbe;              /* An index we are evaluating */
88964  Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
88965  int eqTermMask;             /* Current mask of valid equality operators */
88966  int idxEqTermMask;          /* Index mask of valid equality operators */
88967  Index sPk;                  /* A fake index object for the primary key */
88968  unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
88969  int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
88970  int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
88971
88972  /* Initialize the cost to a worst-case value */
88973  memset(pCost, 0, sizeof(*pCost));
88974  pCost->rCost = SQLITE_BIG_DBL;
88975
88976  /* If the pSrc table is the right table of a LEFT JOIN then we may not
88977  ** use an index to satisfy IS NULL constraints on that table.  This is
88978  ** because columns might end up being NULL if the table does not match -
88979  ** a circumstance which the index cannot help us discover.  Ticket #2177.
88980  */
88981  if( pSrc->jointype & JT_LEFT ){
88982    idxEqTermMask = WO_EQ|WO_IN;
88983  }else{
88984    idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
88985  }
88986
88987  if( pSrc->pIndex ){
88988    /* An INDEXED BY clause specifies a particular index to use */
88989    pIdx = pProbe = pSrc->pIndex;
88990    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
88991    eqTermMask = idxEqTermMask;
88992  }else{
88993    /* There is no INDEXED BY clause.  Create a fake Index object to
88994    ** represent the primary key */
88995    Index *pFirst;                /* Any other index on the table */
88996    memset(&sPk, 0, sizeof(Index));
88997    sPk.nColumn = 1;
88998    sPk.aiColumn = &aiColumnPk;
88999    sPk.aiRowEst = aiRowEstPk;
89000    aiRowEstPk[1] = 1;
89001    sPk.onError = OE_Replace;
89002    sPk.pTable = pSrc->pTab;
89003    pFirst = pSrc->pTab->pIndex;
89004    if( pSrc->notIndexed==0 ){
89005      sPk.pNext = pFirst;
89006    }
89007    /* The aiRowEstPk[0] is an estimate of the total number of rows in the
89008    ** table.  Get this information from the ANALYZE information if it is
89009    ** available.  If not available, assume the table 1 million rows in size.
89010    */
89011    if( pFirst ){
89012      assert( pFirst->aiRowEst!=0 ); /* Allocated together with pFirst */
89013      aiRowEstPk[0] = pFirst->aiRowEst[0];
89014    }else{
89015      aiRowEstPk[0] = 1000000;
89016    }
89017    pProbe = &sPk;
89018    wsFlagMask = ~(
89019        WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
89020    );
89021    eqTermMask = WO_EQ|WO_IN;
89022    pIdx = 0;
89023  }
89024
89025  /* Loop over all indices looking for the best one to use
89026  */
89027  for(; pProbe; pIdx=pProbe=pProbe->pNext){
89028    const unsigned int * const aiRowEst = pProbe->aiRowEst;
89029    double cost;                /* Cost of using pProbe */
89030    double nRow;                /* Estimated number of rows in result set */
89031    int rev;                    /* True to scan in reverse order */
89032    int wsFlags = 0;
89033    Bitmask used = 0;
89034
89035    /* The following variables are populated based on the properties of
89036    ** scan being evaluated. They are then used to determine the expected
89037    ** cost and number of rows returned.
89038    **
89039    **  nEq:
89040    **    Number of equality terms that can be implemented using the index.
89041    **
89042    **  nInMul:
89043    **    The "in-multiplier". This is an estimate of how many seek operations
89044    **    SQLite must perform on the index in question. For example, if the
89045    **    WHERE clause is:
89046    **
89047    **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
89048    **
89049    **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is
89050    **    set to 9. Given the same schema and either of the following WHERE
89051    **    clauses:
89052    **
89053    **      WHERE a =  1
89054    **      WHERE a >= 2
89055    **
89056    **    nInMul is set to 1.
89057    **
89058    **    If there exists a WHERE term of the form "x IN (SELECT ...)", then
89059    **    the sub-select is assumed to return 25 rows for the purposes of
89060    **    determining nInMul.
89061    **
89062    **  bInEst:
89063    **    Set to true if there was at least one "x IN (SELECT ...)" term used
89064    **    in determining the value of nInMul.
89065    **
89066    **  nBound:
89067    **    An estimate on the amount of the table that must be searched.  A
89068    **    value of 100 means the entire table is searched.  Range constraints
89069    **    might reduce this to a value less than 100 to indicate that only
89070    **    a fraction of the table needs searching.  In the absence of
89071    **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
89072    **    space to 1/3rd its original size.  So an x>? constraint reduces
89073    **    nBound to 33.  Two constraints (x>? AND x<?) reduce nBound to 11.
89074    **
89075    **  bSort:
89076    **    Boolean. True if there is an ORDER BY clause that will require an
89077    **    external sort (i.e. scanning the index being evaluated will not
89078    **    correctly order records).
89079    **
89080    **  bLookup:
89081    **    Boolean. True if for each index entry visited a lookup on the
89082    **    corresponding table b-tree is required. This is always false
89083    **    for the rowid index. For other indexes, it is true unless all the
89084    **    columns of the table used by the SELECT statement are present in
89085    **    the index (such an index is sometimes described as a covering index).
89086    **    For example, given the index on (a, b), the second of the following
89087    **    two queries requires table b-tree lookups, but the first does not.
89088    **
89089    **             SELECT a, b    FROM tbl WHERE a = 1;
89090    **             SELECT a, b, c FROM tbl WHERE a = 1;
89091    */
89092    int nEq;
89093    int bInEst = 0;
89094    int nInMul = 1;
89095    int nBound = 100;
89096    int bSort = 0;
89097    int bLookup = 0;
89098
89099    /* Determine the values of nEq and nInMul */
89100    for(nEq=0; nEq<pProbe->nColumn; nEq++){
89101      WhereTerm *pTerm;           /* A single term of the WHERE clause */
89102      int j = pProbe->aiColumn[nEq];
89103      pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
89104      if( pTerm==0 ) break;
89105      wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
89106      if( pTerm->eOperator & WO_IN ){
89107        Expr *pExpr = pTerm->pExpr;
89108        wsFlags |= WHERE_COLUMN_IN;
89109        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
89110          nInMul *= 25;
89111          bInEst = 1;
89112        }else if( pExpr->x.pList ){
89113          nInMul *= pExpr->x.pList->nExpr + 1;
89114        }
89115      }else if( pTerm->eOperator & WO_ISNULL ){
89116        wsFlags |= WHERE_COLUMN_NULL;
89117      }
89118      used |= pTerm->prereqRight;
89119    }
89120
89121    /* Determine the value of nBound. */
89122    if( nEq<pProbe->nColumn ){
89123      int j = pProbe->aiColumn[nEq];
89124      if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
89125        WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
89126        WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
89127        whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &nBound);
89128        if( pTop ){
89129          wsFlags |= WHERE_TOP_LIMIT;
89130          used |= pTop->prereqRight;
89131        }
89132        if( pBtm ){
89133          wsFlags |= WHERE_BTM_LIMIT;
89134          used |= pBtm->prereqRight;
89135        }
89136        wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
89137      }
89138    }else if( pProbe->onError!=OE_None ){
89139      testcase( wsFlags & WHERE_COLUMN_IN );
89140      testcase( wsFlags & WHERE_COLUMN_NULL );
89141      if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
89142        wsFlags |= WHERE_UNIQUE;
89143      }
89144    }
89145
89146    /* If there is an ORDER BY clause and the index being considered will
89147    ** naturally scan rows in the required order, set the appropriate flags
89148    ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
89149    ** will scan rows in a different order, set the bSort variable.  */
89150    if( pOrderBy ){
89151      if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0
89152        && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
89153      ){
89154        wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
89155        wsFlags |= (rev ? WHERE_REVERSE : 0);
89156      }else{
89157        bSort = 1;
89158      }
89159    }
89160
89161    /* If currently calculating the cost of using an index (not the IPK
89162    ** index), determine if all required column data may be obtained without
89163    ** seeking to entries in the main table (i.e. if the index is a covering
89164    ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
89165    ** wsFlags. Otherwise, set the bLookup variable to true.  */
89166    if( pIdx && wsFlags ){
89167      Bitmask m = pSrc->colUsed;
89168      int j;
89169      for(j=0; j<pIdx->nColumn; j++){
89170        int x = pIdx->aiColumn[j];
89171        if( x<BMS-1 ){
89172          m &= ~(((Bitmask)1)<<x);
89173        }
89174      }
89175      if( m==0 ){
89176        wsFlags |= WHERE_IDX_ONLY;
89177      }else{
89178        bLookup = 1;
89179      }
89180    }
89181
89182    /**** Begin adding up the cost of using this index (Needs improvements)
89183    **
89184    ** Estimate the number of rows of output.  For an IN operator,
89185    ** do not let the estimate exceed half the rows in the table.
89186    */
89187    nRow = (double)(aiRowEst[nEq] * nInMul);
89188    if( bInEst && nRow*2>aiRowEst[0] ){
89189      nRow = aiRowEst[0]/2;
89190      nInMul = (int)(nRow / aiRowEst[nEq]);
89191    }
89192
89193    /* Assume constant cost to access a row and logarithmic cost to
89194    ** do a binary search.  Hence, the initial cost is the number of output
89195    ** rows plus log2(table-size) times the number of binary searches.
89196    */
89197    cost = nRow + nInMul*estLog(aiRowEst[0]);
89198
89199    /* Adjust the number of rows and the cost downward to reflect rows
89200    ** that are excluded by range constraints.
89201    */
89202    nRow = (nRow * (double)nBound) / (double)100;
89203    cost = (cost * (double)nBound) / (double)100;
89204
89205    /* Add in the estimated cost of sorting the result
89206    */
89207    if( bSort ){
89208      cost += cost*estLog(cost);
89209    }
89210
89211    /* If all information can be taken directly from the index, we avoid
89212    ** doing table lookups.  This reduces the cost by half.  (Not really -
89213    ** this needs to be fixed.)
89214    */
89215    if( pIdx && bLookup==0 ){
89216      cost /= (double)2;
89217    }
89218    /**** Cost of using this index has now been computed ****/
89219
89220    WHERETRACE((
89221      "tbl=%s idx=%s nEq=%d nInMul=%d nBound=%d bSort=%d bLookup=%d"
89222      " wsFlags=%d   (nRow=%.2f cost=%.2f)\n",
89223      pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"),
89224      nEq, nInMul, nBound, bSort, bLookup, wsFlags, nRow, cost
89225    ));
89226
89227    /* If this index is the best we have seen so far, then record this
89228    ** index and its cost in the pCost structure.
89229    */
89230    if( (!pIdx || wsFlags) && cost<pCost->rCost ){
89231      pCost->rCost = cost;
89232      pCost->nRow = nRow;
89233      pCost->used = used;
89234      pCost->plan.wsFlags = (wsFlags&wsFlagMask);
89235      pCost->plan.nEq = nEq;
89236      pCost->plan.u.pIdx = pIdx;
89237    }
89238
89239    /* If there was an INDEXED BY clause, then only that one index is
89240    ** considered. */
89241    if( pSrc->pIndex ) break;
89242
89243    /* Reset masks for the next index in the loop */
89244    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
89245    eqTermMask = idxEqTermMask;
89246  }
89247
89248  /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
89249  ** is set, then reverse the order that the index will be scanned
89250  ** in. This is used for application testing, to help find cases
89251  ** where application behaviour depends on the (undefined) order that
89252  ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
89253  if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
89254    pCost->plan.wsFlags |= WHERE_REVERSE;
89255  }
89256
89257  assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
89258  assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
89259  assert( pSrc->pIndex==0
89260       || pCost->plan.u.pIdx==0
89261       || pCost->plan.u.pIdx==pSrc->pIndex
89262  );
89263
89264  WHERETRACE(("best index is: %s\n",
89265    (pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
89266  ));
89267
89268  bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
89269  pCost->plan.wsFlags |= eqTermMask;
89270}
89271
89272/*
89273** Find the query plan for accessing table pSrc->pTab. Write the
89274** best query plan and its cost into the WhereCost object supplied
89275** as the last parameter. This function may calculate the cost of
89276** both real and virtual table scans.
89277*/
89278static void bestIndex(
89279  Parse *pParse,              /* The parsing context */
89280  WhereClause *pWC,           /* The WHERE clause */
89281  struct SrcList_item *pSrc,  /* The FROM clause term to search */
89282  Bitmask notReady,           /* Mask of cursors that are not available */
89283  ExprList *pOrderBy,         /* The ORDER BY clause */
89284  WhereCost *pCost            /* Lowest cost query plan */
89285){
89286#ifndef SQLITE_OMIT_VIRTUALTABLE
89287  if( IsVirtual(pSrc->pTab) ){
89288    sqlite3_index_info *p = 0;
89289    bestVirtualIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost, &p);
89290    if( p->needToFreeIdxStr ){
89291      sqlite3_free(p->idxStr);
89292    }
89293    sqlite3DbFree(pParse->db, p);
89294  }else
89295#endif
89296  {
89297    bestBtreeIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
89298  }
89299}
89300
89301/*
89302** Disable a term in the WHERE clause.  Except, do not disable the term
89303** if it controls a LEFT OUTER JOIN and it did not originate in the ON
89304** or USING clause of that join.
89305**
89306** Consider the term t2.z='ok' in the following queries:
89307**
89308**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
89309**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
89310**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
89311**
89312** The t2.z='ok' is disabled in the in (2) because it originates
89313** in the ON clause.  The term is disabled in (3) because it is not part
89314** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
89315**
89316** Disabling a term causes that term to not be tested in the inner loop
89317** of the join.  Disabling is an optimization.  When terms are satisfied
89318** by indices, we disable them to prevent redundant tests in the inner
89319** loop.  We would get the correct results if nothing were ever disabled,
89320** but joins might run a little slower.  The trick is to disable as much
89321** as we can without disabling too much.  If we disabled in (1), we'd get
89322** the wrong answer.  See ticket #813.
89323*/
89324static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
89325  if( pTerm
89326      && ALWAYS((pTerm->wtFlags & TERM_CODED)==0)
89327      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
89328  ){
89329    pTerm->wtFlags |= TERM_CODED;
89330    if( pTerm->iParent>=0 ){
89331      WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
89332      if( (--pOther->nChild)==0 ){
89333        disableTerm(pLevel, pOther);
89334      }
89335    }
89336  }
89337}
89338
89339/*
89340** Code an OP_Affinity opcode to apply the column affinity string zAff
89341** to the n registers starting at base.
89342**
89343** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
89344** beginning and end of zAff are ignored.  If all entries in zAff are
89345** SQLITE_AFF_NONE, then no code gets generated.
89346**
89347** This routine makes its own copy of zAff so that the caller is free
89348** to modify zAff after this routine returns.
89349*/
89350static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
89351  Vdbe *v = pParse->pVdbe;
89352  if( zAff==0 ){
89353    assert( pParse->db->mallocFailed );
89354    return;
89355  }
89356  assert( v!=0 );
89357
89358  /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
89359  ** and end of the affinity string.
89360  */
89361  while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
89362    n--;
89363    base++;
89364    zAff++;
89365  }
89366  while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
89367    n--;
89368  }
89369
89370  /* Code the OP_Affinity opcode if there is anything left to do. */
89371  if( n>0 ){
89372    sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
89373    sqlite3VdbeChangeP4(v, -1, zAff, n);
89374    sqlite3ExprCacheAffinityChange(pParse, base, n);
89375  }
89376}
89377
89378
89379/*
89380** Generate code for a single equality term of the WHERE clause.  An equality
89381** term can be either X=expr or X IN (...).   pTerm is the term to be
89382** coded.
89383**
89384** The current value for the constraint is left in register iReg.
89385**
89386** For a constraint of the form X=expr, the expression is evaluated and its
89387** result is left on the stack.  For constraints of the form X IN (...)
89388** this routine sets up a loop that will iterate over all values of X.
89389*/
89390static int codeEqualityTerm(
89391  Parse *pParse,      /* The parsing context */
89392  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
89393  WhereLevel *pLevel, /* When level of the FROM clause we are working on */
89394  int iTarget         /* Attempt to leave results in this register */
89395){
89396  Expr *pX = pTerm->pExpr;
89397  Vdbe *v = pParse->pVdbe;
89398  int iReg;                  /* Register holding results */
89399
89400  assert( iTarget>0 );
89401  if( pX->op==TK_EQ ){
89402    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
89403  }else if( pX->op==TK_ISNULL ){
89404    iReg = iTarget;
89405    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
89406#ifndef SQLITE_OMIT_SUBQUERY
89407  }else{
89408    int eType;
89409    int iTab;
89410    struct InLoop *pIn;
89411
89412    assert( pX->op==TK_IN );
89413    iReg = iTarget;
89414    eType = sqlite3FindInIndex(pParse, pX, 0);
89415    iTab = pX->iTable;
89416    sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
89417    assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
89418    if( pLevel->u.in.nIn==0 ){
89419      pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
89420    }
89421    pLevel->u.in.nIn++;
89422    pLevel->u.in.aInLoop =
89423       sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
89424                              sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
89425    pIn = pLevel->u.in.aInLoop;
89426    if( pIn ){
89427      pIn += pLevel->u.in.nIn - 1;
89428      pIn->iCur = iTab;
89429      if( eType==IN_INDEX_ROWID ){
89430        pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
89431      }else{
89432        pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
89433      }
89434      sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
89435    }else{
89436      pLevel->u.in.nIn = 0;
89437    }
89438#endif
89439  }
89440  disableTerm(pLevel, pTerm);
89441  return iReg;
89442}
89443
89444/*
89445** Generate code that will evaluate all == and IN constraints for an
89446** index.
89447**
89448** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
89449** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
89450** The index has as many as three equality constraints, but in this
89451** example, the third "c" value is an inequality.  So only two
89452** constraints are coded.  This routine will generate code to evaluate
89453** a==5 and b IN (1,2,3).  The current values for a and b will be stored
89454** in consecutive registers and the index of the first register is returned.
89455**
89456** In the example above nEq==2.  But this subroutine works for any value
89457** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
89458** The only thing it does is allocate the pLevel->iMem memory cell and
89459** compute the affinity string.
89460**
89461** This routine always allocates at least one memory cell and returns
89462** the index of that memory cell. The code that
89463** calls this routine will use that memory cell to store the termination
89464** key value of the loop.  If one or more IN operators appear, then
89465** this routine allocates an additional nEq memory cells for internal
89466** use.
89467**
89468** Before returning, *pzAff is set to point to a buffer containing a
89469** copy of the column affinity string of the index allocated using
89470** sqlite3DbMalloc(). Except, entries in the copy of the string associated
89471** with equality constraints that use NONE affinity are set to
89472** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
89473**
89474**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
89475**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
89476**
89477** In the example above, the index on t1(a) has TEXT affinity. But since
89478** the right hand side of the equality constraint (t2.b) has NONE affinity,
89479** no conversion should be attempted before using a t2.b value as part of
89480** a key to search the index. Hence the first byte in the returned affinity
89481** string in this example would be set to SQLITE_AFF_NONE.
89482*/
89483static int codeAllEqualityTerms(
89484  Parse *pParse,        /* Parsing context */
89485  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
89486  WhereClause *pWC,     /* The WHERE clause */
89487  Bitmask notReady,     /* Which parts of FROM have not yet been coded */
89488  int nExtraReg,        /* Number of extra registers to allocate */
89489  char **pzAff          /* OUT: Set to point to affinity string */
89490){
89491  int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
89492  Vdbe *v = pParse->pVdbe;      /* The vm under construction */
89493  Index *pIdx;                  /* The index being used for this loop */
89494  int iCur = pLevel->iTabCur;   /* The cursor of the table */
89495  WhereTerm *pTerm;             /* A single constraint term */
89496  int j;                        /* Loop counter */
89497  int regBase;                  /* Base register */
89498  int nReg;                     /* Number of registers to allocate */
89499  char *zAff;                   /* Affinity string to return */
89500
89501  /* This module is only called on query plans that use an index. */
89502  assert( pLevel->plan.wsFlags & WHERE_INDEXED );
89503  pIdx = pLevel->plan.u.pIdx;
89504
89505  /* Figure out how many memory cells we will need then allocate them.
89506  */
89507  regBase = pParse->nMem + 1;
89508  nReg = pLevel->plan.nEq + nExtraReg;
89509  pParse->nMem += nReg;
89510
89511  zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
89512  if( !zAff ){
89513    pParse->db->mallocFailed = 1;
89514  }
89515
89516  /* Evaluate the equality constraints
89517  */
89518  assert( pIdx->nColumn>=nEq );
89519  for(j=0; j<nEq; j++){
89520    int r1;
89521    int k = pIdx->aiColumn[j];
89522    pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
89523    if( NEVER(pTerm==0) ) break;
89524    assert( (pTerm->wtFlags & TERM_CODED)==0 );
89525    r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
89526    if( r1!=regBase+j ){
89527      if( nReg==1 ){
89528        sqlite3ReleaseTempReg(pParse, regBase);
89529        regBase = r1;
89530      }else{
89531        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
89532      }
89533    }
89534    testcase( pTerm->eOperator & WO_ISNULL );
89535    testcase( pTerm->eOperator & WO_IN );
89536    if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
89537      Expr *pRight = pTerm->pExpr->pRight;
89538      sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
89539      if( zAff ){
89540        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
89541          zAff[j] = SQLITE_AFF_NONE;
89542        }
89543        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
89544          zAff[j] = SQLITE_AFF_NONE;
89545        }
89546      }
89547    }
89548  }
89549  *pzAff = zAff;
89550  return regBase;
89551}
89552
89553/*
89554** Generate code for the start of the iLevel-th loop in the WHERE clause
89555** implementation described by pWInfo.
89556*/
89557static Bitmask codeOneLoopStart(
89558  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
89559  int iLevel,          /* Which level of pWInfo->a[] should be coded */
89560  u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
89561  Bitmask notReady     /* Which tables are currently available */
89562){
89563  int j, k;            /* Loop counters */
89564  int iCur;            /* The VDBE cursor for the table */
89565  int addrNxt;         /* Where to jump to continue with the next IN case */
89566  int omitTable;       /* True if we use the index only */
89567  int bRev;            /* True if we need to scan in reverse order */
89568  WhereLevel *pLevel;  /* The where level to be coded */
89569  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
89570  WhereTerm *pTerm;               /* A WHERE clause term */
89571  Parse *pParse;                  /* Parsing context */
89572  Vdbe *v;                        /* The prepared stmt under constructions */
89573  struct SrcList_item *pTabItem;  /* FROM clause term being coded */
89574  int addrBrk;                    /* Jump here to break out of the loop */
89575  int addrCont;                   /* Jump here to continue with next cycle */
89576  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
89577  int iReleaseReg = 0;      /* Temp register to free before returning */
89578
89579  pParse = pWInfo->pParse;
89580  v = pParse->pVdbe;
89581  pWC = pWInfo->pWC;
89582  pLevel = &pWInfo->a[iLevel];
89583  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
89584  iCur = pTabItem->iCursor;
89585  bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
89586  omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
89587           && (wctrlFlags & WHERE_FORCE_TABLE)==0;
89588
89589  /* Create labels for the "break" and "continue" instructions
89590  ** for the current loop.  Jump to addrBrk to break out of a loop.
89591  ** Jump to cont to go immediately to the next iteration of the
89592  ** loop.
89593  **
89594  ** When there is an IN operator, we also have a "addrNxt" label that
89595  ** means to continue with the next IN value combination.  When
89596  ** there are no IN operators in the constraints, the "addrNxt" label
89597  ** is the same as "addrBrk".
89598  */
89599  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
89600  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
89601
89602  /* If this is the right table of a LEFT OUTER JOIN, allocate and
89603  ** initialize a memory cell that records if this table matches any
89604  ** row of the left table of the join.
89605  */
89606  if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
89607    pLevel->iLeftJoin = ++pParse->nMem;
89608    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
89609    VdbeComment((v, "init LEFT JOIN no-match flag"));
89610  }
89611
89612#ifndef SQLITE_OMIT_VIRTUALTABLE
89613  if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
89614    /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
89615    **          to access the data.
89616    */
89617    int iReg;   /* P3 Value for OP_VFilter */
89618    sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
89619    int nConstraint = pVtabIdx->nConstraint;
89620    struct sqlite3_index_constraint_usage *aUsage =
89621                                                pVtabIdx->aConstraintUsage;
89622    const struct sqlite3_index_constraint *aConstraint =
89623                                                pVtabIdx->aConstraint;
89624
89625    sqlite3ExprCachePush(pParse);
89626    iReg = sqlite3GetTempRange(pParse, nConstraint+2);
89627    for(j=1; j<=nConstraint; j++){
89628      for(k=0; k<nConstraint; k++){
89629        if( aUsage[k].argvIndex==j ){
89630          int iTerm = aConstraint[k].iTermOffset;
89631          sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
89632          break;
89633        }
89634      }
89635      if( k==nConstraint ) break;
89636    }
89637    sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
89638    sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
89639    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
89640                      pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
89641    pVtabIdx->needToFreeIdxStr = 0;
89642    for(j=0; j<nConstraint; j++){
89643      if( aUsage[j].omit ){
89644        int iTerm = aConstraint[j].iTermOffset;
89645        disableTerm(pLevel, &pWC->a[iTerm]);
89646      }
89647    }
89648    pLevel->op = OP_VNext;
89649    pLevel->p1 = iCur;
89650    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
89651    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
89652    sqlite3ExprCachePop(pParse, 1);
89653  }else
89654#endif /* SQLITE_OMIT_VIRTUALTABLE */
89655
89656  if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
89657    /* Case 1:  We can directly reference a single row using an
89658    **          equality comparison against the ROWID field.  Or
89659    **          we reference multiple rows using a "rowid IN (...)"
89660    **          construct.
89661    */
89662    iReleaseReg = sqlite3GetTempReg(pParse);
89663    pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
89664    assert( pTerm!=0 );
89665    assert( pTerm->pExpr!=0 );
89666    assert( pTerm->leftCursor==iCur );
89667    assert( omitTable==0 );
89668    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
89669    addrNxt = pLevel->addrNxt;
89670    sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
89671    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
89672    sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
89673    VdbeComment((v, "pk"));
89674    pLevel->op = OP_Noop;
89675  }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
89676    /* Case 2:  We have an inequality comparison against the ROWID field.
89677    */
89678    int testOp = OP_Noop;
89679    int start;
89680    int memEndValue = 0;
89681    WhereTerm *pStart, *pEnd;
89682
89683    assert( omitTable==0 );
89684    pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
89685    pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
89686    if( bRev ){
89687      pTerm = pStart;
89688      pStart = pEnd;
89689      pEnd = pTerm;
89690    }
89691    if( pStart ){
89692      Expr *pX;             /* The expression that defines the start bound */
89693      int r1, rTemp;        /* Registers for holding the start boundary */
89694
89695      /* The following constant maps TK_xx codes into corresponding
89696      ** seek opcodes.  It depends on a particular ordering of TK_xx
89697      */
89698      const u8 aMoveOp[] = {
89699           /* TK_GT */  OP_SeekGt,
89700           /* TK_LE */  OP_SeekLe,
89701           /* TK_LT */  OP_SeekLt,
89702           /* TK_GE */  OP_SeekGe
89703      };
89704      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
89705      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
89706      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
89707
89708      pX = pStart->pExpr;
89709      assert( pX!=0 );
89710      assert( pStart->leftCursor==iCur );
89711      r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
89712      sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
89713      VdbeComment((v, "pk"));
89714      sqlite3ExprCacheAffinityChange(pParse, r1, 1);
89715      sqlite3ReleaseTempReg(pParse, rTemp);
89716      disableTerm(pLevel, pStart);
89717    }else{
89718      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
89719    }
89720    if( pEnd ){
89721      Expr *pX;
89722      pX = pEnd->pExpr;
89723      assert( pX!=0 );
89724      assert( pEnd->leftCursor==iCur );
89725      memEndValue = ++pParse->nMem;
89726      sqlite3ExprCode(pParse, pX->pRight, memEndValue);
89727      if( pX->op==TK_LT || pX->op==TK_GT ){
89728        testOp = bRev ? OP_Le : OP_Ge;
89729      }else{
89730        testOp = bRev ? OP_Lt : OP_Gt;
89731      }
89732      disableTerm(pLevel, pEnd);
89733    }
89734    start = sqlite3VdbeCurrentAddr(v);
89735    pLevel->op = bRev ? OP_Prev : OP_Next;
89736    pLevel->p1 = iCur;
89737    pLevel->p2 = start;
89738    pLevel->p5 = (pStart==0 && pEnd==0) ?1:0;
89739    if( testOp!=OP_Noop ){
89740      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
89741      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
89742      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
89743      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
89744      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
89745    }
89746  }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
89747    /* Case 3: A scan using an index.
89748    **
89749    **         The WHERE clause may contain zero or more equality
89750    **         terms ("==" or "IN" operators) that refer to the N
89751    **         left-most columns of the index. It may also contain
89752    **         inequality constraints (>, <, >= or <=) on the indexed
89753    **         column that immediately follows the N equalities. Only
89754    **         the right-most column can be an inequality - the rest must
89755    **         use the "==" and "IN" operators. For example, if the
89756    **         index is on (x,y,z), then the following clauses are all
89757    **         optimized:
89758    **
89759    **            x=5
89760    **            x=5 AND y=10
89761    **            x=5 AND y<10
89762    **            x=5 AND y>5 AND y<10
89763    **            x=5 AND y=5 AND z<=10
89764    **
89765    **         The z<10 term of the following cannot be used, only
89766    **         the x=5 term:
89767    **
89768    **            x=5 AND z<10
89769    **
89770    **         N may be zero if there are inequality constraints.
89771    **         If there are no inequality constraints, then N is at
89772    **         least one.
89773    **
89774    **         This case is also used when there are no WHERE clause
89775    **         constraints but an index is selected anyway, in order
89776    **         to force the output order to conform to an ORDER BY.
89777    */
89778    int aStartOp[] = {
89779      0,
89780      0,
89781      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
89782      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
89783      OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
89784      OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
89785      OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
89786      OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
89787    };
89788    int aEndOp[] = {
89789      OP_Noop,             /* 0: (!end_constraints) */
89790      OP_IdxGE,            /* 1: (end_constraints && !bRev) */
89791      OP_IdxLT             /* 2: (end_constraints && bRev) */
89792    };
89793    int nEq = pLevel->plan.nEq;
89794    int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
89795    int regBase;                 /* Base register holding constraint values */
89796    int r1;                      /* Temp register */
89797    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
89798    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
89799    int startEq;                 /* True if range start uses ==, >= or <= */
89800    int endEq;                   /* True if range end uses ==, >= or <= */
89801    int start_constraints;       /* Start of range is constrained */
89802    int nConstraint;             /* Number of constraint terms */
89803    Index *pIdx;         /* The index we will be using */
89804    int iIdxCur;         /* The VDBE cursor for the index */
89805    int nExtraReg = 0;   /* Number of extra registers needed */
89806    int op;              /* Instruction opcode */
89807    char *zAff;
89808
89809    pIdx = pLevel->plan.u.pIdx;
89810    iIdxCur = pLevel->iIdxCur;
89811    k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
89812
89813    /* If this loop satisfies a sort order (pOrderBy) request that
89814    ** was passed to this function to implement a "SELECT min(x) ..."
89815    ** query, then the caller will only allow the loop to run for
89816    ** a single iteration. This means that the first row returned
89817    ** should not have a NULL value stored in 'x'. If column 'x' is
89818    ** the first one after the nEq equality constraints in the index,
89819    ** this requires some special handling.
89820    */
89821    if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
89822     && (pLevel->plan.wsFlags&WHERE_ORDERBY)
89823     && (pIdx->nColumn>nEq)
89824    ){
89825      /* assert( pOrderBy->nExpr==1 ); */
89826      /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
89827      isMinQuery = 1;
89828      nExtraReg = 1;
89829    }
89830
89831    /* Find any inequality constraint terms for the start and end
89832    ** of the range.
89833    */
89834    if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
89835      pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
89836      nExtraReg = 1;
89837    }
89838    if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
89839      pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
89840      nExtraReg = 1;
89841    }
89842
89843    /* Generate code to evaluate all constraint terms using == or IN
89844    ** and store the values of those terms in an array of registers
89845    ** starting at regBase.
89846    */
89847    regBase = codeAllEqualityTerms(
89848        pParse, pLevel, pWC, notReady, nExtraReg, &zAff
89849    );
89850    addrNxt = pLevel->addrNxt;
89851
89852    /* If we are doing a reverse order scan on an ascending index, or
89853    ** a forward order scan on a descending index, interchange the
89854    ** start and end terms (pRangeStart and pRangeEnd).
89855    */
89856    if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
89857      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
89858    }
89859
89860    testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
89861    testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
89862    testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
89863    testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
89864    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
89865    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
89866    start_constraints = pRangeStart || nEq>0;
89867
89868    /* Seek the index cursor to the start of the range. */
89869    nConstraint = nEq;
89870    if( pRangeStart ){
89871      Expr *pRight = pRangeStart->pExpr->pRight;
89872      sqlite3ExprCode(pParse, pRight, regBase+nEq);
89873      sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
89874      if( zAff ){
89875        if( sqlite3CompareAffinity(pRight, zAff[nConstraint])==SQLITE_AFF_NONE){
89876          /* Since the comparison is to be performed with no conversions
89877          ** applied to the operands, set the affinity to apply to pRight to
89878          ** SQLITE_AFF_NONE.  */
89879          zAff[nConstraint] = SQLITE_AFF_NONE;
89880        }
89881        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[nConstraint]) ){
89882          zAff[nConstraint] = SQLITE_AFF_NONE;
89883        }
89884      }
89885      nConstraint++;
89886    }else if( isMinQuery ){
89887      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
89888      nConstraint++;
89889      startEq = 0;
89890      start_constraints = 1;
89891    }
89892    codeApplyAffinity(pParse, regBase, nConstraint, zAff);
89893    op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
89894    assert( op!=0 );
89895    testcase( op==OP_Rewind );
89896    testcase( op==OP_Last );
89897    testcase( op==OP_SeekGt );
89898    testcase( op==OP_SeekGe );
89899    testcase( op==OP_SeekLe );
89900    testcase( op==OP_SeekLt );
89901    sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
89902
89903    /* Load the value for the inequality constraint at the end of the
89904    ** range (if any).
89905    */
89906    nConstraint = nEq;
89907    if( pRangeEnd ){
89908      Expr *pRight = pRangeEnd->pExpr->pRight;
89909      sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
89910      sqlite3ExprCode(pParse, pRight, regBase+nEq);
89911      sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
89912      if( zAff ){
89913        if( sqlite3CompareAffinity(pRight, zAff[nConstraint])==SQLITE_AFF_NONE){
89914          /* Since the comparison is to be performed with no conversions
89915          ** applied to the operands, set the affinity to apply to pRight to
89916          ** SQLITE_AFF_NONE.  */
89917          zAff[nConstraint] = SQLITE_AFF_NONE;
89918        }
89919        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[nConstraint]) ){
89920          zAff[nConstraint] = SQLITE_AFF_NONE;
89921        }
89922      }
89923      codeApplyAffinity(pParse, regBase, nEq+1, zAff);
89924      nConstraint++;
89925    }
89926    sqlite3DbFree(pParse->db, zAff);
89927
89928    /* Top of the loop body */
89929    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
89930
89931    /* Check if the index cursor is past the end of the range. */
89932    op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
89933    testcase( op==OP_Noop );
89934    testcase( op==OP_IdxGE );
89935    testcase( op==OP_IdxLT );
89936    if( op!=OP_Noop ){
89937      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
89938      sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
89939    }
89940
89941    /* If there are inequality constraints, check that the value
89942    ** of the table column that the inequality contrains is not NULL.
89943    ** If it is, jump to the next iteration of the loop.
89944    */
89945    r1 = sqlite3GetTempReg(pParse);
89946    testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
89947    testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
89948    if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
89949      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
89950      sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
89951    }
89952    sqlite3ReleaseTempReg(pParse, r1);
89953
89954    /* Seek the table cursor, if required */
89955    disableTerm(pLevel, pRangeStart);
89956    disableTerm(pLevel, pRangeEnd);
89957    if( !omitTable ){
89958      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
89959      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
89960      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
89961      sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
89962    }
89963
89964    /* Record the instruction used to terminate the loop. Disable
89965    ** WHERE clause terms made redundant by the index range scan.
89966    */
89967    pLevel->op = bRev ? OP_Prev : OP_Next;
89968    pLevel->p1 = iIdxCur;
89969  }else
89970
89971#ifndef SQLITE_OMIT_OR_OPTIMIZATION
89972  if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
89973    /* Case 4:  Two or more separately indexed terms connected by OR
89974    **
89975    ** Example:
89976    **
89977    **   CREATE TABLE t1(a,b,c,d);
89978    **   CREATE INDEX i1 ON t1(a);
89979    **   CREATE INDEX i2 ON t1(b);
89980    **   CREATE INDEX i3 ON t1(c);
89981    **
89982    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
89983    **
89984    ** In the example, there are three indexed terms connected by OR.
89985    ** The top of the loop looks like this:
89986    **
89987    **          Null       1                # Zero the rowset in reg 1
89988    **
89989    ** Then, for each indexed term, the following. The arguments to
89990    ** RowSetTest are such that the rowid of the current row is inserted
89991    ** into the RowSet. If it is already present, control skips the
89992    ** Gosub opcode and jumps straight to the code generated by WhereEnd().
89993    **
89994    **        sqlite3WhereBegin(<term>)
89995    **          RowSetTest                  # Insert rowid into rowset
89996    **          Gosub      2 A
89997    **        sqlite3WhereEnd()
89998    **
89999    ** Following the above, code to terminate the loop. Label A, the target
90000    ** of the Gosub above, jumps to the instruction right after the Goto.
90001    **
90002    **          Null       1                # Zero the rowset in reg 1
90003    **          Goto       B                # The loop is finished.
90004    **
90005    **       A: <loop body>                 # Return data, whatever.
90006    **
90007    **          Return     2                # Jump back to the Gosub
90008    **
90009    **       B: <after the loop>
90010    **
90011    */
90012    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
90013    WhereTerm *pFinal;     /* Final subterm within the OR-clause. */
90014    SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
90015
90016    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
90017    int regRowset = 0;                        /* Register for RowSet object */
90018    int regRowid = 0;                         /* Register holding rowid */
90019    int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
90020    int iRetInit;                             /* Address of regReturn init */
90021    int untestedTerms = 0;             /* Some terms not completely tested */
90022    int ii;
90023
90024    pTerm = pLevel->plan.u.pTerm;
90025    assert( pTerm!=0 );
90026    assert( pTerm->eOperator==WO_OR );
90027    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
90028    pOrWc = &pTerm->u.pOrInfo->wc;
90029    pFinal = &pOrWc->a[pOrWc->nTerm-1];
90030    pLevel->op = OP_Return;
90031    pLevel->p1 = regReturn;
90032
90033    /* Set up a new SrcList ni pOrTab containing the table being scanned
90034    ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
90035    ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
90036    */
90037    if( pWInfo->nLevel>1 ){
90038      int nNotReady;                 /* The number of notReady tables */
90039      struct SrcList_item *origSrc;     /* Original list of tables */
90040      nNotReady = pWInfo->nLevel - iLevel - 1;
90041      pOrTab = sqlite3StackAllocRaw(pParse->db,
90042                            sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
90043      if( pOrTab==0 ) return notReady;
90044      pOrTab->nAlloc = (i16)(nNotReady + 1);
90045      pOrTab->nSrc = pOrTab->nAlloc;
90046      memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
90047      origSrc = pWInfo->pTabList->a;
90048      for(k=1; k<=nNotReady; k++){
90049        memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
90050      }
90051    }else{
90052      pOrTab = pWInfo->pTabList;
90053    }
90054
90055    /* Initialize the rowset register to contain NULL. An SQL NULL is
90056    ** equivalent to an empty rowset.
90057    **
90058    ** Also initialize regReturn to contain the address of the instruction
90059    ** immediately following the OP_Return at the bottom of the loop. This
90060    ** is required in a few obscure LEFT JOIN cases where control jumps
90061    ** over the top of the loop into the body of it. In this case the
90062    ** correct response for the end-of-loop code (the OP_Return) is to
90063    ** fall through to the next instruction, just as an OP_Next does if
90064    ** called on an uninitialized cursor.
90065    */
90066    if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
90067      regRowset = ++pParse->nMem;
90068      regRowid = ++pParse->nMem;
90069      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
90070    }
90071    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
90072
90073    for(ii=0; ii<pOrWc->nTerm; ii++){
90074      WhereTerm *pOrTerm = &pOrWc->a[ii];
90075      if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
90076        WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
90077        /* Loop through table entries that match term pOrTerm. */
90078        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
90079                        WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
90080                        WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
90081        if( pSubWInfo ){
90082          if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
90083            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
90084            int r;
90085            r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
90086                                         regRowid);
90087            sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
90088                                 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
90089          }
90090          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
90091
90092          /* The pSubWInfo->untestedTerms flag means that this OR term
90093          ** contained one or more AND term from a notReady table.  The
90094          ** terms from the notReady table could not be tested and will
90095          ** need to be tested later.
90096          */
90097          if( pSubWInfo->untestedTerms ) untestedTerms = 1;
90098
90099          /* Finish the loop through table entries that match term pOrTerm. */
90100          sqlite3WhereEnd(pSubWInfo);
90101        }
90102      }
90103    }
90104    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
90105    sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
90106    sqlite3VdbeResolveLabel(v, iLoopBody);
90107
90108    if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
90109    if( !untestedTerms ) disableTerm(pLevel, pTerm);
90110  }else
90111#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
90112
90113  {
90114    /* Case 5:  There is no usable index.  We must do a complete
90115    **          scan of the entire table.
90116    */
90117    static const u8 aStep[] = { OP_Next, OP_Prev };
90118    static const u8 aStart[] = { OP_Rewind, OP_Last };
90119    assert( bRev==0 || bRev==1 );
90120    assert( omitTable==0 );
90121    pLevel->op = aStep[bRev];
90122    pLevel->p1 = iCur;
90123    pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
90124    pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
90125  }
90126  notReady &= ~getMask(pWC->pMaskSet, iCur);
90127
90128  /* Insert code to test every subexpression that can be completely
90129  ** computed using the current set of tables.
90130  */
90131  k = 0;
90132  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
90133    Expr *pE;
90134    testcase( pTerm->wtFlags & TERM_VIRTUAL );
90135    testcase( pTerm->wtFlags & TERM_CODED );
90136    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
90137    if( (pTerm->prereqAll & notReady)!=0 ){
90138      testcase( pWInfo->untestedTerms==0
90139               && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
90140      pWInfo->untestedTerms = 1;
90141      continue;
90142    }
90143    pE = pTerm->pExpr;
90144    assert( pE!=0 );
90145    if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
90146      continue;
90147    }
90148    sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
90149    k = 1;
90150    pTerm->wtFlags |= TERM_CODED;
90151  }
90152
90153  /* For a LEFT OUTER JOIN, generate code that will record the fact that
90154  ** at least one row of the right table has matched the left table.
90155  */
90156  if( pLevel->iLeftJoin ){
90157    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
90158    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
90159    VdbeComment((v, "record LEFT JOIN hit"));
90160    sqlite3ExprCacheClear(pParse);
90161    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
90162      testcase( pTerm->wtFlags & TERM_VIRTUAL );
90163      testcase( pTerm->wtFlags & TERM_CODED );
90164      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
90165      if( (pTerm->prereqAll & notReady)!=0 ){
90166        assert( pWInfo->untestedTerms );
90167        continue;
90168      }
90169      assert( pTerm->pExpr );
90170      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
90171      pTerm->wtFlags |= TERM_CODED;
90172    }
90173  }
90174  sqlite3ReleaseTempReg(pParse, iReleaseReg);
90175
90176  return notReady;
90177}
90178
90179#if defined(SQLITE_TEST)
90180/*
90181** The following variable holds a text description of query plan generated
90182** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
90183** overwrites the previous.  This information is used for testing and
90184** analysis only.
90185*/
90186SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
90187static int nQPlan = 0;              /* Next free slow in _query_plan[] */
90188
90189#endif /* SQLITE_TEST */
90190
90191
90192/*
90193** Free a WhereInfo structure
90194*/
90195static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
90196  if( pWInfo ){
90197    int i;
90198    for(i=0; i<pWInfo->nLevel; i++){
90199      sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
90200      if( pInfo ){
90201        /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
90202        if( pInfo->needToFreeIdxStr ){
90203          sqlite3_free(pInfo->idxStr);
90204        }
90205        sqlite3DbFree(db, pInfo);
90206      }
90207    }
90208    whereClauseClear(pWInfo->pWC);
90209    sqlite3DbFree(db, pWInfo);
90210  }
90211}
90212
90213
90214/*
90215** Generate the beginning of the loop used for WHERE clause processing.
90216** The return value is a pointer to an opaque structure that contains
90217** information needed to terminate the loop.  Later, the calling routine
90218** should invoke sqlite3WhereEnd() with the return value of this function
90219** in order to complete the WHERE clause processing.
90220**
90221** If an error occurs, this routine returns NULL.
90222**
90223** The basic idea is to do a nested loop, one loop for each table in
90224** the FROM clause of a select.  (INSERT and UPDATE statements are the
90225** same as a SELECT with only a single table in the FROM clause.)  For
90226** example, if the SQL is this:
90227**
90228**       SELECT * FROM t1, t2, t3 WHERE ...;
90229**
90230** Then the code generated is conceptually like the following:
90231**
90232**      foreach row1 in t1 do       \    Code generated
90233**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
90234**          foreach row3 in t3 do   /
90235**            ...
90236**          end                     \    Code generated
90237**        end                        |-- by sqlite3WhereEnd()
90238**      end                         /
90239**
90240** Note that the loops might not be nested in the order in which they
90241** appear in the FROM clause if a different order is better able to make
90242** use of indices.  Note also that when the IN operator appears in
90243** the WHERE clause, it might result in additional nested loops for
90244** scanning through all values on the right-hand side of the IN.
90245**
90246** There are Btree cursors associated with each table.  t1 uses cursor
90247** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
90248** And so forth.  This routine generates code to open those VDBE cursors
90249** and sqlite3WhereEnd() generates the code to close them.
90250**
90251** The code that sqlite3WhereBegin() generates leaves the cursors named
90252** in pTabList pointing at their appropriate entries.  The [...] code
90253** can use OP_Column and OP_Rowid opcodes on these cursors to extract
90254** data from the various tables of the loop.
90255**
90256** If the WHERE clause is empty, the foreach loops must each scan their
90257** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
90258** the tables have indices and there are terms in the WHERE clause that
90259** refer to those indices, a complete table scan can be avoided and the
90260** code will run much faster.  Most of the work of this routine is checking
90261** to see if there are indices that can be used to speed up the loop.
90262**
90263** Terms of the WHERE clause are also used to limit which rows actually
90264** make it to the "..." in the middle of the loop.  After each "foreach",
90265** terms of the WHERE clause that use only terms in that loop and outer
90266** loops are evaluated and if false a jump is made around all subsequent
90267** inner loops (or around the "..." if the test occurs within the inner-
90268** most loop)
90269**
90270** OUTER JOINS
90271**
90272** An outer join of tables t1 and t2 is conceptally coded as follows:
90273**
90274**    foreach row1 in t1 do
90275**      flag = 0
90276**      foreach row2 in t2 do
90277**        start:
90278**          ...
90279**          flag = 1
90280**      end
90281**      if flag==0 then
90282**        move the row2 cursor to a null row
90283**        goto start
90284**      fi
90285**    end
90286**
90287** ORDER BY CLAUSE PROCESSING
90288**
90289** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
90290** if there is one.  If there is no ORDER BY clause or if this routine
90291** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
90292**
90293** If an index can be used so that the natural output order of the table
90294** scan is correct for the ORDER BY clause, then that index is used and
90295** *ppOrderBy is set to NULL.  This is an optimization that prevents an
90296** unnecessary sort of the result set if an index appropriate for the
90297** ORDER BY clause already exists.
90298**
90299** If the where clause loops cannot be arranged to provide the correct
90300** output order, then the *ppOrderBy is unchanged.
90301*/
90302SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
90303  Parse *pParse,        /* The parser context */
90304  SrcList *pTabList,    /* A list of all tables to be scanned */
90305  Expr *pWhere,         /* The WHERE clause */
90306  ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
90307  u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
90308){
90309  int i;                     /* Loop counter */
90310  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
90311  int nTabList;              /* Number of elements in pTabList */
90312  WhereInfo *pWInfo;         /* Will become the return value of this function */
90313  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
90314  Bitmask notReady;          /* Cursors that are not yet positioned */
90315  WhereMaskSet *pMaskSet;    /* The expression mask set */
90316  WhereClause *pWC;               /* Decomposition of the WHERE clause */
90317  struct SrcList_item *pTabItem;  /* A single entry from pTabList */
90318  WhereLevel *pLevel;             /* A single level in the pWInfo list */
90319  int iFrom;                      /* First unused FROM clause element */
90320  int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
90321  sqlite3 *db;               /* Database connection */
90322
90323  /* The number of tables in the FROM clause is limited by the number of
90324  ** bits in a Bitmask
90325  */
90326  if( pTabList->nSrc>BMS ){
90327    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
90328    return 0;
90329  }
90330
90331  /* This function normally generates a nested loop for all tables in
90332  ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
90333  ** only generate code for the first table in pTabList and assume that
90334  ** any cursors associated with subsequent tables are uninitialized.
90335  */
90336  nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
90337
90338  /* Allocate and initialize the WhereInfo structure that will become the
90339  ** return value. A single allocation is used to store the WhereInfo
90340  ** struct, the contents of WhereInfo.a[], the WhereClause structure
90341  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
90342  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
90343  ** some architectures. Hence the ROUND8() below.
90344  */
90345  db = pParse->db;
90346  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
90347  pWInfo = sqlite3DbMallocZero(db,
90348      nByteWInfo +
90349      sizeof(WhereClause) +
90350      sizeof(WhereMaskSet)
90351  );
90352  if( db->mallocFailed ){
90353    goto whereBeginError;
90354  }
90355  pWInfo->nLevel = nTabList;
90356  pWInfo->pParse = pParse;
90357  pWInfo->pTabList = pTabList;
90358  pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
90359  pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
90360  pWInfo->wctrlFlags = wctrlFlags;
90361  pMaskSet = (WhereMaskSet*)&pWC[1];
90362
90363  /* Split the WHERE clause into separate subexpressions where each
90364  ** subexpression is separated by an AND operator.
90365  */
90366  initMaskSet(pMaskSet);
90367  whereClauseInit(pWC, pParse, pMaskSet);
90368  sqlite3ExprCodeConstants(pParse, pWhere);
90369  whereSplit(pWC, pWhere, TK_AND);
90370
90371  /* Special case: a WHERE clause that is constant.  Evaluate the
90372  ** expression and either jump over all of the code or fall thru.
90373  */
90374  if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
90375    sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
90376    pWhere = 0;
90377  }
90378
90379  /* Assign a bit from the bitmask to every term in the FROM clause.
90380  **
90381  ** When assigning bitmask values to FROM clause cursors, it must be
90382  ** the case that if X is the bitmask for the N-th FROM clause term then
90383  ** the bitmask for all FROM clause terms to the left of the N-th term
90384  ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
90385  ** its Expr.iRightJoinTable value to find the bitmask of the right table
90386  ** of the join.  Subtracting one from the right table bitmask gives a
90387  ** bitmask for all tables to the left of the join.  Knowing the bitmask
90388  ** for all tables to the left of a left join is important.  Ticket #3015.
90389  **
90390  ** Configure the WhereClause.vmask variable so that bits that correspond
90391  ** to virtual table cursors are set. This is used to selectively disable
90392  ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
90393  ** with virtual tables.
90394  **
90395  ** Note that bitmasks are created for all pTabList->nSrc tables in
90396  ** pTabList, not just the first nTabList tables.  nTabList is normally
90397  ** equal to pTabList->nSrc but might be shortened to 1 if the
90398  ** WHERE_ONETABLE_ONLY flag is set.
90399  */
90400  assert( pWC->vmask==0 && pMaskSet->n==0 );
90401  for(i=0; i<pTabList->nSrc; i++){
90402    createMask(pMaskSet, pTabList->a[i].iCursor);
90403#ifndef SQLITE_OMIT_VIRTUALTABLE
90404    if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
90405      pWC->vmask |= ((Bitmask)1 << i);
90406    }
90407#endif
90408  }
90409#ifndef NDEBUG
90410  {
90411    Bitmask toTheLeft = 0;
90412    for(i=0; i<pTabList->nSrc; i++){
90413      Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
90414      assert( (m-1)==toTheLeft );
90415      toTheLeft |= m;
90416    }
90417  }
90418#endif
90419
90420  /* Analyze all of the subexpressions.  Note that exprAnalyze() might
90421  ** add new virtual terms onto the end of the WHERE clause.  We do not
90422  ** want to analyze these virtual terms, so start analyzing at the end
90423  ** and work forward so that the added virtual terms are never processed.
90424  */
90425  exprAnalyzeAll(pTabList, pWC);
90426  if( db->mallocFailed ){
90427    goto whereBeginError;
90428  }
90429
90430  /* Chose the best index to use for each table in the FROM clause.
90431  **
90432  ** This loop fills in the following fields:
90433  **
90434  **   pWInfo->a[].pIdx      The index to use for this level of the loop.
90435  **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
90436  **   pWInfo->a[].nEq       The number of == and IN constraints
90437  **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
90438  **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
90439  **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
90440  **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
90441  **
90442  ** This loop also figures out the nesting order of tables in the FROM
90443  ** clause.
90444  */
90445  notReady = ~(Bitmask)0;
90446  pTabItem = pTabList->a;
90447  pLevel = pWInfo->a;
90448  andFlags = ~0;
90449  WHERETRACE(("*** Optimizer Start ***\n"));
90450  for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
90451    WhereCost bestPlan;         /* Most efficient plan seen so far */
90452    Index *pIdx;                /* Index for FROM table at pTabItem */
90453    int j;                      /* For looping over FROM tables */
90454    int bestJ = -1;             /* The value of j */
90455    Bitmask m;                  /* Bitmask value for j or bestJ */
90456    int isOptimal;              /* Iterator for optimal/non-optimal search */
90457
90458    memset(&bestPlan, 0, sizeof(bestPlan));
90459    bestPlan.rCost = SQLITE_BIG_DBL;
90460
90461    /* Loop through the remaining entries in the FROM clause to find the
90462    ** next nested loop. The FROM clause entries may be iterated through
90463    ** either once or twice.
90464    **
90465    ** The first iteration, which is always performed, searches for the
90466    ** FROM clause entry that permits the lowest-cost, "optimal" scan. In
90467    ** this context an optimal scan is one that uses the same strategy
90468    ** for the given FROM clause entry as would be selected if the entry
90469    ** were used as the innermost nested loop.  In other words, a table
90470    ** is chosen such that the cost of running that table cannot be reduced
90471    ** by waiting for other tables to run first.
90472    **
90473    ** The second iteration is only performed if no optimal scan strategies
90474    ** were found by the first. This iteration is used to search for the
90475    ** lowest cost scan overall.
90476    **
90477    ** Previous versions of SQLite performed only the second iteration -
90478    ** the next outermost loop was always that with the lowest overall
90479    ** cost. However, this meant that SQLite could select the wrong plan
90480    ** for scripts such as the following:
90481    **
90482    **   CREATE TABLE t1(a, b);
90483    **   CREATE TABLE t2(c, d);
90484    **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
90485    **
90486    ** The best strategy is to iterate through table t1 first. However it
90487    ** is not possible to determine this with a simple greedy algorithm.
90488    ** However, since the cost of a linear scan through table t2 is the same
90489    ** as the cost of a linear scan through table t1, a simple greedy
90490    ** algorithm may choose to use t2 for the outer loop, which is a much
90491    ** costlier approach.
90492    */
90493    for(isOptimal=1; isOptimal>=0 && bestJ<0; isOptimal--){
90494      Bitmask mask = (isOptimal ? 0 : notReady);
90495      assert( (nTabList-iFrom)>1 || isOptimal );
90496      for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
90497        int doNotReorder;    /* True if this table should not be reordered */
90498        WhereCost sCost;     /* Cost information from best[Virtual]Index() */
90499        ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
90500
90501        doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
90502        if( j!=iFrom && doNotReorder ) break;
90503        m = getMask(pMaskSet, pTabItem->iCursor);
90504        if( (m & notReady)==0 ){
90505          if( j==iFrom ) iFrom++;
90506          continue;
90507        }
90508        pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
90509
90510        assert( pTabItem->pTab );
90511#ifndef SQLITE_OMIT_VIRTUALTABLE
90512        if( IsVirtual(pTabItem->pTab) ){
90513          sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
90514          bestVirtualIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost, pp);
90515        }else
90516#endif
90517        {
90518          bestBtreeIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost);
90519        }
90520        assert( isOptimal || (sCost.used&notReady)==0 );
90521
90522        if( (sCost.used&notReady)==0
90523         && (j==iFrom || sCost.rCost<bestPlan.rCost)
90524        ){
90525          bestPlan = sCost;
90526          bestJ = j;
90527        }
90528        if( doNotReorder ) break;
90529      }
90530    }
90531    assert( bestJ>=0 );
90532    assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
90533    WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
90534           pLevel-pWInfo->a));
90535    if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
90536      *ppOrderBy = 0;
90537    }
90538    andFlags &= bestPlan.plan.wsFlags;
90539    pLevel->plan = bestPlan.plan;
90540    if( bestPlan.plan.wsFlags & WHERE_INDEXED ){
90541      pLevel->iIdxCur = pParse->nTab++;
90542    }else{
90543      pLevel->iIdxCur = -1;
90544    }
90545    notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
90546    pLevel->iFrom = (u8)bestJ;
90547
90548    /* Check that if the table scanned by this loop iteration had an
90549    ** INDEXED BY clause attached to it, that the named index is being
90550    ** used for the scan. If not, then query compilation has failed.
90551    ** Return an error.
90552    */
90553    pIdx = pTabList->a[bestJ].pIndex;
90554    if( pIdx ){
90555      if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
90556        sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
90557        goto whereBeginError;
90558      }else{
90559        /* If an INDEXED BY clause is used, the bestIndex() function is
90560        ** guaranteed to find the index specified in the INDEXED BY clause
90561        ** if it find an index at all. */
90562        assert( bestPlan.plan.u.pIdx==pIdx );
90563      }
90564    }
90565  }
90566  WHERETRACE(("*** Optimizer Finished ***\n"));
90567  if( pParse->nErr || db->mallocFailed ){
90568    goto whereBeginError;
90569  }
90570
90571  /* If the total query only selects a single row, then the ORDER BY
90572  ** clause is irrelevant.
90573  */
90574  if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
90575    *ppOrderBy = 0;
90576  }
90577
90578  /* If the caller is an UPDATE or DELETE statement that is requesting
90579  ** to use a one-pass algorithm, determine if this is appropriate.
90580  ** The one-pass algorithm only works if the WHERE clause constraints
90581  ** the statement to update a single row.
90582  */
90583  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
90584  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
90585    pWInfo->okOnePass = 1;
90586    pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
90587  }
90588
90589  /* Open all tables in the pTabList and any indices selected for
90590  ** searching those tables.
90591  */
90592  sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
90593  for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
90594    Table *pTab;     /* Table to open */
90595    int iDb;         /* Index of database containing table/index */
90596
90597#ifndef SQLITE_OMIT_EXPLAIN
90598    if( pParse->explain==2 ){
90599      char *zMsg;
90600      struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
90601      zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
90602      if( pItem->zAlias ){
90603        zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
90604      }
90605      if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
90606        zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s",
90607           zMsg, pLevel->plan.u.pIdx->zName);
90608      }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
90609        zMsg = sqlite3MAppendf(db, zMsg, "%s VIA MULTI-INDEX UNION", zMsg);
90610      }else if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
90611        zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
90612      }
90613#ifndef SQLITE_OMIT_VIRTUALTABLE
90614      else if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
90615        sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
90616        zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
90617                    pVtabIdx->idxNum, pVtabIdx->idxStr);
90618      }
90619#endif
90620      if( pLevel->plan.wsFlags & WHERE_ORDERBY ){
90621        zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
90622      }
90623      sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
90624    }
90625#endif /* SQLITE_OMIT_EXPLAIN */
90626    pTabItem = &pTabList->a[pLevel->iFrom];
90627    pTab = pTabItem->pTab;
90628    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
90629    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
90630#ifndef SQLITE_OMIT_VIRTUALTABLE
90631    if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
90632      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
90633      int iCur = pTabItem->iCursor;
90634      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
90635    }else
90636#endif
90637    if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
90638         && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
90639      int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
90640      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
90641      if( !pWInfo->okOnePass && pTab->nCol<BMS ){
90642        Bitmask b = pTabItem->colUsed;
90643        int n = 0;
90644        for(; b; b=b>>1, n++){}
90645        sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
90646                            SQLITE_INT_TO_PTR(n), P4_INT32);
90647        assert( n<=pTab->nCol );
90648      }
90649    }else{
90650      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
90651    }
90652    pLevel->iTabCur = pTabItem->iCursor;
90653    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
90654      Index *pIx = pLevel->plan.u.pIdx;
90655      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
90656      int iIdxCur = pLevel->iIdxCur;
90657      assert( pIx->pSchema==pTab->pSchema );
90658      assert( iIdxCur>=0 );
90659      sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
90660                        (char*)pKey, P4_KEYINFO_HANDOFF);
90661      VdbeComment((v, "%s", pIx->zName));
90662    }
90663    sqlite3CodeVerifySchema(pParse, iDb);
90664  }
90665  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
90666
90667  /* Generate the code to do the search.  Each iteration of the for
90668  ** loop below generates code for a single nested loop of the VM
90669  ** program.
90670  */
90671  notReady = ~(Bitmask)0;
90672  for(i=0; i<nTabList; i++){
90673    notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
90674    pWInfo->iContinue = pWInfo->a[i].addrCont;
90675  }
90676
90677#ifdef SQLITE_TEST  /* For testing and debugging use only */
90678  /* Record in the query plan information about the current table
90679  ** and the index used to access it (if any).  If the table itself
90680  ** is not used, its name is just '{}'.  If no index is used
90681  ** the index is listed as "{}".  If the primary key is used the
90682  ** index name is '*'.
90683  */
90684  for(i=0; i<nTabList; i++){
90685    char *z;
90686    int n;
90687    pLevel = &pWInfo->a[i];
90688    pTabItem = &pTabList->a[pLevel->iFrom];
90689    z = pTabItem->zAlias;
90690    if( z==0 ) z = pTabItem->pTab->zName;
90691    n = sqlite3Strlen30(z);
90692    if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
90693      if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
90694        memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
90695        nQPlan += 2;
90696      }else{
90697        memcpy(&sqlite3_query_plan[nQPlan], z, n);
90698        nQPlan += n;
90699      }
90700      sqlite3_query_plan[nQPlan++] = ' ';
90701    }
90702    testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
90703    testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
90704    if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
90705      memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
90706      nQPlan += 2;
90707    }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
90708      n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
90709      if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
90710        memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
90711        nQPlan += n;
90712        sqlite3_query_plan[nQPlan++] = ' ';
90713      }
90714    }else{
90715      memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
90716      nQPlan += 3;
90717    }
90718  }
90719  while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
90720    sqlite3_query_plan[--nQPlan] = 0;
90721  }
90722  sqlite3_query_plan[nQPlan] = 0;
90723  nQPlan = 0;
90724#endif /* SQLITE_TEST // Testing and debugging use only */
90725
90726  /* Record the continuation address in the WhereInfo structure.  Then
90727  ** clean up and return.
90728  */
90729  return pWInfo;
90730
90731  /* Jump here if malloc fails */
90732whereBeginError:
90733  whereInfoFree(db, pWInfo);
90734  return 0;
90735}
90736
90737/*
90738** Generate the end of the WHERE loop.  See comments on
90739** sqlite3WhereBegin() for additional information.
90740*/
90741SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
90742  Parse *pParse = pWInfo->pParse;
90743  Vdbe *v = pParse->pVdbe;
90744  int i;
90745  WhereLevel *pLevel;
90746  SrcList *pTabList = pWInfo->pTabList;
90747  sqlite3 *db = pParse->db;
90748
90749  /* Generate loop termination code.
90750  */
90751  sqlite3ExprCacheClear(pParse);
90752  for(i=pWInfo->nLevel-1; i>=0; i--){
90753    pLevel = &pWInfo->a[i];
90754    sqlite3VdbeResolveLabel(v, pLevel->addrCont);
90755    if( pLevel->op!=OP_Noop ){
90756      sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
90757      sqlite3VdbeChangeP5(v, pLevel->p5);
90758    }
90759    if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
90760      struct InLoop *pIn;
90761      int j;
90762      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
90763      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
90764        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
90765        sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
90766        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
90767      }
90768      sqlite3DbFree(db, pLevel->u.in.aInLoop);
90769    }
90770    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
90771    if( pLevel->iLeftJoin ){
90772      int addr;
90773      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
90774      assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
90775           || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
90776      if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
90777        sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
90778      }
90779      if( pLevel->iIdxCur>=0 ){
90780        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
90781      }
90782      if( pLevel->op==OP_Return ){
90783        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
90784      }else{
90785        sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
90786      }
90787      sqlite3VdbeJumpHere(v, addr);
90788    }
90789  }
90790
90791  /* The "break" point is here, just past the end of the outer loop.
90792  ** Set it.
90793  */
90794  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
90795
90796  /* Close all of the cursors that were opened by sqlite3WhereBegin.
90797  */
90798  assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
90799  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
90800    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
90801    Table *pTab = pTabItem->pTab;
90802    assert( pTab!=0 );
90803    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
90804    if( (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0 ){
90805      if( !pWInfo->okOnePass && (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
90806        sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
90807      }
90808      if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
90809        sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
90810      }
90811    }
90812
90813    /* If this scan uses an index, make code substitutions to read data
90814    ** from the index in preference to the table. Sometimes, this means
90815    ** the table need never be read from. This is a performance boost,
90816    ** as the vdbe level waits until the table is read before actually
90817    ** seeking the table cursor to the record corresponding to the current
90818    ** position in the index.
90819    **
90820    ** Calls to the code generator in between sqlite3WhereBegin and
90821    ** sqlite3WhereEnd will have created code that references the table
90822    ** directly.  This loop scans all that code looking for opcodes
90823    ** that reference the table and converts them into opcodes that
90824    ** reference the index.
90825    */
90826    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
90827      int k, j, last;
90828      VdbeOp *pOp;
90829      Index *pIdx = pLevel->plan.u.pIdx;
90830
90831      assert( pIdx!=0 );
90832      pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
90833      last = sqlite3VdbeCurrentAddr(v);
90834      for(k=pWInfo->iTop; k<last; k++, pOp++){
90835        if( pOp->p1!=pLevel->iTabCur ) continue;
90836        if( pOp->opcode==OP_Column ){
90837          for(j=0; j<pIdx->nColumn; j++){
90838            if( pOp->p2==pIdx->aiColumn[j] ){
90839              pOp->p2 = j;
90840              pOp->p1 = pLevel->iIdxCur;
90841              break;
90842            }
90843          }
90844          assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
90845               || j<pIdx->nColumn );
90846        }else if( pOp->opcode==OP_Rowid ){
90847          pOp->p1 = pLevel->iIdxCur;
90848          pOp->opcode = OP_IdxRowid;
90849        }
90850      }
90851    }
90852  }
90853
90854  /* Final cleanup
90855  */
90856  whereInfoFree(db, pWInfo);
90857  return;
90858}
90859
90860/************** End of where.c ***********************************************/
90861/************** Begin file parse.c *******************************************/
90862/* Driver template for the LEMON parser generator.
90863** The author disclaims copyright to this source code.
90864**
90865** This version of "lempar.c" is modified, slightly, for use by SQLite.
90866** The only modifications are the addition of a couple of NEVER()
90867** macros to disable tests that are needed in the case of a general
90868** LALR(1) grammar but which are always false in the
90869** specific grammar used by SQLite.
90870*/
90871/* First off, code is included that follows the "include" declaration
90872** in the input grammar file. */
90873
90874
90875/*
90876** Disable all error recovery processing in the parser push-down
90877** automaton.
90878*/
90879#define YYNOERRORRECOVERY 1
90880
90881/*
90882** Make yytestcase() the same as testcase()
90883*/
90884#define yytestcase(X) testcase(X)
90885
90886/*
90887** An instance of this structure holds information about the
90888** LIMIT clause of a SELECT statement.
90889*/
90890struct LimitVal {
90891  Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
90892  Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
90893};
90894
90895/*
90896** An instance of this structure is used to store the LIKE,
90897** GLOB, NOT LIKE, and NOT GLOB operators.
90898*/
90899struct LikeOp {
90900  Token eOperator;  /* "like" or "glob" or "regexp" */
90901  int not;         /* True if the NOT keyword is present */
90902};
90903
90904/*
90905** An instance of the following structure describes the event of a
90906** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
90907** TK_DELETE, or TK_INSTEAD.  If the event is of the form
90908**
90909**      UPDATE ON (a,b,c)
90910**
90911** Then the "b" IdList records the list "a,b,c".
90912*/
90913struct TrigEvent { int a; IdList * b; };
90914
90915/*
90916** An instance of this structure holds the ATTACH key and the key type.
90917*/
90918struct AttachKey { int type;  Token key; };
90919
90920
90921  /* This is a utility routine used to set the ExprSpan.zStart and
90922  ** ExprSpan.zEnd values of pOut so that the span covers the complete
90923  ** range of text beginning with pStart and going to the end of pEnd.
90924  */
90925  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
90926    pOut->zStart = pStart->z;
90927    pOut->zEnd = &pEnd->z[pEnd->n];
90928  }
90929
90930  /* Construct a new Expr object from a single identifier.  Use the
90931  ** new Expr to populate pOut.  Set the span of pOut to be the identifier
90932  ** that created the expression.
90933  */
90934  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
90935    pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
90936    pOut->zStart = pValue->z;
90937    pOut->zEnd = &pValue->z[pValue->n];
90938  }
90939
90940  /* This routine constructs a binary expression node out of two ExprSpan
90941  ** objects and uses the result to populate a new ExprSpan object.
90942  */
90943  static void spanBinaryExpr(
90944    ExprSpan *pOut,     /* Write the result here */
90945    Parse *pParse,      /* The parsing context.  Errors accumulate here */
90946    int op,             /* The binary operation */
90947    ExprSpan *pLeft,    /* The left operand */
90948    ExprSpan *pRight    /* The right operand */
90949  ){
90950    pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
90951    pOut->zStart = pLeft->zStart;
90952    pOut->zEnd = pRight->zEnd;
90953  }
90954
90955  /* Construct an expression node for a unary postfix operator
90956  */
90957  static void spanUnaryPostfix(
90958    ExprSpan *pOut,        /* Write the new expression node here */
90959    Parse *pParse,         /* Parsing context to record errors */
90960    int op,                /* The operator */
90961    ExprSpan *pOperand,    /* The operand */
90962    Token *pPostOp         /* The operand token for setting the span */
90963  ){
90964    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
90965    pOut->zStart = pOperand->zStart;
90966    pOut->zEnd = &pPostOp->z[pPostOp->n];
90967  }
90968
90969  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
90970  ** unary TK_ISNULL or TK_NOTNULL expression. */
90971  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
90972    sqlite3 *db = pParse->db;
90973    if( db->mallocFailed==0 && pY->op==TK_NULL ){
90974      pA->op = (u8)op;
90975      sqlite3ExprDelete(db, pA->pRight);
90976      pA->pRight = 0;
90977    }
90978  }
90979
90980  /* Construct an expression node for a unary prefix operator
90981  */
90982  static void spanUnaryPrefix(
90983    ExprSpan *pOut,        /* Write the new expression node here */
90984    Parse *pParse,         /* Parsing context to record errors */
90985    int op,                /* The operator */
90986    ExprSpan *pOperand,    /* The operand */
90987    Token *pPreOp         /* The operand token for setting the span */
90988  ){
90989    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
90990    pOut->zStart = pPreOp->z;
90991    pOut->zEnd = pOperand->zEnd;
90992  }
90993/* Next is all token values, in a form suitable for use by makeheaders.
90994** This section will be null unless lemon is run with the -m switch.
90995*/
90996/*
90997** These constants (all generated automatically by the parser generator)
90998** specify the various kinds of tokens (terminals) that the parser
90999** understands.
91000**
91001** Each symbol here is a terminal symbol in the grammar.
91002*/
91003/* Make sure the INTERFACE macro is defined.
91004*/
91005#ifndef INTERFACE
91006# define INTERFACE 1
91007#endif
91008/* The next thing included is series of defines which control
91009** various aspects of the generated parser.
91010**    YYCODETYPE         is the data type used for storing terminal
91011**                       and nonterminal numbers.  "unsigned char" is
91012**                       used if there are fewer than 250 terminals
91013**                       and nonterminals.  "int" is used otherwise.
91014**    YYNOCODE           is a number of type YYCODETYPE which corresponds
91015**                       to no legal terminal or nonterminal number.  This
91016**                       number is used to fill in empty slots of the hash
91017**                       table.
91018**    YYFALLBACK         If defined, this indicates that one or more tokens
91019**                       have fall-back values which should be used if the
91020**                       original value of the token will not parse.
91021**    YYACTIONTYPE       is the data type used for storing terminal
91022**                       and nonterminal numbers.  "unsigned char" is
91023**                       used if there are fewer than 250 rules and
91024**                       states combined.  "int" is used otherwise.
91025**    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
91026**                       directly to the parser from the tokenizer.
91027**    YYMINORTYPE        is the data type used for all minor tokens.
91028**                       This is typically a union of many types, one of
91029**                       which is sqlite3ParserTOKENTYPE.  The entry in the union
91030**                       for base tokens is called "yy0".
91031**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
91032**                       zero the stack is dynamically sized using realloc()
91033**    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
91034**    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
91035**    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
91036**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
91037**    YYNSTATE           the combined number of states.
91038**    YYNRULE            the number of rules in the grammar
91039**    YYERRORSYMBOL      is the code number of the error symbol.  If not
91040**                       defined, then do no error processing.
91041*/
91042#define YYCODETYPE unsigned char
91043#define YYNOCODE 254
91044#define YYACTIONTYPE unsigned short int
91045#define YYWILDCARD 67
91046#define sqlite3ParserTOKENTYPE Token
91047typedef union {
91048  int yyinit;
91049  sqlite3ParserTOKENTYPE yy0;
91050  Select* yy3;
91051  ExprList* yy14;
91052  SrcList* yy65;
91053  struct LikeOp yy96;
91054  Expr* yy132;
91055  u8 yy186;
91056  int yy328;
91057  ExprSpan yy346;
91058  struct TrigEvent yy378;
91059  IdList* yy408;
91060  struct {int value; int mask;} yy429;
91061  TriggerStep* yy473;
91062  struct LimitVal yy476;
91063} YYMINORTYPE;
91064#ifndef YYSTACKDEPTH
91065#define YYSTACKDEPTH 100
91066#endif
91067#define sqlite3ParserARG_SDECL Parse *pParse;
91068#define sqlite3ParserARG_PDECL ,Parse *pParse
91069#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
91070#define sqlite3ParserARG_STORE yypParser->pParse = pParse
91071#define YYNSTATE 631
91072#define YYNRULE 330
91073#define YYFALLBACK 1
91074#define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
91075#define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
91076#define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
91077
91078/* The yyzerominor constant is used to initialize instances of
91079** YYMINORTYPE objects to zero. */
91080static const YYMINORTYPE yyzerominor = { 0 };
91081
91082/* Define the yytestcase() macro to be a no-op if is not already defined
91083** otherwise.
91084**
91085** Applications can choose to define yytestcase() in the %include section
91086** to a macro that can assist in verifying code coverage.  For production
91087** code the yytestcase() macro should be turned off.  But it is useful
91088** for testing.
91089*/
91090#ifndef yytestcase
91091# define yytestcase(X)
91092#endif
91093
91094
91095/* Next are the tables used to determine what action to take based on the
91096** current state and lookahead token.  These tables are used to implement
91097** functions that take a state number and lookahead value and return an
91098** action integer.
91099**
91100** Suppose the action integer is N.  Then the action is determined as
91101** follows
91102**
91103**   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
91104**                                      token onto the stack and goto state N.
91105**
91106**   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
91107**
91108**   N == YYNSTATE+YYNRULE              A syntax error has occurred.
91109**
91110**   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
91111**
91112**   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
91113**                                      slots in the yy_action[] table.
91114**
91115** The action table is constructed as a single large table named yy_action[].
91116** Given state S and lookahead X, the action is computed as
91117**
91118**      yy_action[ yy_shift_ofst[S] + X ]
91119**
91120** If the index value yy_shift_ofst[S]+X is out of range or if the value
91121** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
91122** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
91123** and that yy_default[S] should be used instead.
91124**
91125** The formula above is for computing the action when the lookahead is
91126** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
91127** a reduce action) then the yy_reduce_ofst[] array is used in place of
91128** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
91129** YY_SHIFT_USE_DFLT.
91130**
91131** The following are the tables generated in this section:
91132**
91133**  yy_action[]        A single table containing all actions.
91134**  yy_lookahead[]     A table containing the lookahead for each entry in
91135**                     yy_action.  Used to detect hash collisions.
91136**  yy_shift_ofst[]    For each state, the offset into yy_action for
91137**                     shifting terminals.
91138**  yy_reduce_ofst[]   For each state, the offset into yy_action for
91139**                     shifting non-terminals after a reduce.
91140**  yy_default[]       Default action for each state.
91141*/
91142#define YY_ACTTAB_COUNT (1543)
91143static const YYACTIONTYPE yy_action[] = {
91144 /*     0 */   313,   49,  556,   46,  147,  172,  628,  598,   55,   55,
91145 /*    10 */    55,   55,  302,   53,   53,   53,   53,   52,   52,   51,
91146 /*    20 */    51,   51,   50,  238,  603,   66,  624,  623,  604,  598,
91147 /*    30 */   591,  585,   48,   53,   53,   53,   53,   52,   52,   51,
91148 /*    40 */    51,   51,   50,  238,   51,   51,   51,   50,  238,   56,
91149 /*    50 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
91150 /*    60 */    55,   55,  609,   53,   53,   53,   53,   52,   52,   51,
91151 /*    70 */    51,   51,   50,  238,  313,  598,  672,  330,  411,  217,
91152 /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
91153 /*    90 */    50,  238,  330,  414,  621,  620,  166,  598,  673,  382,
91154 /*   100 */   379,  378,  602,   73,  591,  585,  307,  424,  166,   58,
91155 /*   110 */   377,  382,  379,  378,  516,  515,  624,  623,  254,  200,
91156 /*   120 */   199,  198,  377,   56,   57,   47,  583,  582,  584,  584,
91157 /*   130 */    54,   54,   55,   55,   55,   55,  581,   53,   53,   53,
91158 /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  270,
91159 /*   150 */   226,  422,  283,  133,  177,  139,  284,  385,  279,  384,
91160 /*   160 */   169,  197,  251,  282,  253,  226,  411,  275,  440,  167,
91161 /*   170 */   139,  284,  385,  279,  384,  169,  571,  236,  591,  585,
91162 /*   180 */   240,  414,  275,  622,  621,  620,  674,  437,  441,  442,
91163 /*   190 */   602,   88,  352,  266,  439,  268,  438,   56,   57,   47,
91164 /*   200 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
91165 /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
91166 /*   220 */    50,  238,  313,  471,   52,   52,   51,   51,   51,   50,
91167 /*   230 */   238,  234,  166,  491,  567,  382,  379,  378,    1,  440,
91168 /*   240 */   252,  176,  624,  623,  608,   67,  377,  513,  622,  443,
91169 /*   250 */   237,  577,  591,  585,  622,  172,  466,  598,  554,  441,
91170 /*   260 */   340,  409,  526,  580,  580,  349,  596,  553,  194,  482,
91171 /*   270 */   175,   56,   57,   47,  583,  582,  584,  584,   54,   54,
91172 /*   280 */    55,   55,   55,   55,  562,   53,   53,   53,   53,   52,
91173 /*   290 */    52,   51,   51,   51,   50,  238,  313,  594,  594,  594,
91174 /*   300 */   561,  578,  469,   65,  259,  351,  258,  411,  624,  623,
91175 /*   310 */   621,  620,  332,  576,  575,  240,  560,  568,  520,  411,
91176 /*   320 */   341,  237,  414,  624,  623,  598,  591,  585,  542,  519,
91177 /*   330 */   171,  602,   95,   68,  414,  624,  623,  624,  623,   38,
91178 /*   340 */   877,  506,  507,  602,   88,   56,   57,   47,  583,  582,
91179 /*   350 */   584,  584,   54,   54,   55,   55,   55,   55,  532,   53,
91180 /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
91181 /*   370 */   313,  411,  579,  398,  531,  237,  621,  620,  388,  625,
91182 /*   380 */   500,  206,  167,  396,  233,  312,  414,  387,  569,  492,
91183 /*   390 */   216,  621,  620,  566,  622,  602,   74,  533,  210,  491,
91184 /*   400 */   591,  585,  548,  621,  620,  621,  620,  300,  598,  466,
91185 /*   410 */   481,   67,  603,   35,  622,  601,  604,  547,    6,   56,
91186 /*   420 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
91187 /*   430 */    55,   55,  601,   53,   53,   53,   53,   52,   52,   51,
91188 /*   440 */    51,   51,   50,  238,  313,  411,  184,  409,  528,  580,
91189 /*   450 */   580,  551,  962,  186,  419,    2,  353,  259,  351,  258,
91190 /*   460 */   414,  409,  411,  580,  580,   44,  411,  544,  240,  602,
91191 /*   470 */    94,  190,    7,   62,  591,  585,  598,  414,  350,  607,
91192 /*   480 */   493,  414,  409,  317,  580,  580,  602,   95,  496,  565,
91193 /*   490 */   602,   80,  203,   56,   57,   47,  583,  582,  584,  584,
91194 /*   500 */    54,   54,   55,   55,   55,   55,  535,   53,   53,   53,
91195 /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  202,
91196 /*   520 */   564,  293,  511,   49,  562,   46,  147,  411,  394,  183,
91197 /*   530 */   563,  549,  505,  549,  174,  409,  322,  580,  580,   39,
91198 /*   540 */   561,   37,  414,  624,  623,  192,  473,  383,  591,  585,
91199 /*   550 */   474,  602,   80,  601,  504,  544,  560,  364,  402,  210,
91200 /*   560 */   421,  952,  361,  952,  365,  201,  144,   56,   57,   47,
91201 /*   570 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
91202 /*   580 */   559,   53,   53,   53,   53,   52,   52,   51,   51,   51,
91203 /*   590 */    50,  238,  313,  601,  232,  264,  272,  321,  374,  484,
91204 /*   600 */   510,  146,  342,  146,  328,  425,  485,  407,  576,  575,
91205 /*   610 */   622,  621,  620,   49,  168,   46,  147,  353,  546,  491,
91206 /*   620 */   204,  240,  591,  585,  421,  951,  549,  951,  549,  168,
91207 /*   630 */   429,   67,  390,  343,  622,  434,  307,  423,  338,  360,
91208 /*   640 */   391,   56,   57,   47,  583,  582,  584,  584,   54,   54,
91209 /*   650 */    55,   55,   55,   55,  601,   53,   53,   53,   53,   52,
91210 /*   660 */    52,   51,   51,   51,   50,  238,  313,   34,  318,  425,
91211 /*   670 */   237,   21,  359,  273,  411,  167,  411,  276,  411,  540,
91212 /*   680 */   411,  422,   13,  318,  619,  618,  617,  622,  275,  414,
91213 /*   690 */   336,  414,  622,  414,  622,  414,  591,  585,  602,   69,
91214 /*   700 */   602,   97,  602,  100,  602,   98,  631,  629,  334,  475,
91215 /*   710 */   475,  367,  319,  148,  327,   56,   57,   47,  583,  582,
91216 /*   720 */   584,  584,   54,   54,   55,   55,   55,   55,  411,   53,
91217 /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
91218 /*   740 */   313,  411,  331,  414,  411,   49,  276,   46,  147,  569,
91219 /*   750 */   406,  216,  602,  106,  573,  573,  414,  354,  524,  414,
91220 /*   760 */   411,  622,  411,  224,    4,  602,  104,  605,  602,  108,
91221 /*   770 */   591,  585,  622,   20,  375,  414,  167,  414,  215,  144,
91222 /*   780 */   470,  239,  167,  225,  602,  109,  602,  134,   18,   56,
91223 /*   790 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
91224 /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
91225 /*   810 */    51,   51,   50,  238,  313,  411,  276,  414,   12,  459,
91226 /*   820 */   276,  171,  411,   16,  223,  189,  602,  135,  354,  170,
91227 /*   830 */   414,  622,  630,    2,  411,  622,  540,  414,  143,  602,
91228 /*   840 */    61,  359,  132,  622,  591,  585,  602,  105,  458,  414,
91229 /*   850 */    23,  622,  446,  326,   23,  538,  622,  325,  602,  103,
91230 /*   860 */   427,  530,  309,   56,   57,   47,  583,  582,  584,  584,
91231 /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
91232 /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
91233 /*   890 */   264,  414,  411,  276,  359,  219,  157,  214,  357,  366,
91234 /*   900 */   602,   96,  522,  521,  414,  622,  358,  414,  622,  622,
91235 /*   910 */   411,  613,  612,  602,  102,  142,  602,   77,  591,  585,
91236 /*   920 */   529,  540,  231,  426,  308,  414,  622,  622,  468,  521,
91237 /*   930 */   324,  601,  257,  263,  602,   99,  622,   56,   45,   47,
91238 /*   940 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
91239 /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
91240 /*   960 */    50,  238,  313,  264,  264,  414,  411,  213,  209,  544,
91241 /*   970 */   544,  207,  611,   28,  602,  138,   50,  238,  622,  622,
91242 /*   980 */   381,  414,  503,  140,  323,  222,  274,  622,  590,  589,
91243 /*   990 */   602,  137,  591,  585,  629,  334,  606,   30,  622,  571,
91244 /*  1000 */   236,  601,  601,  130,  496,  601,  453,  451,  288,  286,
91245 /*  1010 */   587,  586,   57,   47,  583,  582,  584,  584,   54,   54,
91246 /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
91247 /*  1030 */    52,   51,   51,   51,   50,  238,  313,  588,  411,  414,
91248 /*  1040 */   411,  264,  410,  129,  595,  400,   27,  376,  602,  136,
91249 /*  1050 */   128,  165,  479,  414,  282,  414,  622,  622,  411,  622,
91250 /*  1060 */   622,  411,  602,   76,  602,   93,  591,  585,  188,  372,
91251 /*  1070 */   368,  125,  476,  414,  261,  160,  414,  171,  124,  472,
91252 /*  1080 */   123,   15,  602,   92,  450,  602,   75,   47,  583,  582,
91253 /*  1090 */   584,  584,   54,   54,   55,   55,   55,   55,  464,   53,
91254 /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
91255 /*  1110 */    43,  405,  264,    3,  558,  264,  545,  415,  623,  159,
91256 /*  1120 */   541,  158,  539,  278,   25,  461,  121,  622,  408,  622,
91257 /*  1130 */   622,  622,   24,   43,  405,  622,    3,  622,  622,  120,
91258 /*  1140 */   415,  623,   11,  456,  411,  156,  452,  403,  509,  277,
91259 /*  1150 */   118,  408,  489,  113,  205,  449,  271,  567,  221,  414,
91260 /*  1160 */   269,  267,  155,  622,  622,  111,  411,  622,  602,   95,
91261 /*  1170 */   403,  622,  411,  110,   10,  622,  622,   40,   41,  534,
91262 /*  1180 */   567,  414,   64,  264,   42,  413,  412,  414,  601,  596,
91263 /*  1190 */   602,   91,  445,  436,  150,  435,  602,   90,  622,  265,
91264 /*  1200 */    40,   41,  337,  242,  411,  191,  333,   42,  413,  412,
91265 /*  1210 */   398,  420,  596,  316,  622,  399,  260,  107,  230,  414,
91266 /*  1220 */   594,  594,  594,  593,  592,   14,  220,  411,  602,  101,
91267 /*  1230 */   240,  622,   43,  405,  362,    3,  149,  315,  626,  415,
91268 /*  1240 */   623,  127,  414,  594,  594,  594,  593,  592,   14,  622,
91269 /*  1250 */   408,  602,   89,  411,  181,   33,  405,  463,    3,  411,
91270 /*  1260 */   264,  462,  415,  623,  616,  615,  614,  355,  414,  403,
91271 /*  1270 */   417,  416,  622,  408,  414,  622,  622,  602,   87,  567,
91272 /*  1280 */   418,  627,  622,  602,   86,    8,  241,  180,  126,  255,
91273 /*  1290 */   600,  178,  403,  240,  208,  455,  395,  294,  444,   40,
91274 /*  1300 */    41,  297,  567,  248,  622,  296,   42,  413,  412,  247,
91275 /*  1310 */   622,  596,  244,  622,   30,   60,   31,  243,  430,  624,
91276 /*  1320 */   623,  292,   40,   41,  622,  295,  145,  622,  601,   42,
91277 /*  1330 */   413,  412,  622,  622,  596,  393,  622,  397,  599,   59,
91278 /*  1340 */   235,  622,  594,  594,  594,  593,  592,   14,  218,  291,
91279 /*  1350 */   622,   36,  344,  305,  304,  303,  179,  301,  411,  567,
91280 /*  1360 */   454,  557,  173,  185,  622,  594,  594,  594,  593,  592,
91281 /*  1370 */    14,  411,   29,  414,  151,  289,  246,  523,  411,  196,
91282 /*  1380 */   195,  335,  602,   85,  411,  245,  414,  526,  392,  543,
91283 /*  1390 */   411,  596,  287,  414,  285,  602,   72,  537,  153,  414,
91284 /*  1400 */   466,  411,  602,   71,  154,  414,  411,  152,  602,   84,
91285 /*  1410 */   386,  536,  329,  411,  602,   83,  414,  518,  280,  411,
91286 /*  1420 */   513,  414,  594,  594,  594,  602,   82,  517,  414,  311,
91287 /*  1430 */   602,   81,  411,  514,  414,  512,  131,  602,   70,  229,
91288 /*  1440 */   228,  227,  494,  602,   17,  411,  488,  414,  259,  346,
91289 /*  1450 */   249,  389,  487,  486,  314,  164,  602,   79,  310,  240,
91290 /*  1460 */   414,  373,  480,  163,  262,  371,  414,  162,  369,  602,
91291 /*  1470 */    78,  212,  478,   26,  477,  602,    9,  161,  467,  363,
91292 /*  1480 */   141,  122,  339,  187,  119,  457,  348,  117,  347,  116,
91293 /*  1490 */   115,  114,  448,  112,  182,  320,   22,  433,   19,  432,
91294 /*  1500 */   431,   63,  428,  610,  193,  298,  597,  574,  572,  404,
91295 /*  1510 */   555,  552,  290,  281,  510,  499,  498,  497,  495,  380,
91296 /*  1520 */   356,  460,  256,  250,  345,  447,  306,    5,  570,  550,
91297 /*  1530 */   299,  211,  370,  401,  550,  508,  502,  501,  490,  527,
91298 /*  1540 */   525,  483,  238,
91299};
91300static const YYCODETYPE yy_lookahead[] = {
91301 /*     0 */    19,  222,  223,  224,  225,   24,    1,   26,   77,   78,
91302 /*    10 */    79,   80,   15,   82,   83,   84,   85,   86,   87,   88,
91303 /*    20 */    89,   90,   91,   92,  113,   22,   26,   27,  117,   26,
91304 /*    30 */    49,   50,   81,   82,   83,   84,   85,   86,   87,   88,
91305 /*    40 */    89,   90,   91,   92,   88,   89,   90,   91,   92,   68,
91306 /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
91307 /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
91308 /*    70 */    89,   90,   91,   92,   19,   94,  118,   19,  150,   22,
91309 /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
91310 /*    90 */    91,   92,   19,  165,   94,   95,   96,   94,  118,   99,
91311 /*   100 */   100,  101,  174,  175,   49,   50,   22,   23,   96,   54,
91312 /*   110 */   110,   99,  100,  101,    7,    8,   26,   27,   16,  105,
91313 /*   120 */   106,  107,  110,   68,   69,   70,   71,   72,   73,   74,
91314 /*   130 */    75,   76,   77,   78,   79,   80,  113,   82,   83,   84,
91315 /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   16,
91316 /*   150 */    92,   67,   98,   24,   96,   97,   98,   99,  100,  101,
91317 /*   160 */   102,   25,   60,  109,   62,   92,  150,  109,  150,   25,
91318 /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
91319 /*   180 */   116,  165,  109,  165,   94,   95,  118,   97,  170,  171,
91320 /*   190 */   174,  175,  128,   60,  104,   62,  106,   68,   69,   70,
91321 /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
91322 /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
91323 /*   220 */    91,   92,   19,   21,   86,   87,   88,   89,   90,   91,
91324 /*   230 */    92,  215,   96,  150,   66,   99,  100,  101,   22,  150,
91325 /*   240 */   138,  118,   26,   27,  161,  162,  110,  103,  165,  231,
91326 /*   250 */   232,   23,   49,   50,  165,   24,   57,   26,   32,  170,
91327 /*   260 */   171,  112,   94,  114,  115,   63,   98,   41,  185,  186,
91328 /*   270 */   118,   68,   69,   70,   71,   72,   73,   74,   75,   76,
91329 /*   280 */    77,   78,   79,   80,   12,   82,   83,   84,   85,   86,
91330 /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
91331 /*   300 */    28,   23,  100,   25,  105,  106,  107,  150,   26,   27,
91332 /*   310 */    94,   95,  169,  170,  171,  116,   44,   23,   46,  150,
91333 /*   320 */   231,  232,  165,   26,   27,   94,   49,   50,   23,   57,
91334 /*   330 */    25,  174,  175,   22,  165,   26,   27,   26,   27,  136,
91335 /*   340 */   138,   97,   98,  174,  175,   68,   69,   70,   71,   72,
91336 /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   23,   82,
91337 /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
91338 /*   370 */    19,  150,   23,  216,   23,  232,   94,   95,  221,  150,
91339 /*   380 */    23,  160,   25,  214,  215,  163,  165,   88,  166,  167,
91340 /*   390 */   168,   94,   95,   23,  165,  174,  175,   88,  160,  150,
91341 /*   400 */    49,   50,  120,   94,   95,   94,   95,  158,   26,   57,
91342 /*   410 */   161,  162,  113,  136,  165,  194,  117,  120,   22,   68,
91343 /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
91344 /*   430 */    79,   80,  194,   82,   83,   84,   85,   86,   87,   88,
91345 /*   440 */    89,   90,   91,   92,   19,  150,   23,  112,   23,  114,
91346 /*   450 */   115,   25,  142,  143,  144,  145,  218,  105,  106,  107,
91347 /*   460 */   165,  112,  150,  114,  115,   22,  150,  166,  116,  174,
91348 /*   470 */   175,   22,   76,  235,   49,   50,   94,  165,  240,  172,
91349 /*   480 */   173,  165,  112,  155,  114,  115,  174,  175,  181,   11,
91350 /*   490 */   174,  175,   22,   68,   69,   70,   71,   72,   73,   74,
91351 /*   500 */    75,   76,   77,   78,   79,   80,  205,   82,   83,   84,
91352 /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  160,
91353 /*   520 */    23,  226,   23,  222,   12,  224,  225,  150,  216,   23,
91354 /*   530 */    23,   25,   36,   25,   25,  112,  220,  114,  115,  135,
91355 /*   540 */    28,  137,  165,   26,   27,  119,   30,   51,   49,   50,
91356 /*   550 */    34,  174,  175,  194,   58,  166,   44,  229,   46,  160,
91357 /*   560 */    22,   23,  234,   25,   48,  206,  207,   68,   69,   70,
91358 /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
91359 /*   580 */    23,   82,   83,   84,   85,   86,   87,   88,   89,   90,
91360 /*   590 */    91,   92,   19,  194,  205,  150,   23,  220,   19,  181,
91361 /*   600 */   182,   95,   97,   95,  108,   67,  188,  169,  170,  171,
91362 /*   610 */   165,   94,   95,  222,   50,  224,  225,  218,  120,  150,
91363 /*   620 */   160,  116,   49,   50,   22,   23,  120,   25,  120,   50,
91364 /*   630 */   161,  162,   19,  128,  165,  244,   22,   23,  193,  240,
91365 /*   640 */    27,   68,   69,   70,   71,   72,   73,   74,   75,   76,
91366 /*   650 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,
91367 /*   660 */    87,   88,   89,   90,   91,   92,   19,   25,  104,   67,
91368 /*   670 */   232,   24,  150,   23,  150,   25,  150,  150,  150,  150,
91369 /*   680 */   150,   67,   25,  104,    7,    8,    9,  165,  109,  165,
91370 /*   690 */   245,  165,  165,  165,  165,  165,   49,   50,  174,  175,
91371 /*   700 */   174,  175,  174,  175,  174,  175,    0,    1,    2,  105,
91372 /*   710 */   106,  107,  248,  249,  187,   68,   69,   70,   71,   72,
91373 /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
91374 /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
91375 /*   740 */    19,  150,  213,  165,  150,  222,  150,  224,  225,  166,
91376 /*   750 */   167,  168,  174,  175,  129,  130,  165,  150,  165,  165,
91377 /*   760 */   150,  165,  150,  241,   35,  174,  175,  174,  174,  175,
91378 /*   770 */    49,   50,  165,   52,   23,  165,   25,  165,  206,  207,
91379 /*   780 */    23,  197,   25,  187,  174,  175,  174,  175,  204,   68,
91380 /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
91381 /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
91382 /*   810 */    89,   90,   91,   92,   19,  150,  150,  165,   35,   23,
91383 /*   820 */   150,   25,  150,   22,  217,   24,  174,  175,  150,   35,
91384 /*   830 */   165,  165,  144,  145,  150,  165,  150,  165,  118,  174,
91385 /*   840 */   175,  150,   22,  165,   49,   50,  174,  175,   23,  165,
91386 /*   850 */    25,  165,   23,  187,   25,   27,  165,  187,  174,  175,
91387 /*   860 */    23,   23,   25,   68,   69,   70,   71,   72,   73,   74,
91388 /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
91389 /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
91390 /*   890 */   150,  165,  150,  150,  150,  217,   25,  160,   19,  213,
91391 /*   900 */   174,  175,  190,  191,  165,  165,   27,  165,  165,  165,
91392 /*   910 */   150,  150,  150,  174,  175,   39,  174,  175,   49,   50,
91393 /*   920 */    23,  150,   52,  250,  251,  165,  165,  165,  190,  191,
91394 /*   930 */   187,  194,  241,  193,  174,  175,  165,   68,   69,   70,
91395 /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
91396 /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
91397 /*   960 */    91,   92,   19,  150,  150,  165,  150,  160,  160,  166,
91398 /*   970 */   166,  160,  150,   22,  174,  175,   91,   92,  165,  165,
91399 /*   980 */    52,  165,   29,  150,  213,  241,   23,  165,   49,   50,
91400 /*   990 */   174,  175,   49,   50,    1,    2,  173,  126,  165,   86,
91401 /*  1000 */    87,  194,  194,   22,  181,  194,  193,  193,  205,  205,
91402 /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
91403 /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
91404 /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
91405 /*  1040 */   150,  150,  150,   22,  150,  150,   22,   52,  174,  175,
91406 /*  1050 */    22,  102,   20,  165,  109,  165,  165,  165,  150,  165,
91407 /*  1060 */   165,  150,  174,  175,  174,  175,   49,   50,   24,   19,
91408 /*  1070 */    43,  104,   59,  165,  138,  104,  165,   25,   53,   53,
91409 /*  1080 */    22,    5,  174,  175,  193,  174,  175,   70,   71,   72,
91410 /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,    1,   82,
91411 /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
91412 /*  1110 */    19,   20,  150,   22,  150,  150,  150,   26,   27,  118,
91413 /*  1120 */   150,   35,  150,  150,   76,   27,  108,  165,   37,  165,
91414 /*  1130 */   165,  165,   76,   19,   20,  165,   22,  165,  165,  127,
91415 /*  1140 */    26,   27,   22,    1,  150,   16,   20,   56,  150,  150,
91416 /*  1150 */   119,   37,  150,  119,  160,  193,  150,   66,  193,  165,
91417 /*  1160 */   150,  150,  121,  165,  165,  108,  150,  165,  174,  175,
91418 /*  1170 */    56,  165,  150,  127,   22,  165,  165,   86,   87,   88,
91419 /*  1180 */    66,  165,   16,  150,   93,   94,   95,  165,  194,   98,
91420 /*  1190 */   174,  175,  128,   23,   15,   23,  174,  175,  165,  150,
91421 /*  1200 */    86,   87,   65,  140,  150,   22,    3,   93,   94,   95,
91422 /*  1210 */   216,    4,   98,  252,  165,  221,  150,  164,  180,  165,
91423 /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
91424 /*  1230 */   116,  165,   19,   20,  150,   22,  249,  252,  149,   26,
91425 /*  1240 */    27,  180,  165,  129,  130,  131,  132,  133,  134,  165,
91426 /*  1250 */    37,  174,  175,  150,    6,   19,   20,  150,   22,  150,
91427 /*  1260 */   150,  150,   26,   27,  149,  149,   13,  150,  165,   56,
91428 /*  1270 */   149,  159,  165,   37,  165,  165,  165,  174,  175,   66,
91429 /*  1280 */   146,  147,  165,  174,  175,   25,  152,  151,  154,  150,
91430 /*  1290 */   194,  151,   56,  116,  160,  150,  123,  202,  150,   86,
91431 /*  1300 */    87,  199,   66,  193,  165,  200,   93,   94,   95,  150,
91432 /*  1310 */   165,   98,  150,  165,  126,   22,  124,  150,  150,   26,
91433 /*  1320 */    27,  150,   86,   87,  165,  201,  150,  165,  194,   93,
91434 /*  1330 */    94,   95,  165,  165,   98,  150,  165,  122,  203,  125,
91435 /*  1340 */   227,  165,  129,  130,  131,  132,  133,  134,    5,  150,
91436 /*  1350 */   165,  135,  218,   10,   11,   12,   13,   14,  150,   66,
91437 /*  1360 */    17,  157,  118,  157,  165,  129,  130,  131,  132,  133,
91438 /*  1370 */   134,  150,  104,  165,   31,  210,   33,  176,  150,   86,
91439 /*  1380 */    87,  247,  174,  175,  150,   42,  165,   94,  121,  211,
91440 /*  1390 */   150,   98,  210,  165,  210,  174,  175,  211,   55,  165,
91441 /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
91442 /*  1410 */   104,  211,   47,  150,  174,  175,  165,  176,  176,  150,
91443 /*  1420 */   103,  165,  129,  130,  131,  174,  175,  184,  165,  179,
91444 /*  1430 */   174,  175,  150,  178,  165,  176,   22,  174,  175,  230,
91445 /*  1440 */    92,  230,  184,  174,  175,  150,  176,  165,  105,  106,
91446 /*  1450 */   107,  150,  176,  176,  111,  156,  174,  175,  179,  116,
91447 /*  1460 */   165,   18,  157,  156,  238,  157,  165,  156,   45,  174,
91448 /*  1470 */   175,  157,  157,  135,  239,  174,  175,  156,  189,  157,
91449 /*  1480 */    68,  189,  139,  219,   22,  199,  157,  192,   18,  192,
91450 /*  1490 */   192,  192,  199,  189,  219,  157,  243,   40,  243,  157,
91451 /*  1500 */   157,  246,   38,  153,  196,  198,  166,  233,  233,  228,
91452 /*  1510 */   177,  177,  209,  177,  182,  177,  166,  177,  166,  178,
91453 /*  1520 */   242,  199,  242,  209,  209,  199,  148,  196,  166,  208,
91454 /*  1530 */   195,  236,  237,  191,  208,  183,  183,  183,  186,  174,
91455 /*  1540 */   174,  186,   92,
91456};
91457#define YY_SHIFT_USE_DFLT (-90)
91458#define YY_SHIFT_COUNT (418)
91459#define YY_SHIFT_MIN   (-89)
91460#define YY_SHIFT_MAX   (1470)
91461static const short yy_shift_ofst[] = {
91462 /*     0 */   993, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
91463 /*    10 */  1213, 1213, 1213, 1213, 1213,  352,  517,  721, 1091, 1213,
91464 /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
91465 /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
91466 /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
91467 /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
91468 /*    60 */  1213,  -49,  199,  517,  517,  913,  913,  382, 1177,   55,
91469 /*    70 */   647,  573,  499,  425,  351,  277,  203,  129,  795,  795,
91470 /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
91471 /*    90 */   795,  795,  795,  795,  795,  795,  869,  795,  943, 1017,
91472 /*   100 */  1017,  -69,  -69,  -69,  -69,   -1,   -1,   58,  138,  -44,
91473 /*   110 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
91474 /*   120 */   517,  517,  517,  517,  517,  517,  202,  579,  517,  517,
91475 /*   130 */   517,  517,  517,  382,  885, 1450,  -90,  -90,  -90, 1293,
91476 /*   140 */    73,  272,  272,  309,  311,  297,  282,  216,  602,  538,
91477 /*   150 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
91478 /*   160 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
91479 /*   170 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
91480 /*   180 */   517,  517,  505,  231,  231,  231,  706,   64, 1177, 1177,
91481 /*   190 */  1177,  -90,  -90,  -90,  136,  168,  168,   12,  496,  496,
91482 /*   200 */   496,  506,  423,  512,  370,  349,  335,  149,  149,  149,
91483 /*   210 */   149,  604,  516,  149,  149,  508,    3,  299,  677,  871,
91484 /*   220 */   613,  613,  879,  871,  879,  144,  382,  226,  382,  226,
91485 /*   230 */   564,  226,  613,  226,  226,  404,  625,  625,  382,  426,
91486 /*   240 */   -89,  801, 1464, 1244, 1244, 1457, 1457, 1244, 1462, 1412,
91487 /*   250 */  1188, 1470, 1470, 1470, 1470, 1244, 1188, 1462, 1412, 1412,
91488 /*   260 */  1244, 1443, 1338, 1423, 1244, 1244, 1443, 1244, 1443, 1244,
91489 /*   270 */  1443, 1414, 1306, 1306, 1306, 1365, 1348, 1348, 1414, 1306,
91490 /*   280 */  1317, 1306, 1365, 1306, 1306, 1267, 1268, 1267, 1268, 1267,
91491 /*   290 */  1268, 1244, 1244, 1216, 1214, 1215, 1192, 1173, 1188, 1177,
91492 /*   300 */  1260, 1253, 1253, 1248, 1248, 1248, 1248,  -90,  -90,  -90,
91493 /*   310 */   -90,  -90,  -90,  939,  102,  614,   84,  133,   14,  837,
91494 /*   320 */   396,  829,  825,  796,  757,  751,  650,  357,  244,  107,
91495 /*   330 */    54,  305,  278, 1207, 1203, 1183, 1063, 1179, 1137, 1166,
91496 /*   340 */  1172, 1170, 1064, 1152, 1046, 1057, 1034, 1126, 1041, 1129,
91497 /*   350 */  1142, 1031, 1120, 1012, 1056, 1048, 1018, 1098, 1086, 1001,
91498 /*   360 */  1097, 1076, 1058,  971,  936, 1026, 1052, 1025, 1013, 1027,
91499 /*   370 */   967, 1044, 1032, 1050,  945,  949, 1028,  995, 1024, 1021,
91500 /*   380 */   963,  981,  928,  953,  951,  870,  876,  897,  838,  720,
91501 /*   390 */   828,  794,  820,  498,  642,  783,  657,  729,  642,  557,
91502 /*   400 */   507,  509,  497,  470,  478,  449,  294,  228,  443,   23,
91503 /*   410 */   152,  123,   68,  -20,  -42,   57,   39,   -3,    5,
91504};
91505#define YY_REDUCE_USE_DFLT (-222)
91506#define YY_REDUCE_COUNT (312)
91507#define YY_REDUCE_MIN   (-221)
91508#define YY_REDUCE_MAX   (1378)
91509static const short yy_reduce_ofst[] = {
91510 /*     0 */   310,  994, 1134,  221,  169,  157,   89,   18,   83,  301,
91511 /*    10 */   377,  316,  312,   16,  295,  238,  249,  391, 1301, 1295,
91512 /*    20 */  1282, 1269, 1263, 1256, 1251, 1240, 1234, 1228, 1221, 1208,
91513 /*    30 */  1109, 1103, 1077, 1054, 1022, 1016,  911,  908,  890,  888,
91514 /*    40 */   874,  816,  800,  760,  742,  739,  726,  684,  672,  665,
91515 /*    50 */   652,  612,  610,  594,  591,  578,  530,  528,  526,  524,
91516 /*    60 */   -72, -221,  399,  469,  445,  438,  143,  222,  359,  523,
91517 /*    70 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
91518 /*    80 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
91519 /*    90 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
91520 /*   100 */   523,  523,  523,  523,  523,  523,  523,  307,  523,  523,
91521 /*   110 */  1110,  678, 1033,  965,  962,  891,  814,  813,  744,  771,
91522 /*   120 */   691,  607,  522,  743,  686,  740,  328,  418,  670,  666,
91523 /*   130 */   596,  527,  529,  583,  523,  523,  523,  523,  523,  593,
91524 /*   140 */   823,  738,  712,  892, 1199, 1185, 1176, 1171,  673,  673,
91525 /*   150 */  1168, 1167, 1162, 1159, 1148, 1145, 1139, 1117, 1111, 1107,
91526 /*   160 */  1084, 1066, 1049, 1011, 1010, 1006, 1002,  999,  998,  973,
91527 /*   170 */   972,  970,  966,  964,  895,  894,  892,  833,  822,  762,
91528 /*   180 */   761,  229,  811,  804,  803,  389,  688,  808,  807,  737,
91529 /*   190 */   460,  464,  572,  584, 1355, 1366, 1365, 1352, 1354, 1353,
91530 /*   200 */  1352, 1326, 1335, 1342, 1335, 1335, 1335, 1335, 1335, 1335,
91531 /*   210 */  1335, 1295, 1295, 1335, 1335, 1321, 1362, 1331, 1378, 1326,
91532 /*   220 */  1315, 1314, 1280, 1322, 1278, 1341, 1352, 1340, 1350, 1338,
91533 /*   230 */  1332, 1336, 1303, 1334, 1333, 1281, 1275, 1274, 1340, 1307,
91534 /*   240 */  1308, 1350, 1255, 1343, 1342, 1255, 1253, 1338, 1275, 1304,
91535 /*   250 */  1293, 1299, 1298, 1297, 1295, 1329, 1286, 1264, 1292, 1289,
91536 /*   260 */  1322, 1321, 1235, 1226, 1315, 1314, 1311, 1308, 1307, 1305,
91537 /*   270 */  1299, 1279, 1277, 1276, 1270, 1258, 1211, 1209, 1250, 1259,
91538 /*   280 */  1255, 1242, 1243, 1241, 1201, 1200, 1184, 1186, 1182, 1178,
91539 /*   290 */  1165, 1206, 1204, 1113, 1135, 1095, 1124, 1105, 1102, 1096,
91540 /*   300 */  1112, 1140, 1136, 1121, 1116, 1115, 1089,  985,  961,  987,
91541 /*   310 */  1061, 1038, 1053,
91542};
91543static const YYACTIONTYPE yy_default[] = {
91544 /*     0 */   636,  872,  961,  961,  961,  872,  901,  901,  961,  760,
91545 /*    10 */   961,  961,  961,  961,  870,  961,  961,  935,  961,  961,
91546 /*    20 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91547 /*    30 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91548 /*    40 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91549 /*    50 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91550 /*    60 */   961,  844,  961,  961,  961,  901,  901,  675,  764,  795,
91551 /*    70 */   961,  961,  961,  961,  961,  961,  961,  961,  934,  936,
91552 /*    80 */   810,  809,  803,  802,  914,  775,  800,  793,  786,  797,
91553 /*    90 */   873,  866,  867,  865,  869,  874,  961,  796,  832,  850,
91554 /*   100 */   831,  849,  856,  848,  834,  843,  833,  667,  835,  836,
91555 /*   110 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91556 /*   120 */   961,  961,  961,  961,  961,  961,  662,  729,  961,  961,
91557 /*   130 */   961,  961,  961,  961,  837,  838,  853,  852,  851,  961,
91558 /*   140 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91559 /*   150 */   961,  941,  939,  961,  885,  961,  961,  961,  961,  961,
91560 /*   160 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91561 /*   170 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91562 /*   180 */   961,  642,  961,  760,  760,  760,  636,  961,  961,  961,
91563 /*   190 */   961,  953,  764,  754,  720,  961,  961,  961,  961,  961,
91564 /*   200 */   961,  961,  961,  961,  961,  961,  961,  805,  743,  924,
91565 /*   210 */   926,  961,  907,  741,  664,  762,  677,  752,  644,  799,
91566 /*   220 */   777,  777,  919,  799,  919,  701,  961,  789,  961,  789,
91567 /*   230 */   698,  789,  777,  789,  789,  868,  961,  961,  961,  761,
91568 /*   240 */   752,  961,  946,  768,  768,  938,  938,  768,  811,  733,
91569 /*   250 */   799,  740,  740,  740,  740,  768,  799,  811,  733,  733,
91570 /*   260 */   768,  659,  913,  911,  768,  768,  659,  768,  659,  768,
91571 /*   270 */   659,  878,  731,  731,  731,  716,  882,  882,  878,  731,
91572 /*   280 */   701,  731,  716,  731,  731,  781,  776,  781,  776,  781,
91573 /*   290 */   776,  768,  768,  961,  794,  782,  792,  790,  799,  961,
91574 /*   300 */   719,  652,  652,  641,  641,  641,  641,  958,  958,  953,
91575 /*   310 */   703,  703,  685,  961,  961,  961,  961,  961,  961,  961,
91576 /*   320 */   887,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91577 /*   330 */   961,  961,  961,  961,  637,  948,  961,  961,  945,  961,
91578 /*   340 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91579 /*   350 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  917,
91580 /*   360 */   961,  961,  961,  961,  961,  961,  910,  909,  961,  961,
91581 /*   370 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91582 /*   380 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91583 /*   390 */   961,  961,  961,  961,  791,  961,  783,  961,  871,  961,
91584 /*   400 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  746,
91585 /*   410 */   820,  961,  819,  823,  818,  669,  961,  650,  961,  633,
91586 /*   420 */   638,  957,  960,  959,  956,  955,  954,  949,  947,  944,
91587 /*   430 */   943,  942,  940,  937,  933,  891,  889,  896,  895,  894,
91588 /*   440 */   893,  892,  890,  888,  886,  806,  804,  801,  798,  932,
91589 /*   450 */   884,  742,  739,  738,  658,  950,  916,  925,  923,  812,
91590 /*   460 */   922,  921,  920,  918,  915,  902,  808,  807,  734,  876,
91591 /*   470 */   875,  661,  906,  905,  904,  908,  912,  903,  770,  660,
91592 /*   480 */   657,  666,  723,  722,  730,  728,  727,  726,  725,  724,
91593 /*   490 */   721,  668,  676,  687,  715,  700,  699,  881,  883,  880,
91594 /*   500 */   879,  708,  707,  713,  712,  711,  710,  709,  706,  705,
91595 /*   510 */   704,  697,  696,  702,  695,  718,  717,  714,  694,  737,
91596 /*   520 */   736,  735,  732,  693,  692,  691,  823,  690,  689,  829,
91597 /*   530 */   828,  816,  860,  757,  756,  755,  767,  766,  779,  778,
91598 /*   540 */   814,  813,  780,  765,  759,  758,  774,  773,  772,  771,
91599 /*   550 */   763,  753,  785,  788,  787,  784,  845,  862,  769,  859,
91600 /*   560 */   931,  930,  929,  928,  927,  864,  863,  830,  827,  680,
91601 /*   570 */   681,  900,  898,  899,  897,  683,  682,  679,  678,  861,
91602 /*   580 */   748,  747,  857,  854,  846,  841,  858,  855,  847,  842,
91603 /*   590 */   840,  839,  825,  824,  822,  821,  817,  826,  671,  749,
91604 /*   600 */   745,  744,  815,  751,  750,  688,  686,  684,  665,  663,
91605 /*   610 */   656,  654,  653,  655,  651,  649,  648,  647,  646,  645,
91606 /*   620 */   674,  673,  672,  670,  669,  643,  640,  639,  635,  634,
91607 /*   630 */   632,
91608};
91609
91610/* The next table maps tokens into fallback tokens.  If a construct
91611** like the following:
91612**
91613**      %fallback ID X Y Z.
91614**
91615** appears in the grammar, then ID becomes a fallback token for X, Y,
91616** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
91617** but it does not parse, the type of the token is changed to ID and
91618** the parse is retried before an error is thrown.
91619*/
91620#ifdef YYFALLBACK
91621static const YYCODETYPE yyFallback[] = {
91622    0,  /*          $ => nothing */
91623    0,  /*       SEMI => nothing */
91624   26,  /*    EXPLAIN => ID */
91625   26,  /*      QUERY => ID */
91626   26,  /*       PLAN => ID */
91627   26,  /*      BEGIN => ID */
91628    0,  /* TRANSACTION => nothing */
91629   26,  /*   DEFERRED => ID */
91630   26,  /*  IMMEDIATE => ID */
91631   26,  /*  EXCLUSIVE => ID */
91632    0,  /*     COMMIT => nothing */
91633   26,  /*        END => ID */
91634   26,  /*   ROLLBACK => ID */
91635   26,  /*  SAVEPOINT => ID */
91636   26,  /*    RELEASE => ID */
91637    0,  /*         TO => nothing */
91638    0,  /*      TABLE => nothing */
91639    0,  /*     CREATE => nothing */
91640   26,  /*         IF => ID */
91641    0,  /*        NOT => nothing */
91642    0,  /*     EXISTS => nothing */
91643   26,  /*       TEMP => ID */
91644    0,  /*         LP => nothing */
91645    0,  /*         RP => nothing */
91646    0,  /*         AS => nothing */
91647    0,  /*      COMMA => nothing */
91648    0,  /*         ID => nothing */
91649    0,  /*    INDEXED => nothing */
91650   26,  /*      ABORT => ID */
91651   26,  /*     ACTION => ID */
91652   26,  /*      AFTER => ID */
91653   26,  /*    ANALYZE => ID */
91654   26,  /*        ASC => ID */
91655   26,  /*     ATTACH => ID */
91656   26,  /*     BEFORE => ID */
91657   26,  /*         BY => ID */
91658   26,  /*    CASCADE => ID */
91659   26,  /*       CAST => ID */
91660   26,  /*   COLUMNKW => ID */
91661   26,  /*   CONFLICT => ID */
91662   26,  /*   DATABASE => ID */
91663   26,  /*       DESC => ID */
91664   26,  /*     DETACH => ID */
91665   26,  /*       EACH => ID */
91666   26,  /*       FAIL => ID */
91667   26,  /*        FOR => ID */
91668   26,  /*     IGNORE => ID */
91669   26,  /*  INITIALLY => ID */
91670   26,  /*    INSTEAD => ID */
91671   26,  /*    LIKE_KW => ID */
91672   26,  /*      MATCH => ID */
91673   26,  /*         NO => ID */
91674   26,  /*        KEY => ID */
91675   26,  /*         OF => ID */
91676   26,  /*     OFFSET => ID */
91677   26,  /*     PRAGMA => ID */
91678   26,  /*      RAISE => ID */
91679   26,  /*    REPLACE => ID */
91680   26,  /*   RESTRICT => ID */
91681   26,  /*        ROW => ID */
91682   26,  /*    TRIGGER => ID */
91683   26,  /*     VACUUM => ID */
91684   26,  /*       VIEW => ID */
91685   26,  /*    VIRTUAL => ID */
91686   26,  /*    REINDEX => ID */
91687   26,  /*     RENAME => ID */
91688   26,  /*   CTIME_KW => ID */
91689};
91690#endif /* YYFALLBACK */
91691
91692/* The following structure represents a single element of the
91693** parser's stack.  Information stored includes:
91694**
91695**   +  The state number for the parser at this level of the stack.
91696**
91697**   +  The value of the token stored at this level of the stack.
91698**      (In other words, the "major" token.)
91699**
91700**   +  The semantic value stored at this level of the stack.  This is
91701**      the information used by the action routines in the grammar.
91702**      It is sometimes called the "minor" token.
91703*/
91704struct yyStackEntry {
91705  YYACTIONTYPE stateno;  /* The state-number */
91706  YYCODETYPE major;      /* The major token value.  This is the code
91707                         ** number for the token at this stack level */
91708  YYMINORTYPE minor;     /* The user-supplied minor token value.  This
91709                         ** is the value of the token  */
91710};
91711typedef struct yyStackEntry yyStackEntry;
91712
91713/* The state of the parser is completely contained in an instance of
91714** the following structure */
91715struct yyParser {
91716  int yyidx;                    /* Index of top element in stack */
91717#ifdef YYTRACKMAXSTACKDEPTH
91718  int yyidxMax;                 /* Maximum value of yyidx */
91719#endif
91720  int yyerrcnt;                 /* Shifts left before out of the error */
91721  sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
91722#if YYSTACKDEPTH<=0
91723  int yystksz;                  /* Current side of the stack */
91724  yyStackEntry *yystack;        /* The parser's stack */
91725#else
91726  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
91727#endif
91728};
91729typedef struct yyParser yyParser;
91730
91731#ifndef NDEBUG
91732static FILE *yyTraceFILE = 0;
91733static char *yyTracePrompt = 0;
91734#endif /* NDEBUG */
91735
91736#ifndef NDEBUG
91737/*
91738** Turn parser tracing on by giving a stream to which to write the trace
91739** and a prompt to preface each trace message.  Tracing is turned off
91740** by making either argument NULL
91741**
91742** Inputs:
91743** <ul>
91744** <li> A FILE* to which trace output should be written.
91745**      If NULL, then tracing is turned off.
91746** <li> A prefix string written at the beginning of every
91747**      line of trace output.  If NULL, then tracing is
91748**      turned off.
91749** </ul>
91750**
91751** Outputs:
91752** None.
91753*/
91754SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
91755  yyTraceFILE = TraceFILE;
91756  yyTracePrompt = zTracePrompt;
91757  if( yyTraceFILE==0 ) yyTracePrompt = 0;
91758  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
91759}
91760#endif /* NDEBUG */
91761
91762#ifndef NDEBUG
91763/* For tracing shifts, the names of all terminals and nonterminals
91764** are required.  The following table supplies these names */
91765static const char *const yyTokenName[] = {
91766  "$",             "SEMI",          "EXPLAIN",       "QUERY",
91767  "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
91768  "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
91769  "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
91770  "TABLE",         "CREATE",        "IF",            "NOT",
91771  "EXISTS",        "TEMP",          "LP",            "RP",
91772  "AS",            "COMMA",         "ID",            "INDEXED",
91773  "ABORT",         "ACTION",        "AFTER",         "ANALYZE",
91774  "ASC",           "ATTACH",        "BEFORE",        "BY",
91775  "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",
91776  "DATABASE",      "DESC",          "DETACH",        "EACH",
91777  "FAIL",          "FOR",           "IGNORE",        "INITIALLY",
91778  "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",
91779  "KEY",           "OF",            "OFFSET",        "PRAGMA",
91780  "RAISE",         "REPLACE",       "RESTRICT",      "ROW",
91781  "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",
91782  "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",
91783  "OR",            "AND",           "IS",            "BETWEEN",
91784  "IN",            "ISNULL",        "NOTNULL",       "NE",
91785  "EQ",            "GT",            "LE",            "LT",
91786  "GE",            "ESCAPE",        "BITAND",        "BITOR",
91787  "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",
91788  "STAR",          "SLASH",         "REM",           "CONCAT",
91789  "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",
91790  "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",
91791  "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",
91792  "ON",            "INSERT",        "DELETE",        "UPDATE",
91793  "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",
91794  "UNION",         "ALL",           "EXCEPT",        "INTERSECT",
91795  "SELECT",        "DISTINCT",      "DOT",           "FROM",
91796  "JOIN",          "USING",         "ORDER",         "GROUP",
91797  "HAVING",        "LIMIT",         "WHERE",         "INTO",
91798  "VALUES",        "INTEGER",       "FLOAT",         "BLOB",
91799  "REGISTER",      "VARIABLE",      "CASE",          "WHEN",
91800  "THEN",          "ELSE",          "INDEX",         "ALTER",
91801  "ADD",           "error",         "input",         "cmdlist",
91802  "ecmd",          "explain",       "cmdx",          "cmd",
91803  "transtype",     "trans_opt",     "nm",            "savepoint_opt",
91804  "create_table",  "create_table_args",  "createkw",      "temp",
91805  "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
91806  "select",        "column",        "columnid",      "type",
91807  "carglist",      "id",            "ids",           "typetoken",
91808  "typename",      "signed",        "plus_num",      "minus_num",
91809  "carg",          "ccons",         "term",          "expr",
91810  "onconf",        "sortorder",     "autoinc",       "idxlist_opt",
91811  "refargs",       "defer_subclause",  "refarg",        "refact",
91812  "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",
91813  "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",
91814  "ifexists",      "fullname",      "oneselect",     "multiselect_op",
91815  "distinct",      "selcollist",    "from",          "where_opt",
91816  "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",
91817  "sclp",          "as",            "seltablist",    "stl_prefix",
91818  "joinop",        "indexed_opt",   "on_opt",        "using_opt",
91819  "joinop2",       "inscollist",    "sortlist",      "sortitem",
91820  "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
91821  "itemlist",      "exprlist",      "likeop",        "escape",
91822  "between_op",    "in_op",         "case_operand",  "case_exprlist",
91823  "case_else",     "uniqueflag",    "collate",       "nmnum",
91824  "plus_opt",      "number",        "trigger_decl",  "trigger_cmd_list",
91825  "trigger_time",  "trigger_event",  "foreach_clause",  "when_clause",
91826  "trigger_cmd",   "trnm",          "tridxby",       "database_kw_opt",
91827  "key_opt",       "add_column_fullname",  "kwcolumn_opt",  "create_vtab",
91828  "vtabarglist",   "vtabarg",       "vtabargtoken",  "lp",
91829  "anylist",
91830};
91831#endif /* NDEBUG */
91832
91833#ifndef NDEBUG
91834/* For tracing reduce actions, the names of all rules are required.
91835*/
91836static const char *const yyRuleName[] = {
91837 /*   0 */ "input ::= cmdlist",
91838 /*   1 */ "cmdlist ::= cmdlist ecmd",
91839 /*   2 */ "cmdlist ::= ecmd",
91840 /*   3 */ "ecmd ::= SEMI",
91841 /*   4 */ "ecmd ::= explain cmdx SEMI",
91842 /*   5 */ "explain ::=",
91843 /*   6 */ "explain ::= EXPLAIN",
91844 /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
91845 /*   8 */ "cmdx ::= cmd",
91846 /*   9 */ "cmd ::= BEGIN transtype trans_opt",
91847 /*  10 */ "trans_opt ::=",
91848 /*  11 */ "trans_opt ::= TRANSACTION",
91849 /*  12 */ "trans_opt ::= TRANSACTION nm",
91850 /*  13 */ "transtype ::=",
91851 /*  14 */ "transtype ::= DEFERRED",
91852 /*  15 */ "transtype ::= IMMEDIATE",
91853 /*  16 */ "transtype ::= EXCLUSIVE",
91854 /*  17 */ "cmd ::= COMMIT trans_opt",
91855 /*  18 */ "cmd ::= END trans_opt",
91856 /*  19 */ "cmd ::= ROLLBACK trans_opt",
91857 /*  20 */ "savepoint_opt ::= SAVEPOINT",
91858 /*  21 */ "savepoint_opt ::=",
91859 /*  22 */ "cmd ::= SAVEPOINT nm",
91860 /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
91861 /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
91862 /*  25 */ "cmd ::= create_table create_table_args",
91863 /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
91864 /*  27 */ "createkw ::= CREATE",
91865 /*  28 */ "ifnotexists ::=",
91866 /*  29 */ "ifnotexists ::= IF NOT EXISTS",
91867 /*  30 */ "temp ::= TEMP",
91868 /*  31 */ "temp ::=",
91869 /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
91870 /*  33 */ "create_table_args ::= AS select",
91871 /*  34 */ "columnlist ::= columnlist COMMA column",
91872 /*  35 */ "columnlist ::= column",
91873 /*  36 */ "column ::= columnid type carglist",
91874 /*  37 */ "columnid ::= nm",
91875 /*  38 */ "id ::= ID",
91876 /*  39 */ "id ::= INDEXED",
91877 /*  40 */ "ids ::= ID|STRING",
91878 /*  41 */ "nm ::= id",
91879 /*  42 */ "nm ::= STRING",
91880 /*  43 */ "nm ::= JOIN_KW",
91881 /*  44 */ "type ::=",
91882 /*  45 */ "type ::= typetoken",
91883 /*  46 */ "typetoken ::= typename",
91884 /*  47 */ "typetoken ::= typename LP signed RP",
91885 /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
91886 /*  49 */ "typename ::= ids",
91887 /*  50 */ "typename ::= typename ids",
91888 /*  51 */ "signed ::= plus_num",
91889 /*  52 */ "signed ::= minus_num",
91890 /*  53 */ "carglist ::= carglist carg",
91891 /*  54 */ "carglist ::=",
91892 /*  55 */ "carg ::= CONSTRAINT nm ccons",
91893 /*  56 */ "carg ::= ccons",
91894 /*  57 */ "ccons ::= DEFAULT term",
91895 /*  58 */ "ccons ::= DEFAULT LP expr RP",
91896 /*  59 */ "ccons ::= DEFAULT PLUS term",
91897 /*  60 */ "ccons ::= DEFAULT MINUS term",
91898 /*  61 */ "ccons ::= DEFAULT id",
91899 /*  62 */ "ccons ::= NULL onconf",
91900 /*  63 */ "ccons ::= NOT NULL onconf",
91901 /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
91902 /*  65 */ "ccons ::= UNIQUE onconf",
91903 /*  66 */ "ccons ::= CHECK LP expr RP",
91904 /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
91905 /*  68 */ "ccons ::= defer_subclause",
91906 /*  69 */ "ccons ::= COLLATE ids",
91907 /*  70 */ "autoinc ::=",
91908 /*  71 */ "autoinc ::= AUTOINCR",
91909 /*  72 */ "refargs ::=",
91910 /*  73 */ "refargs ::= refargs refarg",
91911 /*  74 */ "refarg ::= MATCH nm",
91912 /*  75 */ "refarg ::= ON INSERT refact",
91913 /*  76 */ "refarg ::= ON DELETE refact",
91914 /*  77 */ "refarg ::= ON UPDATE refact",
91915 /*  78 */ "refact ::= SET NULL",
91916 /*  79 */ "refact ::= SET DEFAULT",
91917 /*  80 */ "refact ::= CASCADE",
91918 /*  81 */ "refact ::= RESTRICT",
91919 /*  82 */ "refact ::= NO ACTION",
91920 /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
91921 /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
91922 /*  85 */ "init_deferred_pred_opt ::=",
91923 /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
91924 /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
91925 /*  88 */ "conslist_opt ::=",
91926 /*  89 */ "conslist_opt ::= COMMA conslist",
91927 /*  90 */ "conslist ::= conslist COMMA tcons",
91928 /*  91 */ "conslist ::= conslist tcons",
91929 /*  92 */ "conslist ::= tcons",
91930 /*  93 */ "tcons ::= CONSTRAINT nm",
91931 /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
91932 /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
91933 /*  96 */ "tcons ::= CHECK LP expr RP onconf",
91934 /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
91935 /*  98 */ "defer_subclause_opt ::=",
91936 /*  99 */ "defer_subclause_opt ::= defer_subclause",
91937 /* 100 */ "onconf ::=",
91938 /* 101 */ "onconf ::= ON CONFLICT resolvetype",
91939 /* 102 */ "orconf ::=",
91940 /* 103 */ "orconf ::= OR resolvetype",
91941 /* 104 */ "resolvetype ::= raisetype",
91942 /* 105 */ "resolvetype ::= IGNORE",
91943 /* 106 */ "resolvetype ::= REPLACE",
91944 /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
91945 /* 108 */ "ifexists ::= IF EXISTS",
91946 /* 109 */ "ifexists ::=",
91947 /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
91948 /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
91949 /* 112 */ "cmd ::= select",
91950 /* 113 */ "select ::= oneselect",
91951 /* 114 */ "select ::= select multiselect_op oneselect",
91952 /* 115 */ "multiselect_op ::= UNION",
91953 /* 116 */ "multiselect_op ::= UNION ALL",
91954 /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
91955 /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
91956 /* 119 */ "distinct ::= DISTINCT",
91957 /* 120 */ "distinct ::= ALL",
91958 /* 121 */ "distinct ::=",
91959 /* 122 */ "sclp ::= selcollist COMMA",
91960 /* 123 */ "sclp ::=",
91961 /* 124 */ "selcollist ::= sclp expr as",
91962 /* 125 */ "selcollist ::= sclp STAR",
91963 /* 126 */ "selcollist ::= sclp nm DOT STAR",
91964 /* 127 */ "as ::= AS nm",
91965 /* 128 */ "as ::= ids",
91966 /* 129 */ "as ::=",
91967 /* 130 */ "from ::=",
91968 /* 131 */ "from ::= FROM seltablist",
91969 /* 132 */ "stl_prefix ::= seltablist joinop",
91970 /* 133 */ "stl_prefix ::=",
91971 /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
91972 /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
91973 /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
91974 /* 137 */ "dbnm ::=",
91975 /* 138 */ "dbnm ::= DOT nm",
91976 /* 139 */ "fullname ::= nm dbnm",
91977 /* 140 */ "joinop ::= COMMA|JOIN",
91978 /* 141 */ "joinop ::= JOIN_KW JOIN",
91979 /* 142 */ "joinop ::= JOIN_KW nm JOIN",
91980 /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
91981 /* 144 */ "on_opt ::= ON expr",
91982 /* 145 */ "on_opt ::=",
91983 /* 146 */ "indexed_opt ::=",
91984 /* 147 */ "indexed_opt ::= INDEXED BY nm",
91985 /* 148 */ "indexed_opt ::= NOT INDEXED",
91986 /* 149 */ "using_opt ::= USING LP inscollist RP",
91987 /* 150 */ "using_opt ::=",
91988 /* 151 */ "orderby_opt ::=",
91989 /* 152 */ "orderby_opt ::= ORDER BY sortlist",
91990 /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
91991 /* 154 */ "sortlist ::= sortitem sortorder",
91992 /* 155 */ "sortitem ::= expr",
91993 /* 156 */ "sortorder ::= ASC",
91994 /* 157 */ "sortorder ::= DESC",
91995 /* 158 */ "sortorder ::=",
91996 /* 159 */ "groupby_opt ::=",
91997 /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
91998 /* 161 */ "having_opt ::=",
91999 /* 162 */ "having_opt ::= HAVING expr",
92000 /* 163 */ "limit_opt ::=",
92001 /* 164 */ "limit_opt ::= LIMIT expr",
92002 /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
92003 /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
92004 /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
92005 /* 168 */ "where_opt ::=",
92006 /* 169 */ "where_opt ::= WHERE expr",
92007 /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
92008 /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
92009 /* 172 */ "setlist ::= nm EQ expr",
92010 /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
92011 /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
92012 /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
92013 /* 176 */ "insert_cmd ::= INSERT orconf",
92014 /* 177 */ "insert_cmd ::= REPLACE",
92015 /* 178 */ "itemlist ::= itemlist COMMA expr",
92016 /* 179 */ "itemlist ::= expr",
92017 /* 180 */ "inscollist_opt ::=",
92018 /* 181 */ "inscollist_opt ::= LP inscollist RP",
92019 /* 182 */ "inscollist ::= inscollist COMMA nm",
92020 /* 183 */ "inscollist ::= nm",
92021 /* 184 */ "expr ::= term",
92022 /* 185 */ "expr ::= LP expr RP",
92023 /* 186 */ "term ::= NULL",
92024 /* 187 */ "expr ::= id",
92025 /* 188 */ "expr ::= JOIN_KW",
92026 /* 189 */ "expr ::= nm DOT nm",
92027 /* 190 */ "expr ::= nm DOT nm DOT nm",
92028 /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
92029 /* 192 */ "term ::= STRING",
92030 /* 193 */ "expr ::= REGISTER",
92031 /* 194 */ "expr ::= VARIABLE",
92032 /* 195 */ "expr ::= expr COLLATE ids",
92033 /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
92034 /* 197 */ "expr ::= ID LP distinct exprlist RP",
92035 /* 198 */ "expr ::= ID LP STAR RP",
92036 /* 199 */ "term ::= CTIME_KW",
92037 /* 200 */ "expr ::= expr AND expr",
92038 /* 201 */ "expr ::= expr OR expr",
92039 /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
92040 /* 203 */ "expr ::= expr EQ|NE expr",
92041 /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
92042 /* 205 */ "expr ::= expr PLUS|MINUS expr",
92043 /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
92044 /* 207 */ "expr ::= expr CONCAT expr",
92045 /* 208 */ "likeop ::= LIKE_KW",
92046 /* 209 */ "likeop ::= NOT LIKE_KW",
92047 /* 210 */ "likeop ::= MATCH",
92048 /* 211 */ "likeop ::= NOT MATCH",
92049 /* 212 */ "escape ::= ESCAPE expr",
92050 /* 213 */ "escape ::=",
92051 /* 214 */ "expr ::= expr likeop expr escape",
92052 /* 215 */ "expr ::= expr ISNULL|NOTNULL",
92053 /* 216 */ "expr ::= expr NOT NULL",
92054 /* 217 */ "expr ::= expr IS expr",
92055 /* 218 */ "expr ::= expr IS NOT expr",
92056 /* 219 */ "expr ::= NOT expr",
92057 /* 220 */ "expr ::= BITNOT expr",
92058 /* 221 */ "expr ::= MINUS expr",
92059 /* 222 */ "expr ::= PLUS expr",
92060 /* 223 */ "between_op ::= BETWEEN",
92061 /* 224 */ "between_op ::= NOT BETWEEN",
92062 /* 225 */ "expr ::= expr between_op expr AND expr",
92063 /* 226 */ "in_op ::= IN",
92064 /* 227 */ "in_op ::= NOT IN",
92065 /* 228 */ "expr ::= expr in_op LP exprlist RP",
92066 /* 229 */ "expr ::= LP select RP",
92067 /* 230 */ "expr ::= expr in_op LP select RP",
92068 /* 231 */ "expr ::= expr in_op nm dbnm",
92069 /* 232 */ "expr ::= EXISTS LP select RP",
92070 /* 233 */ "expr ::= CASE case_operand case_exprlist case_else END",
92071 /* 234 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
92072 /* 235 */ "case_exprlist ::= WHEN expr THEN expr",
92073 /* 236 */ "case_else ::= ELSE expr",
92074 /* 237 */ "case_else ::=",
92075 /* 238 */ "case_operand ::= expr",
92076 /* 239 */ "case_operand ::=",
92077 /* 240 */ "exprlist ::= nexprlist",
92078 /* 241 */ "exprlist ::=",
92079 /* 242 */ "nexprlist ::= nexprlist COMMA expr",
92080 /* 243 */ "nexprlist ::= expr",
92081 /* 244 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
92082 /* 245 */ "uniqueflag ::= UNIQUE",
92083 /* 246 */ "uniqueflag ::=",
92084 /* 247 */ "idxlist_opt ::=",
92085 /* 248 */ "idxlist_opt ::= LP idxlist RP",
92086 /* 249 */ "idxlist ::= idxlist COMMA nm collate sortorder",
92087 /* 250 */ "idxlist ::= nm collate sortorder",
92088 /* 251 */ "collate ::=",
92089 /* 252 */ "collate ::= COLLATE ids",
92090 /* 253 */ "cmd ::= DROP INDEX ifexists fullname",
92091 /* 254 */ "cmd ::= VACUUM",
92092 /* 255 */ "cmd ::= VACUUM nm",
92093 /* 256 */ "cmd ::= PRAGMA nm dbnm",
92094 /* 257 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
92095 /* 258 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
92096 /* 259 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
92097 /* 260 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
92098 /* 261 */ "nmnum ::= plus_num",
92099 /* 262 */ "nmnum ::= nm",
92100 /* 263 */ "nmnum ::= ON",
92101 /* 264 */ "nmnum ::= DELETE",
92102 /* 265 */ "nmnum ::= DEFAULT",
92103 /* 266 */ "plus_num ::= plus_opt number",
92104 /* 267 */ "minus_num ::= MINUS number",
92105 /* 268 */ "number ::= INTEGER|FLOAT",
92106 /* 269 */ "plus_opt ::= PLUS",
92107 /* 270 */ "plus_opt ::=",
92108 /* 271 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
92109 /* 272 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
92110 /* 273 */ "trigger_time ::= BEFORE",
92111 /* 274 */ "trigger_time ::= AFTER",
92112 /* 275 */ "trigger_time ::= INSTEAD OF",
92113 /* 276 */ "trigger_time ::=",
92114 /* 277 */ "trigger_event ::= DELETE|INSERT",
92115 /* 278 */ "trigger_event ::= UPDATE",
92116 /* 279 */ "trigger_event ::= UPDATE OF inscollist",
92117 /* 280 */ "foreach_clause ::=",
92118 /* 281 */ "foreach_clause ::= FOR EACH ROW",
92119 /* 282 */ "when_clause ::=",
92120 /* 283 */ "when_clause ::= WHEN expr",
92121 /* 284 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
92122 /* 285 */ "trigger_cmd_list ::= trigger_cmd SEMI",
92123 /* 286 */ "trnm ::= nm",
92124 /* 287 */ "trnm ::= nm DOT nm",
92125 /* 288 */ "tridxby ::=",
92126 /* 289 */ "tridxby ::= INDEXED BY nm",
92127 /* 290 */ "tridxby ::= NOT INDEXED",
92128 /* 291 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
92129 /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
92130 /* 293 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
92131 /* 294 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
92132 /* 295 */ "trigger_cmd ::= select",
92133 /* 296 */ "expr ::= RAISE LP IGNORE RP",
92134 /* 297 */ "expr ::= RAISE LP raisetype COMMA nm RP",
92135 /* 298 */ "raisetype ::= ROLLBACK",
92136 /* 299 */ "raisetype ::= ABORT",
92137 /* 300 */ "raisetype ::= FAIL",
92138 /* 301 */ "cmd ::= DROP TRIGGER ifexists fullname",
92139 /* 302 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
92140 /* 303 */ "cmd ::= DETACH database_kw_opt expr",
92141 /* 304 */ "key_opt ::=",
92142 /* 305 */ "key_opt ::= KEY expr",
92143 /* 306 */ "database_kw_opt ::= DATABASE",
92144 /* 307 */ "database_kw_opt ::=",
92145 /* 308 */ "cmd ::= REINDEX",
92146 /* 309 */ "cmd ::= REINDEX nm dbnm",
92147 /* 310 */ "cmd ::= ANALYZE",
92148 /* 311 */ "cmd ::= ANALYZE nm dbnm",
92149 /* 312 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
92150 /* 313 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
92151 /* 314 */ "add_column_fullname ::= fullname",
92152 /* 315 */ "kwcolumn_opt ::=",
92153 /* 316 */ "kwcolumn_opt ::= COLUMNKW",
92154 /* 317 */ "cmd ::= create_vtab",
92155 /* 318 */ "cmd ::= create_vtab LP vtabarglist RP",
92156 /* 319 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
92157 /* 320 */ "vtabarglist ::= vtabarg",
92158 /* 321 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
92159 /* 322 */ "vtabarg ::=",
92160 /* 323 */ "vtabarg ::= vtabarg vtabargtoken",
92161 /* 324 */ "vtabargtoken ::= ANY",
92162 /* 325 */ "vtabargtoken ::= lp anylist RP",
92163 /* 326 */ "lp ::= LP",
92164 /* 327 */ "anylist ::=",
92165 /* 328 */ "anylist ::= anylist LP anylist RP",
92166 /* 329 */ "anylist ::= anylist ANY",
92167};
92168#endif /* NDEBUG */
92169
92170
92171#if YYSTACKDEPTH<=0
92172/*
92173** Try to increase the size of the parser stack.
92174*/
92175static void yyGrowStack(yyParser *p){
92176  int newSize;
92177  yyStackEntry *pNew;
92178
92179  newSize = p->yystksz*2 + 100;
92180  pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
92181  if( pNew ){
92182    p->yystack = pNew;
92183    p->yystksz = newSize;
92184#ifndef NDEBUG
92185    if( yyTraceFILE ){
92186      fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
92187              yyTracePrompt, p->yystksz);
92188    }
92189#endif
92190  }
92191}
92192#endif
92193
92194/*
92195** This function allocates a new parser.
92196** The only argument is a pointer to a function which works like
92197** malloc.
92198**
92199** Inputs:
92200** A pointer to the function used to allocate memory.
92201**
92202** Outputs:
92203** A pointer to a parser.  This pointer is used in subsequent calls
92204** to sqlite3Parser and sqlite3ParserFree.
92205*/
92206SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
92207  yyParser *pParser;
92208  pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
92209  if( pParser ){
92210    pParser->yyidx = -1;
92211#ifdef YYTRACKMAXSTACKDEPTH
92212    pParser->yyidxMax = 0;
92213#endif
92214#if YYSTACKDEPTH<=0
92215    pParser->yystack = NULL;
92216    pParser->yystksz = 0;
92217    yyGrowStack(pParser);
92218#endif
92219  }
92220  return pParser;
92221}
92222
92223/* The following function deletes the value associated with a
92224** symbol.  The symbol can be either a terminal or nonterminal.
92225** "yymajor" is the symbol code, and "yypminor" is a pointer to
92226** the value.
92227*/
92228static void yy_destructor(
92229  yyParser *yypParser,    /* The parser */
92230  YYCODETYPE yymajor,     /* Type code for object to destroy */
92231  YYMINORTYPE *yypminor   /* The object to be destroyed */
92232){
92233  sqlite3ParserARG_FETCH;
92234  switch( yymajor ){
92235    /* Here is inserted the actions which take place when a
92236    ** terminal or non-terminal is destroyed.  This can happen
92237    ** when the symbol is popped from the stack during a
92238    ** reduce or during error processing or when a parser is
92239    ** being destroyed before it is finished parsing.
92240    **
92241    ** Note: during a reduce, the only symbols destroyed are those
92242    ** which appear on the RHS of the rule, but which are not used
92243    ** inside the C code.
92244    */
92245    case 160: /* select */
92246    case 194: /* oneselect */
92247{
92248sqlite3SelectDelete(pParse->db, (yypminor->yy3));
92249}
92250      break;
92251    case 174: /* term */
92252    case 175: /* expr */
92253    case 223: /* escape */
92254{
92255sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
92256}
92257      break;
92258    case 179: /* idxlist_opt */
92259    case 187: /* idxlist */
92260    case 197: /* selcollist */
92261    case 200: /* groupby_opt */
92262    case 202: /* orderby_opt */
92263    case 204: /* sclp */
92264    case 214: /* sortlist */
92265    case 216: /* nexprlist */
92266    case 217: /* setlist */
92267    case 220: /* itemlist */
92268    case 221: /* exprlist */
92269    case 227: /* case_exprlist */
92270{
92271sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
92272}
92273      break;
92274    case 193: /* fullname */
92275    case 198: /* from */
92276    case 206: /* seltablist */
92277    case 207: /* stl_prefix */
92278{
92279sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
92280}
92281      break;
92282    case 199: /* where_opt */
92283    case 201: /* having_opt */
92284    case 210: /* on_opt */
92285    case 215: /* sortitem */
92286    case 226: /* case_operand */
92287    case 228: /* case_else */
92288    case 239: /* when_clause */
92289    case 244: /* key_opt */
92290{
92291sqlite3ExprDelete(pParse->db, (yypminor->yy132));
92292}
92293      break;
92294    case 211: /* using_opt */
92295    case 213: /* inscollist */
92296    case 219: /* inscollist_opt */
92297{
92298sqlite3IdListDelete(pParse->db, (yypminor->yy408));
92299}
92300      break;
92301    case 235: /* trigger_cmd_list */
92302    case 240: /* trigger_cmd */
92303{
92304sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
92305}
92306      break;
92307    case 237: /* trigger_event */
92308{
92309sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
92310}
92311      break;
92312    default:  break;   /* If no destructor action specified: do nothing */
92313  }
92314}
92315
92316/*
92317** Pop the parser's stack once.
92318**
92319** If there is a destructor routine associated with the token which
92320** is popped from the stack, then call it.
92321**
92322** Return the major token number for the symbol popped.
92323*/
92324static int yy_pop_parser_stack(yyParser *pParser){
92325  YYCODETYPE yymajor;
92326  yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
92327
92328  /* There is no mechanism by which the parser stack can be popped below
92329  ** empty in SQLite.  */
92330  if( NEVER(pParser->yyidx<0) ) return 0;
92331#ifndef NDEBUG
92332  if( yyTraceFILE && pParser->yyidx>=0 ){
92333    fprintf(yyTraceFILE,"%sPopping %s\n",
92334      yyTracePrompt,
92335      yyTokenName[yytos->major]);
92336  }
92337#endif
92338  yymajor = yytos->major;
92339  yy_destructor(pParser, yymajor, &yytos->minor);
92340  pParser->yyidx--;
92341  return yymajor;
92342}
92343
92344/*
92345** Deallocate and destroy a parser.  Destructors are all called for
92346** all stack elements before shutting the parser down.
92347**
92348** Inputs:
92349** <ul>
92350** <li>  A pointer to the parser.  This should be a pointer
92351**       obtained from sqlite3ParserAlloc.
92352** <li>  A pointer to a function used to reclaim memory obtained
92353**       from malloc.
92354** </ul>
92355*/
92356SQLITE_PRIVATE void sqlite3ParserFree(
92357  void *p,                    /* The parser to be deleted */
92358  void (*freeProc)(void*)     /* Function used to reclaim memory */
92359){
92360  yyParser *pParser = (yyParser*)p;
92361  /* In SQLite, we never try to destroy a parser that was not successfully
92362  ** created in the first place. */
92363  if( NEVER(pParser==0) ) return;
92364  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
92365#if YYSTACKDEPTH<=0
92366  free(pParser->yystack);
92367#endif
92368  (*freeProc)((void*)pParser);
92369}
92370
92371/*
92372** Return the peak depth of the stack for a parser.
92373*/
92374#ifdef YYTRACKMAXSTACKDEPTH
92375SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
92376  yyParser *pParser = (yyParser*)p;
92377  return pParser->yyidxMax;
92378}
92379#endif
92380
92381/*
92382** Find the appropriate action for a parser given the terminal
92383** look-ahead token iLookAhead.
92384**
92385** If the look-ahead token is YYNOCODE, then check to see if the action is
92386** independent of the look-ahead.  If it is, return the action, otherwise
92387** return YY_NO_ACTION.
92388*/
92389static int yy_find_shift_action(
92390  yyParser *pParser,        /* The parser */
92391  YYCODETYPE iLookAhead     /* The look-ahead token */
92392){
92393  int i;
92394  int stateno = pParser->yystack[pParser->yyidx].stateno;
92395
92396  if( stateno>YY_SHIFT_COUNT
92397   || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
92398    return yy_default[stateno];
92399  }
92400  assert( iLookAhead!=YYNOCODE );
92401  i += iLookAhead;
92402  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
92403    if( iLookAhead>0 ){
92404#ifdef YYFALLBACK
92405      YYCODETYPE iFallback;            /* Fallback token */
92406      if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
92407             && (iFallback = yyFallback[iLookAhead])!=0 ){
92408#ifndef NDEBUG
92409        if( yyTraceFILE ){
92410          fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
92411             yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
92412        }
92413#endif
92414        return yy_find_shift_action(pParser, iFallback);
92415      }
92416#endif
92417#ifdef YYWILDCARD
92418      {
92419        int j = i - iLookAhead + YYWILDCARD;
92420        if(
92421#if YY_SHIFT_MIN+YYWILDCARD<0
92422          j>=0 &&
92423#endif
92424#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
92425          j<YY_ACTTAB_COUNT &&
92426#endif
92427          yy_lookahead[j]==YYWILDCARD
92428        ){
92429#ifndef NDEBUG
92430          if( yyTraceFILE ){
92431            fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
92432               yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
92433          }
92434#endif /* NDEBUG */
92435          return yy_action[j];
92436        }
92437      }
92438#endif /* YYWILDCARD */
92439    }
92440    return yy_default[stateno];
92441  }else{
92442    return yy_action[i];
92443  }
92444}
92445
92446/*
92447** Find the appropriate action for a parser given the non-terminal
92448** look-ahead token iLookAhead.
92449**
92450** If the look-ahead token is YYNOCODE, then check to see if the action is
92451** independent of the look-ahead.  If it is, return the action, otherwise
92452** return YY_NO_ACTION.
92453*/
92454static int yy_find_reduce_action(
92455  int stateno,              /* Current state number */
92456  YYCODETYPE iLookAhead     /* The look-ahead token */
92457){
92458  int i;
92459#ifdef YYERRORSYMBOL
92460  if( stateno>YY_REDUCE_COUNT ){
92461    return yy_default[stateno];
92462  }
92463#else
92464  assert( stateno<=YY_REDUCE_COUNT );
92465#endif
92466  i = yy_reduce_ofst[stateno];
92467  assert( i!=YY_REDUCE_USE_DFLT );
92468  assert( iLookAhead!=YYNOCODE );
92469  i += iLookAhead;
92470#ifdef YYERRORSYMBOL
92471  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
92472    return yy_default[stateno];
92473  }
92474#else
92475  assert( i>=0 && i<YY_ACTTAB_COUNT );
92476  assert( yy_lookahead[i]==iLookAhead );
92477#endif
92478  return yy_action[i];
92479}
92480
92481/*
92482** The following routine is called if the stack overflows.
92483*/
92484static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
92485   sqlite3ParserARG_FETCH;
92486   yypParser->yyidx--;
92487#ifndef NDEBUG
92488   if( yyTraceFILE ){
92489     fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
92490   }
92491#endif
92492   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
92493   /* Here code is inserted which will execute if the parser
92494   ** stack every overflows */
92495
92496  UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
92497  sqlite3ErrorMsg(pParse, "parser stack overflow");
92498  pParse->parseError = 1;
92499   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
92500}
92501
92502/*
92503** Perform a shift action.
92504*/
92505static void yy_shift(
92506  yyParser *yypParser,          /* The parser to be shifted */
92507  int yyNewState,               /* The new state to shift in */
92508  int yyMajor,                  /* The major token to shift in */
92509  YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
92510){
92511  yyStackEntry *yytos;
92512  yypParser->yyidx++;
92513#ifdef YYTRACKMAXSTACKDEPTH
92514  if( yypParser->yyidx>yypParser->yyidxMax ){
92515    yypParser->yyidxMax = yypParser->yyidx;
92516  }
92517#endif
92518#if YYSTACKDEPTH>0
92519  if( yypParser->yyidx>=YYSTACKDEPTH ){
92520    yyStackOverflow(yypParser, yypMinor);
92521    return;
92522  }
92523#else
92524  if( yypParser->yyidx>=yypParser->yystksz ){
92525    yyGrowStack(yypParser);
92526    if( yypParser->yyidx>=yypParser->yystksz ){
92527      yyStackOverflow(yypParser, yypMinor);
92528      return;
92529    }
92530  }
92531#endif
92532  yytos = &yypParser->yystack[yypParser->yyidx];
92533  yytos->stateno = (YYACTIONTYPE)yyNewState;
92534  yytos->major = (YYCODETYPE)yyMajor;
92535  yytos->minor = *yypMinor;
92536#ifndef NDEBUG
92537  if( yyTraceFILE && yypParser->yyidx>0 ){
92538    int i;
92539    fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
92540    fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
92541    for(i=1; i<=yypParser->yyidx; i++)
92542      fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
92543    fprintf(yyTraceFILE,"\n");
92544  }
92545#endif
92546}
92547
92548/* The following table contains information about every rule that
92549** is used during the reduce.
92550*/
92551static const struct {
92552  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
92553  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
92554} yyRuleInfo[] = {
92555  { 142, 1 },
92556  { 143, 2 },
92557  { 143, 1 },
92558  { 144, 1 },
92559  { 144, 3 },
92560  { 145, 0 },
92561  { 145, 1 },
92562  { 145, 3 },
92563  { 146, 1 },
92564  { 147, 3 },
92565  { 149, 0 },
92566  { 149, 1 },
92567  { 149, 2 },
92568  { 148, 0 },
92569  { 148, 1 },
92570  { 148, 1 },
92571  { 148, 1 },
92572  { 147, 2 },
92573  { 147, 2 },
92574  { 147, 2 },
92575  { 151, 1 },
92576  { 151, 0 },
92577  { 147, 2 },
92578  { 147, 3 },
92579  { 147, 5 },
92580  { 147, 2 },
92581  { 152, 6 },
92582  { 154, 1 },
92583  { 156, 0 },
92584  { 156, 3 },
92585  { 155, 1 },
92586  { 155, 0 },
92587  { 153, 4 },
92588  { 153, 2 },
92589  { 158, 3 },
92590  { 158, 1 },
92591  { 161, 3 },
92592  { 162, 1 },
92593  { 165, 1 },
92594  { 165, 1 },
92595  { 166, 1 },
92596  { 150, 1 },
92597  { 150, 1 },
92598  { 150, 1 },
92599  { 163, 0 },
92600  { 163, 1 },
92601  { 167, 1 },
92602  { 167, 4 },
92603  { 167, 6 },
92604  { 168, 1 },
92605  { 168, 2 },
92606  { 169, 1 },
92607  { 169, 1 },
92608  { 164, 2 },
92609  { 164, 0 },
92610  { 172, 3 },
92611  { 172, 1 },
92612  { 173, 2 },
92613  { 173, 4 },
92614  { 173, 3 },
92615  { 173, 3 },
92616  { 173, 2 },
92617  { 173, 2 },
92618  { 173, 3 },
92619  { 173, 5 },
92620  { 173, 2 },
92621  { 173, 4 },
92622  { 173, 4 },
92623  { 173, 1 },
92624  { 173, 2 },
92625  { 178, 0 },
92626  { 178, 1 },
92627  { 180, 0 },
92628  { 180, 2 },
92629  { 182, 2 },
92630  { 182, 3 },
92631  { 182, 3 },
92632  { 182, 3 },
92633  { 183, 2 },
92634  { 183, 2 },
92635  { 183, 1 },
92636  { 183, 1 },
92637  { 183, 2 },
92638  { 181, 3 },
92639  { 181, 2 },
92640  { 184, 0 },
92641  { 184, 2 },
92642  { 184, 2 },
92643  { 159, 0 },
92644  { 159, 2 },
92645  { 185, 3 },
92646  { 185, 2 },
92647  { 185, 1 },
92648  { 186, 2 },
92649  { 186, 7 },
92650  { 186, 5 },
92651  { 186, 5 },
92652  { 186, 10 },
92653  { 188, 0 },
92654  { 188, 1 },
92655  { 176, 0 },
92656  { 176, 3 },
92657  { 189, 0 },
92658  { 189, 2 },
92659  { 190, 1 },
92660  { 190, 1 },
92661  { 190, 1 },
92662  { 147, 4 },
92663  { 192, 2 },
92664  { 192, 0 },
92665  { 147, 8 },
92666  { 147, 4 },
92667  { 147, 1 },
92668  { 160, 1 },
92669  { 160, 3 },
92670  { 195, 1 },
92671  { 195, 2 },
92672  { 195, 1 },
92673  { 194, 9 },
92674  { 196, 1 },
92675  { 196, 1 },
92676  { 196, 0 },
92677  { 204, 2 },
92678  { 204, 0 },
92679  { 197, 3 },
92680  { 197, 2 },
92681  { 197, 4 },
92682  { 205, 2 },
92683  { 205, 1 },
92684  { 205, 0 },
92685  { 198, 0 },
92686  { 198, 2 },
92687  { 207, 2 },
92688  { 207, 0 },
92689  { 206, 7 },
92690  { 206, 7 },
92691  { 206, 7 },
92692  { 157, 0 },
92693  { 157, 2 },
92694  { 193, 2 },
92695  { 208, 1 },
92696  { 208, 2 },
92697  { 208, 3 },
92698  { 208, 4 },
92699  { 210, 2 },
92700  { 210, 0 },
92701  { 209, 0 },
92702  { 209, 3 },
92703  { 209, 2 },
92704  { 211, 4 },
92705  { 211, 0 },
92706  { 202, 0 },
92707  { 202, 3 },
92708  { 214, 4 },
92709  { 214, 2 },
92710  { 215, 1 },
92711  { 177, 1 },
92712  { 177, 1 },
92713  { 177, 0 },
92714  { 200, 0 },
92715  { 200, 3 },
92716  { 201, 0 },
92717  { 201, 2 },
92718  { 203, 0 },
92719  { 203, 2 },
92720  { 203, 4 },
92721  { 203, 4 },
92722  { 147, 5 },
92723  { 199, 0 },
92724  { 199, 2 },
92725  { 147, 7 },
92726  { 217, 5 },
92727  { 217, 3 },
92728  { 147, 8 },
92729  { 147, 5 },
92730  { 147, 6 },
92731  { 218, 2 },
92732  { 218, 1 },
92733  { 220, 3 },
92734  { 220, 1 },
92735  { 219, 0 },
92736  { 219, 3 },
92737  { 213, 3 },
92738  { 213, 1 },
92739  { 175, 1 },
92740  { 175, 3 },
92741  { 174, 1 },
92742  { 175, 1 },
92743  { 175, 1 },
92744  { 175, 3 },
92745  { 175, 5 },
92746  { 174, 1 },
92747  { 174, 1 },
92748  { 175, 1 },
92749  { 175, 1 },
92750  { 175, 3 },
92751  { 175, 6 },
92752  { 175, 5 },
92753  { 175, 4 },
92754  { 174, 1 },
92755  { 175, 3 },
92756  { 175, 3 },
92757  { 175, 3 },
92758  { 175, 3 },
92759  { 175, 3 },
92760  { 175, 3 },
92761  { 175, 3 },
92762  { 175, 3 },
92763  { 222, 1 },
92764  { 222, 2 },
92765  { 222, 1 },
92766  { 222, 2 },
92767  { 223, 2 },
92768  { 223, 0 },
92769  { 175, 4 },
92770  { 175, 2 },
92771  { 175, 3 },
92772  { 175, 3 },
92773  { 175, 4 },
92774  { 175, 2 },
92775  { 175, 2 },
92776  { 175, 2 },
92777  { 175, 2 },
92778  { 224, 1 },
92779  { 224, 2 },
92780  { 175, 5 },
92781  { 225, 1 },
92782  { 225, 2 },
92783  { 175, 5 },
92784  { 175, 3 },
92785  { 175, 5 },
92786  { 175, 4 },
92787  { 175, 4 },
92788  { 175, 5 },
92789  { 227, 5 },
92790  { 227, 4 },
92791  { 228, 2 },
92792  { 228, 0 },
92793  { 226, 1 },
92794  { 226, 0 },
92795  { 221, 1 },
92796  { 221, 0 },
92797  { 216, 3 },
92798  { 216, 1 },
92799  { 147, 11 },
92800  { 229, 1 },
92801  { 229, 0 },
92802  { 179, 0 },
92803  { 179, 3 },
92804  { 187, 5 },
92805  { 187, 3 },
92806  { 230, 0 },
92807  { 230, 2 },
92808  { 147, 4 },
92809  { 147, 1 },
92810  { 147, 2 },
92811  { 147, 3 },
92812  { 147, 5 },
92813  { 147, 6 },
92814  { 147, 5 },
92815  { 147, 6 },
92816  { 231, 1 },
92817  { 231, 1 },
92818  { 231, 1 },
92819  { 231, 1 },
92820  { 231, 1 },
92821  { 170, 2 },
92822  { 171, 2 },
92823  { 233, 1 },
92824  { 232, 1 },
92825  { 232, 0 },
92826  { 147, 5 },
92827  { 234, 11 },
92828  { 236, 1 },
92829  { 236, 1 },
92830  { 236, 2 },
92831  { 236, 0 },
92832  { 237, 1 },
92833  { 237, 1 },
92834  { 237, 3 },
92835  { 238, 0 },
92836  { 238, 3 },
92837  { 239, 0 },
92838  { 239, 2 },
92839  { 235, 3 },
92840  { 235, 2 },
92841  { 241, 1 },
92842  { 241, 3 },
92843  { 242, 0 },
92844  { 242, 3 },
92845  { 242, 2 },
92846  { 240, 7 },
92847  { 240, 8 },
92848  { 240, 5 },
92849  { 240, 5 },
92850  { 240, 1 },
92851  { 175, 4 },
92852  { 175, 6 },
92853  { 191, 1 },
92854  { 191, 1 },
92855  { 191, 1 },
92856  { 147, 4 },
92857  { 147, 6 },
92858  { 147, 3 },
92859  { 244, 0 },
92860  { 244, 2 },
92861  { 243, 1 },
92862  { 243, 0 },
92863  { 147, 1 },
92864  { 147, 3 },
92865  { 147, 1 },
92866  { 147, 3 },
92867  { 147, 6 },
92868  { 147, 6 },
92869  { 245, 1 },
92870  { 246, 0 },
92871  { 246, 1 },
92872  { 147, 1 },
92873  { 147, 4 },
92874  { 247, 7 },
92875  { 248, 1 },
92876  { 248, 3 },
92877  { 249, 0 },
92878  { 249, 2 },
92879  { 250, 1 },
92880  { 250, 3 },
92881  { 251, 1 },
92882  { 252, 0 },
92883  { 252, 4 },
92884  { 252, 2 },
92885};
92886
92887static void yy_accept(yyParser*);  /* Forward Declaration */
92888
92889/*
92890** Perform a reduce action and the shift that must immediately
92891** follow the reduce.
92892*/
92893static void yy_reduce(
92894  yyParser *yypParser,         /* The parser */
92895  int yyruleno                 /* Number of the rule by which to reduce */
92896){
92897  int yygoto;                     /* The next state */
92898  int yyact;                      /* The next action */
92899  YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
92900  yyStackEntry *yymsp;            /* The top of the parser's stack */
92901  int yysize;                     /* Amount to pop the stack */
92902  sqlite3ParserARG_FETCH;
92903  yymsp = &yypParser->yystack[yypParser->yyidx];
92904#ifndef NDEBUG
92905  if( yyTraceFILE && yyruleno>=0
92906        && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
92907    fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
92908      yyRuleName[yyruleno]);
92909  }
92910#endif /* NDEBUG */
92911
92912  /* Silence complaints from purify about yygotominor being uninitialized
92913  ** in some cases when it is copied into the stack after the following
92914  ** switch.  yygotominor is uninitialized when a rule reduces that does
92915  ** not set the value of its left-hand side nonterminal.  Leaving the
92916  ** value of the nonterminal uninitialized is utterly harmless as long
92917  ** as the value is never used.  So really the only thing this code
92918  ** accomplishes is to quieten purify.
92919  **
92920  ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
92921  ** without this code, their parser segfaults.  I'm not sure what there
92922  ** parser is doing to make this happen.  This is the second bug report
92923  ** from wireshark this week.  Clearly they are stressing Lemon in ways
92924  ** that it has not been previously stressed...  (SQLite ticket #2172)
92925  */
92926  /*memset(&yygotominor, 0, sizeof(yygotominor));*/
92927  yygotominor = yyzerominor;
92928
92929
92930  switch( yyruleno ){
92931  /* Beginning here are the reduction cases.  A typical example
92932  ** follows:
92933  **   case 0:
92934  **  #line <lineno> <grammarfile>
92935  **     { ... }           // User supplied code
92936  **  #line <lineno> <thisfile>
92937  **     break;
92938  */
92939      case 5: /* explain ::= */
92940{ sqlite3BeginParse(pParse, 0); }
92941        break;
92942      case 6: /* explain ::= EXPLAIN */
92943{ sqlite3BeginParse(pParse, 1); }
92944        break;
92945      case 7: /* explain ::= EXPLAIN QUERY PLAN */
92946{ sqlite3BeginParse(pParse, 2); }
92947        break;
92948      case 8: /* cmdx ::= cmd */
92949{ sqlite3FinishCoding(pParse); }
92950        break;
92951      case 9: /* cmd ::= BEGIN transtype trans_opt */
92952{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
92953        break;
92954      case 13: /* transtype ::= */
92955{yygotominor.yy328 = (pParse->db->flags&SQLITE_BeginImmediate) ? TK_IMMEDIATE : TK_DEFERRED;}/* Android Change */
92956        break;
92957      case 14: /* transtype ::= DEFERRED */
92958      case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
92959      case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
92960      case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
92961      case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
92962{yygotominor.yy328 = yymsp[0].major;}
92963        break;
92964      case 17: /* cmd ::= COMMIT trans_opt */
92965      case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
92966{sqlite3CommitTransaction(pParse);}
92967        break;
92968      case 19: /* cmd ::= ROLLBACK trans_opt */
92969{sqlite3RollbackTransaction(pParse);}
92970        break;
92971      case 22: /* cmd ::= SAVEPOINT nm */
92972{
92973  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
92974}
92975        break;
92976      case 23: /* cmd ::= RELEASE savepoint_opt nm */
92977{
92978  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
92979}
92980        break;
92981      case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
92982{
92983  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
92984}
92985        break;
92986      case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
92987{
92988   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
92989}
92990        break;
92991      case 27: /* createkw ::= CREATE */
92992{
92993  pParse->db->lookaside.bEnabled = 0;
92994  yygotominor.yy0 = yymsp[0].minor.yy0;
92995}
92996        break;
92997      case 28: /* ifnotexists ::= */
92998      case 31: /* temp ::= */ yytestcase(yyruleno==31);
92999      case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
93000      case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
93001      case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
93002      case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
93003      case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
93004      case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
93005      case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
93006      case 121: /* distinct ::= */ yytestcase(yyruleno==121);
93007      case 223: /* between_op ::= BETWEEN */ yytestcase(yyruleno==223);
93008      case 226: /* in_op ::= IN */ yytestcase(yyruleno==226);
93009{yygotominor.yy328 = 0;}
93010        break;
93011      case 29: /* ifnotexists ::= IF NOT EXISTS */
93012      case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
93013      case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
93014      case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
93015      case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
93016      case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
93017      case 224: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==224);
93018      case 227: /* in_op ::= NOT IN */ yytestcase(yyruleno==227);
93019{yygotominor.yy328 = 1;}
93020        break;
93021      case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
93022{
93023  sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
93024}
93025        break;
93026      case 33: /* create_table_args ::= AS select */
93027{
93028  sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy3);
93029  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
93030}
93031        break;
93032      case 36: /* column ::= columnid type carglist */
93033{
93034  yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
93035  yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
93036}
93037        break;
93038      case 37: /* columnid ::= nm */
93039{
93040  sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
93041  yygotominor.yy0 = yymsp[0].minor.yy0;
93042}
93043        break;
93044      case 38: /* id ::= ID */
93045      case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
93046      case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
93047      case 41: /* nm ::= id */ yytestcase(yyruleno==41);
93048      case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
93049      case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
93050      case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
93051      case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
93052      case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
93053      case 128: /* as ::= ids */ yytestcase(yyruleno==128);
93054      case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
93055      case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
93056      case 252: /* collate ::= COLLATE ids */ yytestcase(yyruleno==252);
93057      case 261: /* nmnum ::= plus_num */ yytestcase(yyruleno==261);
93058      case 262: /* nmnum ::= nm */ yytestcase(yyruleno==262);
93059      case 263: /* nmnum ::= ON */ yytestcase(yyruleno==263);
93060      case 264: /* nmnum ::= DELETE */ yytestcase(yyruleno==264);
93061      case 265: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==265);
93062      case 266: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==266);
93063      case 267: /* minus_num ::= MINUS number */ yytestcase(yyruleno==267);
93064      case 268: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==268);
93065      case 286: /* trnm ::= nm */ yytestcase(yyruleno==286);
93066{yygotominor.yy0 = yymsp[0].minor.yy0;}
93067        break;
93068      case 45: /* type ::= typetoken */
93069{sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
93070        break;
93071      case 47: /* typetoken ::= typename LP signed RP */
93072{
93073  yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
93074  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
93075}
93076        break;
93077      case 48: /* typetoken ::= typename LP signed COMMA signed RP */
93078{
93079  yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
93080  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
93081}
93082        break;
93083      case 50: /* typename ::= typename ids */
93084{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);}
93085        break;
93086      case 57: /* ccons ::= DEFAULT term */
93087      case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
93088{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
93089        break;
93090      case 58: /* ccons ::= DEFAULT LP expr RP */
93091{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
93092        break;
93093      case 60: /* ccons ::= DEFAULT MINUS term */
93094{
93095  ExprSpan v;
93096  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
93097  v.zStart = yymsp[-1].minor.yy0.z;
93098  v.zEnd = yymsp[0].minor.yy346.zEnd;
93099  sqlite3AddDefaultValue(pParse,&v);
93100}
93101        break;
93102      case 61: /* ccons ::= DEFAULT id */
93103{
93104  ExprSpan v;
93105  spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
93106  sqlite3AddDefaultValue(pParse,&v);
93107}
93108        break;
93109      case 63: /* ccons ::= NOT NULL onconf */
93110{sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
93111        break;
93112      case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
93113{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
93114        break;
93115      case 65: /* ccons ::= UNIQUE onconf */
93116{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
93117        break;
93118      case 66: /* ccons ::= CHECK LP expr RP */
93119{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
93120        break;
93121      case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
93122{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
93123        break;
93124      case 68: /* ccons ::= defer_subclause */
93125{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
93126        break;
93127      case 69: /* ccons ::= COLLATE ids */
93128{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
93129        break;
93130      case 72: /* refargs ::= */
93131{ yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
93132        break;
93133      case 73: /* refargs ::= refargs refarg */
93134{ yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
93135        break;
93136      case 74: /* refarg ::= MATCH nm */
93137      case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
93138{ yygotominor.yy429.value = 0;     yygotominor.yy429.mask = 0x000000; }
93139        break;
93140      case 76: /* refarg ::= ON DELETE refact */
93141{ yygotominor.yy429.value = yymsp[0].minor.yy328;     yygotominor.yy429.mask = 0x0000ff; }
93142        break;
93143      case 77: /* refarg ::= ON UPDATE refact */
93144{ yygotominor.yy429.value = yymsp[0].minor.yy328<<8;  yygotominor.yy429.mask = 0x00ff00; }
93145        break;
93146      case 78: /* refact ::= SET NULL */
93147{ yygotominor.yy328 = OE_SetNull;  /* EV: R-33326-45252 */}
93148        break;
93149      case 79: /* refact ::= SET DEFAULT */
93150{ yygotominor.yy328 = OE_SetDflt;  /* EV: R-33326-45252 */}
93151        break;
93152      case 80: /* refact ::= CASCADE */
93153{ yygotominor.yy328 = OE_Cascade;  /* EV: R-33326-45252 */}
93154        break;
93155      case 81: /* refact ::= RESTRICT */
93156{ yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
93157        break;
93158      case 82: /* refact ::= NO ACTION */
93159{ yygotominor.yy328 = OE_None;     /* EV: R-33326-45252 */}
93160        break;
93161      case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
93162      case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
93163      case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
93164      case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
93165{yygotominor.yy328 = yymsp[0].minor.yy328;}
93166        break;
93167      case 88: /* conslist_opt ::= */
93168{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
93169        break;
93170      case 89: /* conslist_opt ::= COMMA conslist */
93171{yygotominor.yy0 = yymsp[-1].minor.yy0;}
93172        break;
93173      case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
93174{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
93175        break;
93176      case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
93177{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
93178        break;
93179      case 96: /* tcons ::= CHECK LP expr RP onconf */
93180{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
93181        break;
93182      case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
93183{
93184    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
93185    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
93186}
93187        break;
93188      case 100: /* onconf ::= */
93189{yygotominor.yy328 = OE_Default;}
93190        break;
93191      case 102: /* orconf ::= */
93192{yygotominor.yy186 = OE_Default;}
93193        break;
93194      case 103: /* orconf ::= OR resolvetype */
93195{yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
93196        break;
93197      case 105: /* resolvetype ::= IGNORE */
93198{yygotominor.yy328 = OE_Ignore;}
93199        break;
93200      case 106: /* resolvetype ::= REPLACE */
93201{yygotominor.yy328 = OE_Replace;}
93202        break;
93203      case 107: /* cmd ::= DROP TABLE ifexists fullname */
93204{
93205  sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
93206}
93207        break;
93208      case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
93209{
93210  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);
93211}
93212        break;
93213      case 111: /* cmd ::= DROP VIEW ifexists fullname */
93214{
93215  sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
93216}
93217        break;
93218      case 112: /* cmd ::= select */
93219{
93220  SelectDest dest = {SRT_Output, 0, 0, 0, 0};
93221  sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
93222  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
93223}
93224        break;
93225      case 113: /* select ::= oneselect */
93226{yygotominor.yy3 = yymsp[0].minor.yy3;}
93227        break;
93228      case 114: /* select ::= select multiselect_op oneselect */
93229{
93230  if( yymsp[0].minor.yy3 ){
93231    yymsp[0].minor.yy3->op = (u8)yymsp[-1].minor.yy328;
93232    yymsp[0].minor.yy3->pPrior = yymsp[-2].minor.yy3;
93233  }else{
93234    sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
93235  }
93236  yygotominor.yy3 = yymsp[0].minor.yy3;
93237}
93238        break;
93239      case 116: /* multiselect_op ::= UNION ALL */
93240{yygotominor.yy328 = TK_ALL;}
93241        break;
93242      case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
93243{
93244  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);
93245}
93246        break;
93247      case 122: /* sclp ::= selcollist COMMA */
93248      case 248: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==248);
93249{yygotominor.yy14 = yymsp[-1].minor.yy14;}
93250        break;
93251      case 123: /* sclp ::= */
93252      case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
93253      case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
93254      case 241: /* exprlist ::= */ yytestcase(yyruleno==241);
93255      case 247: /* idxlist_opt ::= */ yytestcase(yyruleno==247);
93256{yygotominor.yy14 = 0;}
93257        break;
93258      case 124: /* selcollist ::= sclp expr as */
93259{
93260   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
93261   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
93262   sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
93263}
93264        break;
93265      case 125: /* selcollist ::= sclp STAR */
93266{
93267  Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
93268  yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
93269}
93270        break;
93271      case 126: /* selcollist ::= sclp nm DOT STAR */
93272{
93273  Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
93274  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
93275  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
93276  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
93277}
93278        break;
93279      case 129: /* as ::= */
93280{yygotominor.yy0.n = 0;}
93281        break;
93282      case 130: /* from ::= */
93283{yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
93284        break;
93285      case 131: /* from ::= FROM seltablist */
93286{
93287  yygotominor.yy65 = yymsp[0].minor.yy65;
93288  sqlite3SrcListShiftJoinType(yygotominor.yy65);
93289}
93290        break;
93291      case 132: /* stl_prefix ::= seltablist joinop */
93292{
93293   yygotominor.yy65 = yymsp[-1].minor.yy65;
93294   if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
93295}
93296        break;
93297      case 133: /* stl_prefix ::= */
93298{yygotominor.yy65 = 0;}
93299        break;
93300      case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
93301{
93302  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);
93303  sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
93304}
93305        break;
93306      case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
93307{
93308    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);
93309  }
93310        break;
93311      case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
93312{
93313    if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
93314      yygotominor.yy65 = yymsp[-4].minor.yy65;
93315    }else{
93316      Select *pSubquery;
93317      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
93318      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,0,0,0);
93319      yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
93320    }
93321  }
93322        break;
93323      case 137: /* dbnm ::= */
93324      case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
93325{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
93326        break;
93327      case 139: /* fullname ::= nm dbnm */
93328{yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
93329        break;
93330      case 140: /* joinop ::= COMMA|JOIN */
93331{ yygotominor.yy328 = JT_INNER; }
93332        break;
93333      case 141: /* joinop ::= JOIN_KW JOIN */
93334{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
93335        break;
93336      case 142: /* joinop ::= JOIN_KW nm JOIN */
93337{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
93338        break;
93339      case 143: /* joinop ::= JOIN_KW nm nm JOIN */
93340{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
93341        break;
93342      case 144: /* on_opt ::= ON expr */
93343      case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
93344      case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
93345      case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
93346      case 236: /* case_else ::= ELSE expr */ yytestcase(yyruleno==236);
93347      case 238: /* case_operand ::= expr */ yytestcase(yyruleno==238);
93348{yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
93349        break;
93350      case 145: /* on_opt ::= */
93351      case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
93352      case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
93353      case 237: /* case_else ::= */ yytestcase(yyruleno==237);
93354      case 239: /* case_operand ::= */ yytestcase(yyruleno==239);
93355{yygotominor.yy132 = 0;}
93356        break;
93357      case 148: /* indexed_opt ::= NOT INDEXED */
93358{yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
93359        break;
93360      case 149: /* using_opt ::= USING LP inscollist RP */
93361      case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
93362{yygotominor.yy408 = yymsp[-1].minor.yy408;}
93363        break;
93364      case 150: /* using_opt ::= */
93365      case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
93366{yygotominor.yy408 = 0;}
93367        break;
93368      case 152: /* orderby_opt ::= ORDER BY sortlist */
93369      case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
93370      case 240: /* exprlist ::= nexprlist */ yytestcase(yyruleno==240);
93371{yygotominor.yy14 = yymsp[0].minor.yy14;}
93372        break;
93373      case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
93374{
93375  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy132);
93376  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
93377}
93378        break;
93379      case 154: /* sortlist ::= sortitem sortorder */
93380{
93381  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy132);
93382  if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
93383}
93384        break;
93385      case 156: /* sortorder ::= ASC */
93386      case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
93387{yygotominor.yy328 = SQLITE_SO_ASC;}
93388        break;
93389      case 157: /* sortorder ::= DESC */
93390{yygotominor.yy328 = SQLITE_SO_DESC;}
93391        break;
93392      case 163: /* limit_opt ::= */
93393{yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
93394        break;
93395      case 164: /* limit_opt ::= LIMIT expr */
93396{yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
93397        break;
93398      case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
93399{yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
93400        break;
93401      case 166: /* limit_opt ::= LIMIT expr COMMA expr */
93402{yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
93403        break;
93404      case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
93405{
93406  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
93407  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
93408}
93409        break;
93410      case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
93411{
93412  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
93413  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
93414  sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
93415}
93416        break;
93417      case 171: /* setlist ::= setlist COMMA nm EQ expr */
93418{
93419  yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
93420  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
93421}
93422        break;
93423      case 172: /* setlist ::= nm EQ expr */
93424{
93425  yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
93426  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
93427}
93428        break;
93429      case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
93430{sqlite3Insert(pParse, yymsp[-5].minor.yy65, yymsp[-1].minor.yy14, 0, yymsp[-4].minor.yy408, yymsp[-7].minor.yy186);}
93431        break;
93432      case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
93433{sqlite3Insert(pParse, yymsp[-2].minor.yy65, 0, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);}
93434        break;
93435      case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
93436{sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);}
93437        break;
93438      case 176: /* insert_cmd ::= INSERT orconf */
93439{yygotominor.yy186 = yymsp[0].minor.yy186;}
93440        break;
93441      case 177: /* insert_cmd ::= REPLACE */
93442{yygotominor.yy186 = OE_Replace;}
93443        break;
93444      case 178: /* itemlist ::= itemlist COMMA expr */
93445      case 242: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==242);
93446{yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
93447        break;
93448      case 179: /* itemlist ::= expr */
93449      case 243: /* nexprlist ::= expr */ yytestcase(yyruleno==243);
93450{yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
93451        break;
93452      case 182: /* inscollist ::= inscollist COMMA nm */
93453{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
93454        break;
93455      case 183: /* inscollist ::= nm */
93456{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
93457        break;
93458      case 184: /* expr ::= term */
93459      case 212: /* escape ::= ESCAPE expr */ yytestcase(yyruleno==212);
93460{yygotominor.yy346 = yymsp[0].minor.yy346;}
93461        break;
93462      case 185: /* expr ::= LP expr RP */
93463{yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
93464        break;
93465      case 186: /* term ::= NULL */
93466      case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
93467      case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
93468{spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
93469        break;
93470      case 187: /* expr ::= id */
93471      case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
93472{spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
93473        break;
93474      case 189: /* expr ::= nm DOT nm */
93475{
93476  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
93477  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
93478  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
93479  spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
93480}
93481        break;
93482      case 190: /* expr ::= nm DOT nm DOT nm */
93483{
93484  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
93485  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
93486  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
93487  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
93488  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
93489  spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
93490}
93491        break;
93492      case 193: /* expr ::= REGISTER */
93493{
93494  /* When doing a nested parse, one can include terms in an expression
93495  ** that look like this:   #1 #2 ...  These terms refer to registers
93496  ** in the virtual machine.  #N is the N-th register. */
93497  if( pParse->nested==0 ){
93498    sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
93499    yygotominor.yy346.pExpr = 0;
93500  }else{
93501    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
93502    if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
93503  }
93504  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
93505}
93506        break;
93507      case 194: /* expr ::= VARIABLE */
93508{
93509  spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
93510  sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
93511  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
93512}
93513        break;
93514      case 195: /* expr ::= expr COLLATE ids */
93515{
93516  yygotominor.yy346.pExpr = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0);
93517  yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
93518  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93519}
93520        break;
93521      case 196: /* expr ::= CAST LP expr AS typetoken RP */
93522{
93523  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
93524  spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
93525}
93526        break;
93527      case 197: /* expr ::= ID LP distinct exprlist RP */
93528{
93529  if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
93530    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
93531  }
93532  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
93533  spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
93534  if( yymsp[-2].minor.yy328 && yygotominor.yy346.pExpr ){
93535    yygotominor.yy346.pExpr->flags |= EP_Distinct;
93536  }
93537}
93538        break;
93539      case 198: /* expr ::= ID LP STAR RP */
93540{
93541  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
93542  spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
93543}
93544        break;
93545      case 199: /* term ::= CTIME_KW */
93546{
93547  /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
93548  ** treated as functions that return constants */
93549  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
93550  if( yygotominor.yy346.pExpr ){
93551    yygotominor.yy346.pExpr->op = TK_CONST_FUNC;
93552  }
93553  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
93554}
93555        break;
93556      case 200: /* expr ::= expr AND expr */
93557      case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
93558      case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
93559      case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
93560      case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
93561      case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
93562      case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
93563      case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
93564{spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
93565        break;
93566      case 208: /* likeop ::= LIKE_KW */
93567      case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
93568{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = 0;}
93569        break;
93570      case 209: /* likeop ::= NOT LIKE_KW */
93571      case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
93572{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = 1;}
93573        break;
93574      case 213: /* escape ::= */
93575{memset(&yygotominor.yy346,0,sizeof(yygotominor.yy346));}
93576        break;
93577      case 214: /* expr ::= expr likeop expr escape */
93578{
93579  ExprList *pList;
93580  pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy346.pExpr);
93581  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy346.pExpr);
93582  if( yymsp[0].minor.yy346.pExpr ){
93583    pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
93584  }
93585  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-2].minor.yy96.eOperator);
93586  if( yymsp[-2].minor.yy96.not ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93587  yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
93588  yygotominor.yy346.zEnd = yymsp[-1].minor.yy346.zEnd;
93589  if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
93590}
93591        break;
93592      case 215: /* expr ::= expr ISNULL|NOTNULL */
93593{spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
93594        break;
93595      case 216: /* expr ::= expr NOT NULL */
93596{spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
93597        break;
93598      case 217: /* expr ::= expr IS expr */
93599{
93600  spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
93601  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
93602}
93603        break;
93604      case 218: /* expr ::= expr IS NOT expr */
93605{
93606  spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
93607  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
93608}
93609        break;
93610      case 219: /* expr ::= NOT expr */
93611      case 220: /* expr ::= BITNOT expr */ yytestcase(yyruleno==220);
93612{spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
93613        break;
93614      case 221: /* expr ::= MINUS expr */
93615{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
93616        break;
93617      case 222: /* expr ::= PLUS expr */
93618{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
93619        break;
93620      case 225: /* expr ::= expr between_op expr AND expr */
93621{
93622  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
93623  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
93624  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
93625  if( yygotominor.yy346.pExpr ){
93626    yygotominor.yy346.pExpr->x.pList = pList;
93627  }else{
93628    sqlite3ExprListDelete(pParse->db, pList);
93629  }
93630  if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93631  yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
93632  yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
93633}
93634        break;
93635      case 228: /* expr ::= expr in_op LP exprlist RP */
93636{
93637    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
93638    if( yygotominor.yy346.pExpr ){
93639      yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
93640      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93641    }else{
93642      sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
93643    }
93644    if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93645    yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
93646    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93647  }
93648        break;
93649      case 229: /* expr ::= LP select RP */
93650{
93651    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
93652    if( yygotominor.yy346.pExpr ){
93653      yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
93654      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
93655      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93656    }else{
93657      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
93658    }
93659    yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
93660    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93661  }
93662        break;
93663      case 230: /* expr ::= expr in_op LP select RP */
93664{
93665    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
93666    if( yygotominor.yy346.pExpr ){
93667      yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
93668      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
93669      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93670    }else{
93671      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
93672    }
93673    if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93674    yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
93675    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93676  }
93677        break;
93678      case 231: /* expr ::= expr in_op nm dbnm */
93679{
93680    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
93681    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
93682    if( yygotominor.yy346.pExpr ){
93683      yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
93684      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
93685      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93686    }else{
93687      sqlite3SrcListDelete(pParse->db, pSrc);
93688    }
93689    if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93690    yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
93691    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];
93692  }
93693        break;
93694      case 232: /* expr ::= EXISTS LP select RP */
93695{
93696    Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
93697    if( p ){
93698      p->x.pSelect = yymsp[-1].minor.yy3;
93699      ExprSetProperty(p, EP_xIsSelect);
93700      sqlite3ExprSetHeight(pParse, p);
93701    }else{
93702      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
93703    }
93704    yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
93705    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93706  }
93707        break;
93708      case 233: /* expr ::= CASE case_operand case_exprlist case_else END */
93709{
93710  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, yymsp[-1].minor.yy132, 0);
93711  if( yygotominor.yy346.pExpr ){
93712    yygotominor.yy346.pExpr->x.pList = yymsp[-2].minor.yy14;
93713    sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93714  }else{
93715    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
93716  }
93717  yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
93718  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93719}
93720        break;
93721      case 234: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
93722{
93723  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
93724  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
93725}
93726        break;
93727      case 235: /* case_exprlist ::= WHEN expr THEN expr */
93728{
93729  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
93730  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
93731}
93732        break;
93733      case 244: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
93734{
93735  sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
93736                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy14, yymsp[-9].minor.yy328,
93737                      &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy328);
93738}
93739        break;
93740      case 245: /* uniqueflag ::= UNIQUE */
93741      case 299: /* raisetype ::= ABORT */ yytestcase(yyruleno==299);
93742{yygotominor.yy328 = OE_Abort;}
93743        break;
93744      case 246: /* uniqueflag ::= */
93745{yygotominor.yy328 = OE_None;}
93746        break;
93747      case 249: /* idxlist ::= idxlist COMMA nm collate sortorder */
93748{
93749  Expr *p = 0;
93750  if( yymsp[-1].minor.yy0.n>0 ){
93751    p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
93752    sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
93753  }
93754  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
93755  sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
93756  sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
93757  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
93758}
93759        break;
93760      case 250: /* idxlist ::= nm collate sortorder */
93761{
93762  Expr *p = 0;
93763  if( yymsp[-1].minor.yy0.n>0 ){
93764    p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
93765    sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
93766  }
93767  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
93768  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
93769  sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
93770  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
93771}
93772        break;
93773      case 251: /* collate ::= */
93774{yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
93775        break;
93776      case 253: /* cmd ::= DROP INDEX ifexists fullname */
93777{sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
93778        break;
93779      case 254: /* cmd ::= VACUUM */
93780      case 255: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==255);
93781{sqlite3Vacuum(pParse);}
93782        break;
93783      case 256: /* cmd ::= PRAGMA nm dbnm */
93784{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
93785        break;
93786      case 257: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
93787{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
93788        break;
93789      case 258: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
93790{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
93791        break;
93792      case 259: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
93793{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
93794        break;
93795      case 260: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
93796{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
93797        break;
93798      case 271: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
93799{
93800  Token all;
93801  all.z = yymsp[-3].minor.yy0.z;
93802  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
93803  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
93804}
93805        break;
93806      case 272: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
93807{
93808  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);
93809  yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
93810}
93811        break;
93812      case 273: /* trigger_time ::= BEFORE */
93813      case 276: /* trigger_time ::= */ yytestcase(yyruleno==276);
93814{ yygotominor.yy328 = TK_BEFORE; }
93815        break;
93816      case 274: /* trigger_time ::= AFTER */
93817{ yygotominor.yy328 = TK_AFTER;  }
93818        break;
93819      case 275: /* trigger_time ::= INSTEAD OF */
93820{ yygotominor.yy328 = TK_INSTEAD;}
93821        break;
93822      case 277: /* trigger_event ::= DELETE|INSERT */
93823      case 278: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==278);
93824{yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
93825        break;
93826      case 279: /* trigger_event ::= UPDATE OF inscollist */
93827{yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
93828        break;
93829      case 282: /* when_clause ::= */
93830      case 304: /* key_opt ::= */ yytestcase(yyruleno==304);
93831{ yygotominor.yy132 = 0; }
93832        break;
93833      case 283: /* when_clause ::= WHEN expr */
93834      case 305: /* key_opt ::= KEY expr */ yytestcase(yyruleno==305);
93835{ yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
93836        break;
93837      case 284: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
93838{
93839  assert( yymsp[-2].minor.yy473!=0 );
93840  yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
93841  yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
93842  yygotominor.yy473 = yymsp[-2].minor.yy473;
93843}
93844        break;
93845      case 285: /* trigger_cmd_list ::= trigger_cmd SEMI */
93846{
93847  assert( yymsp[-1].minor.yy473!=0 );
93848  yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
93849  yygotominor.yy473 = yymsp[-1].minor.yy473;
93850}
93851        break;
93852      case 287: /* trnm ::= nm DOT nm */
93853{
93854  yygotominor.yy0 = yymsp[0].minor.yy0;
93855  sqlite3ErrorMsg(pParse,
93856        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
93857        "statements within triggers");
93858}
93859        break;
93860      case 289: /* tridxby ::= INDEXED BY nm */
93861{
93862  sqlite3ErrorMsg(pParse,
93863        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
93864        "within triggers");
93865}
93866        break;
93867      case 290: /* tridxby ::= NOT INDEXED */
93868{
93869  sqlite3ErrorMsg(pParse,
93870        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
93871        "within triggers");
93872}
93873        break;
93874      case 291: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
93875{ yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
93876        break;
93877      case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
93878{yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy408, yymsp[-1].minor.yy14, 0, yymsp[-7].minor.yy186);}
93879        break;
93880      case 293: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
93881{yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, 0, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
93882        break;
93883      case 294: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
93884{yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
93885        break;
93886      case 295: /* trigger_cmd ::= select */
93887{yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
93888        break;
93889      case 296: /* expr ::= RAISE LP IGNORE RP */
93890{
93891  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
93892  if( yygotominor.yy346.pExpr ){
93893    yygotominor.yy346.pExpr->affinity = OE_Ignore;
93894  }
93895  yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
93896  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93897}
93898        break;
93899      case 297: /* expr ::= RAISE LP raisetype COMMA nm RP */
93900{
93901  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
93902  if( yygotominor.yy346.pExpr ) {
93903    yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
93904  }
93905  yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
93906  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93907}
93908        break;
93909      case 298: /* raisetype ::= ROLLBACK */
93910{yygotominor.yy328 = OE_Rollback;}
93911        break;
93912      case 300: /* raisetype ::= FAIL */
93913{yygotominor.yy328 = OE_Fail;}
93914        break;
93915      case 301: /* cmd ::= DROP TRIGGER ifexists fullname */
93916{
93917  sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
93918}
93919        break;
93920      case 302: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
93921{
93922  sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
93923}
93924        break;
93925      case 303: /* cmd ::= DETACH database_kw_opt expr */
93926{
93927  sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
93928}
93929        break;
93930      case 308: /* cmd ::= REINDEX */
93931{sqlite3Reindex(pParse, 0, 0);}
93932        break;
93933      case 309: /* cmd ::= REINDEX nm dbnm */
93934{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
93935        break;
93936      case 310: /* cmd ::= ANALYZE */
93937{sqlite3Analyze(pParse, 0, 0);}
93938        break;
93939      case 311: /* cmd ::= ANALYZE nm dbnm */
93940{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
93941        break;
93942      case 312: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
93943{
93944  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
93945}
93946        break;
93947      case 313: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
93948{
93949  sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
93950}
93951        break;
93952      case 314: /* add_column_fullname ::= fullname */
93953{
93954  pParse->db->lookaside.bEnabled = 0;
93955  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
93956}
93957        break;
93958      case 317: /* cmd ::= create_vtab */
93959{sqlite3VtabFinishParse(pParse,0);}
93960        break;
93961      case 318: /* cmd ::= create_vtab LP vtabarglist RP */
93962{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
93963        break;
93964      case 319: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
93965{
93966    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
93967}
93968        break;
93969      case 322: /* vtabarg ::= */
93970{sqlite3VtabArgInit(pParse);}
93971        break;
93972      case 324: /* vtabargtoken ::= ANY */
93973      case 325: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==325);
93974      case 326: /* lp ::= LP */ yytestcase(yyruleno==326);
93975{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
93976        break;
93977      default:
93978      /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
93979      /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
93980      /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
93981      /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
93982      /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
93983      /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
93984      /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
93985      /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
93986      /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
93987      /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
93988      /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
93989      /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
93990      /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
93991      /* (44) type ::= */ yytestcase(yyruleno==44);
93992      /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
93993      /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
93994      /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
93995      /* (54) carglist ::= */ yytestcase(yyruleno==54);
93996      /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
93997      /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
93998      /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
93999      /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
94000      /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
94001      /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
94002      /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
94003      /* (269) plus_opt ::= PLUS */ yytestcase(yyruleno==269);
94004      /* (270) plus_opt ::= */ yytestcase(yyruleno==270);
94005      /* (280) foreach_clause ::= */ yytestcase(yyruleno==280);
94006      /* (281) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==281);
94007      /* (288) tridxby ::= */ yytestcase(yyruleno==288);
94008      /* (306) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==306);
94009      /* (307) database_kw_opt ::= */ yytestcase(yyruleno==307);
94010      /* (315) kwcolumn_opt ::= */ yytestcase(yyruleno==315);
94011      /* (316) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==316);
94012      /* (320) vtabarglist ::= vtabarg */ yytestcase(yyruleno==320);
94013      /* (321) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==321);
94014      /* (323) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==323);
94015      /* (327) anylist ::= */ yytestcase(yyruleno==327);
94016      /* (328) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==328);
94017      /* (329) anylist ::= anylist ANY */ yytestcase(yyruleno==329);
94018        break;
94019  };
94020  yygoto = yyRuleInfo[yyruleno].lhs;
94021  yysize = yyRuleInfo[yyruleno].nrhs;
94022  yypParser->yyidx -= yysize;
94023  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
94024  if( yyact < YYNSTATE ){
94025#ifdef NDEBUG
94026    /* If we are not debugging and the reduce action popped at least
94027    ** one element off the stack, then we can push the new element back
94028    ** onto the stack here, and skip the stack overflow test in yy_shift().
94029    ** That gives a significant speed improvement. */
94030    if( yysize ){
94031      yypParser->yyidx++;
94032      yymsp -= yysize-1;
94033      yymsp->stateno = (YYACTIONTYPE)yyact;
94034      yymsp->major = (YYCODETYPE)yygoto;
94035      yymsp->minor = yygotominor;
94036    }else
94037#endif
94038    {
94039      yy_shift(yypParser,yyact,yygoto,&yygotominor);
94040    }
94041  }else{
94042    assert( yyact == YYNSTATE + YYNRULE + 1 );
94043    yy_accept(yypParser);
94044  }
94045}
94046
94047/*
94048** The following code executes when the parse fails
94049*/
94050#ifndef YYNOERRORRECOVERY
94051static void yy_parse_failed(
94052  yyParser *yypParser           /* The parser */
94053){
94054  sqlite3ParserARG_FETCH;
94055#ifndef NDEBUG
94056  if( yyTraceFILE ){
94057    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
94058  }
94059#endif
94060  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
94061  /* Here code is inserted which will be executed whenever the
94062  ** parser fails */
94063  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
94064}
94065#endif /* YYNOERRORRECOVERY */
94066
94067/*
94068** The following code executes when a syntax error first occurs.
94069*/
94070static void yy_syntax_error(
94071  yyParser *yypParser,           /* The parser */
94072  int yymajor,                   /* The major type of the error token */
94073  YYMINORTYPE yyminor            /* The minor type of the error token */
94074){
94075  sqlite3ParserARG_FETCH;
94076#define TOKEN (yyminor.yy0)
94077
94078  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
94079  assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
94080  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
94081  pParse->parseError = 1;
94082  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
94083}
94084
94085/*
94086** The following is executed when the parser accepts
94087*/
94088static void yy_accept(
94089  yyParser *yypParser           /* The parser */
94090){
94091  sqlite3ParserARG_FETCH;
94092#ifndef NDEBUG
94093  if( yyTraceFILE ){
94094    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
94095  }
94096#endif
94097  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
94098  /* Here code is inserted which will be executed whenever the
94099  ** parser accepts */
94100  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
94101}
94102
94103/* The main parser program.
94104** The first argument is a pointer to a structure obtained from
94105** "sqlite3ParserAlloc" which describes the current state of the parser.
94106** The second argument is the major token number.  The third is
94107** the minor token.  The fourth optional argument is whatever the
94108** user wants (and specified in the grammar) and is available for
94109** use by the action routines.
94110**
94111** Inputs:
94112** <ul>
94113** <li> A pointer to the parser (an opaque structure.)
94114** <li> The major token number.
94115** <li> The minor token number.
94116** <li> An option argument of a grammar-specified type.
94117** </ul>
94118**
94119** Outputs:
94120** None.
94121*/
94122SQLITE_PRIVATE void sqlite3Parser(
94123  void *yyp,                   /* The parser */
94124  int yymajor,                 /* The major token code number */
94125  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
94126  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
94127){
94128  YYMINORTYPE yyminorunion;
94129  int yyact;            /* The parser action. */
94130  int yyendofinput;     /* True if we are at the end of input */
94131#ifdef YYERRORSYMBOL
94132  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
94133#endif
94134  yyParser *yypParser;  /* The parser */
94135
94136  /* (re)initialize the parser, if necessary */
94137  yypParser = (yyParser*)yyp;
94138  if( yypParser->yyidx<0 ){
94139#if YYSTACKDEPTH<=0
94140    if( yypParser->yystksz <=0 ){
94141      /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
94142      yyminorunion = yyzerominor;
94143      yyStackOverflow(yypParser, &yyminorunion);
94144      return;
94145    }
94146#endif
94147    yypParser->yyidx = 0;
94148    yypParser->yyerrcnt = -1;
94149    yypParser->yystack[0].stateno = 0;
94150    yypParser->yystack[0].major = 0;
94151  }
94152  yyminorunion.yy0 = yyminor;
94153  yyendofinput = (yymajor==0);
94154  sqlite3ParserARG_STORE;
94155
94156#ifndef NDEBUG
94157  if( yyTraceFILE ){
94158    fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
94159  }
94160#endif
94161
94162  do{
94163    yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
94164    if( yyact<YYNSTATE ){
94165      assert( !yyendofinput );  /* Impossible to shift the $ token */
94166      yy_shift(yypParser,yyact,yymajor,&yyminorunion);
94167      yypParser->yyerrcnt--;
94168      yymajor = YYNOCODE;
94169    }else if( yyact < YYNSTATE + YYNRULE ){
94170      yy_reduce(yypParser,yyact-YYNSTATE);
94171    }else{
94172      assert( yyact == YY_ERROR_ACTION );
94173#ifdef YYERRORSYMBOL
94174      int yymx;
94175#endif
94176#ifndef NDEBUG
94177      if( yyTraceFILE ){
94178        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
94179      }
94180#endif
94181#ifdef YYERRORSYMBOL
94182      /* A syntax error has occurred.
94183      ** The response to an error depends upon whether or not the
94184      ** grammar defines an error token "ERROR".
94185      **
94186      ** This is what we do if the grammar does define ERROR:
94187      **
94188      **  * Call the %syntax_error function.
94189      **
94190      **  * Begin popping the stack until we enter a state where
94191      **    it is legal to shift the error symbol, then shift
94192      **    the error symbol.
94193      **
94194      **  * Set the error count to three.
94195      **
94196      **  * Begin accepting and shifting new tokens.  No new error
94197      **    processing will occur until three tokens have been
94198      **    shifted successfully.
94199      **
94200      */
94201      if( yypParser->yyerrcnt<0 ){
94202        yy_syntax_error(yypParser,yymajor,yyminorunion);
94203      }
94204      yymx = yypParser->yystack[yypParser->yyidx].major;
94205      if( yymx==YYERRORSYMBOL || yyerrorhit ){
94206#ifndef NDEBUG
94207        if( yyTraceFILE ){
94208          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
94209             yyTracePrompt,yyTokenName[yymajor]);
94210        }
94211#endif
94212        yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
94213        yymajor = YYNOCODE;
94214      }else{
94215         while(
94216          yypParser->yyidx >= 0 &&
94217          yymx != YYERRORSYMBOL &&
94218          (yyact = yy_find_reduce_action(
94219                        yypParser->yystack[yypParser->yyidx].stateno,
94220                        YYERRORSYMBOL)) >= YYNSTATE
94221        ){
94222          yy_pop_parser_stack(yypParser);
94223        }
94224        if( yypParser->yyidx < 0 || yymajor==0 ){
94225          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
94226          yy_parse_failed(yypParser);
94227          yymajor = YYNOCODE;
94228        }else if( yymx!=YYERRORSYMBOL ){
94229          YYMINORTYPE u2;
94230          u2.YYERRSYMDT = 0;
94231          yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
94232        }
94233      }
94234      yypParser->yyerrcnt = 3;
94235      yyerrorhit = 1;
94236#elif defined(YYNOERRORRECOVERY)
94237      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
94238      ** do any kind of error recovery.  Instead, simply invoke the syntax
94239      ** error routine and continue going as if nothing had happened.
94240      **
94241      ** Applications can set this macro (for example inside %include) if
94242      ** they intend to abandon the parse upon the first syntax error seen.
94243      */
94244      yy_syntax_error(yypParser,yymajor,yyminorunion);
94245      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
94246      yymajor = YYNOCODE;
94247
94248#else  /* YYERRORSYMBOL is not defined */
94249      /* This is what we do if the grammar does not define ERROR:
94250      **
94251      **  * Report an error message, and throw away the input token.
94252      **
94253      **  * If the input token is $, then fail the parse.
94254      **
94255      ** As before, subsequent error messages are suppressed until
94256      ** three input tokens have been successfully shifted.
94257      */
94258      if( yypParser->yyerrcnt<=0 ){
94259        yy_syntax_error(yypParser,yymajor,yyminorunion);
94260      }
94261      yypParser->yyerrcnt = 3;
94262      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
94263      if( yyendofinput ){
94264        yy_parse_failed(yypParser);
94265      }
94266      yymajor = YYNOCODE;
94267#endif
94268    }
94269  }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
94270  return;
94271}
94272
94273/************** End of parse.c ***********************************************/
94274/************** Begin file tokenize.c ****************************************/
94275/*
94276** 2001 September 15
94277**
94278** The author disclaims copyright to this source code.  In place of
94279** a legal notice, here is a blessing:
94280**
94281**    May you do good and not evil.
94282**    May you find forgiveness for yourself and forgive others.
94283**    May you share freely, never taking more than you give.
94284**
94285*************************************************************************
94286** An tokenizer for SQL
94287**
94288** This file contains C code that splits an SQL input string up into
94289** individual tokens and sends those tokens one-by-one over to the
94290** parser for analysis.
94291*/
94292
94293/*
94294** The charMap() macro maps alphabetic characters into their
94295** lower-case ASCII equivalent.  On ASCII machines, this is just
94296** an upper-to-lower case map.  On EBCDIC machines we also need
94297** to adjust the encoding.  Only alphabetic characters and underscores
94298** need to be translated.
94299*/
94300#ifdef SQLITE_ASCII
94301# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
94302#endif
94303#ifdef SQLITE_EBCDIC
94304# define charMap(X) ebcdicToAscii[(unsigned char)X]
94305const unsigned char ebcdicToAscii[] = {
94306/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
94307   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
94308   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
94309   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
94310   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
94311   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
94312   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
94313   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
94314   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
94315   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
94316   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
94317   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
94318   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
94319   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
94320   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
94321   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
94322   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
94323};
94324#endif
94325
94326/*
94327** The sqlite3KeywordCode function looks up an identifier to determine if
94328** it is a keyword.  If it is a keyword, the token code of that keyword is
94329** returned.  If the input is not a keyword, TK_ID is returned.
94330**
94331** The implementation of this routine was generated by a program,
94332** mkkeywordhash.h, located in the tool subdirectory of the distribution.
94333** The output of the mkkeywordhash.c program is written into a file
94334** named keywordhash.h and then included into this source file by
94335** the #include below.
94336*/
94337/************** Include keywordhash.h in the middle of tokenize.c ************/
94338/************** Begin file keywordhash.h *************************************/
94339/***** This file contains automatically generated code ******
94340**
94341** The code in this file has been automatically generated by
94342**
94343**   sqlite/tool/mkkeywordhash.c
94344**
94345** The code in this file implements a function that determines whether
94346** or not a given identifier is really an SQL keyword.  The same thing
94347** might be implemented more directly using a hand-written hash table.
94348** But by using this automatically generated code, the size of the code
94349** is substantially reduced.  This is important for embedded applications
94350** on platforms with limited memory.
94351*/
94352/* Hash score: 175 */
94353static int keywordCode(const char *z, int n){
94354  /* zText[] encodes 811 bytes of keywords in 541 bytes */
94355  /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
94356  /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
94357  /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
94358  /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
94359  /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
94360  /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
94361  /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
94362  /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
94363  /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
94364  /*   INITIALLY                                                          */
94365  static const char zText[540] = {
94366    'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
94367    'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
94368    'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
94369    'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
94370    'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
94371    'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
94372    'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
94373    'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
94374    'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
94375    'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
94376    'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
94377    'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
94378    'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
94379    'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
94380    'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
94381    'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
94382    'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
94383    'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
94384    'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
94385    'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
94386    'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
94387    'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
94388    'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
94389    'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
94390    'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
94391    'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
94392    'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
94393    'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
94394    'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
94395    'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
94396  };
94397  static const unsigned char aHash[127] = {
94398      72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
94399      42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
94400     118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
94401       0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
94402       0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
94403      92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
94404      96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
94405      39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
94406      58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
94407      29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
94408  };
94409  static const unsigned char aNext[121] = {
94410       0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
94411       0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
94412       0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
94413       0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
94414       0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
94415      62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
94416      61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
94417       0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
94418     103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
94419      35,  64,   0,   0,
94420  };
94421  static const unsigned char aLen[121] = {
94422       7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
94423       7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
94424      11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
94425       4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
94426       5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
94427       7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
94428       7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
94429       6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
94430       4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
94431       6,   4,   9,   3,
94432  };
94433  static const unsigned short int aOffset[121] = {
94434       0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
94435      36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
94436      86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
94437     159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
94438     203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
94439     248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
94440     326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
94441     387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
94442     462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
94443     521, 527, 531, 536,
94444  };
94445  static const unsigned char aCode[121] = {
94446    TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
94447    TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
94448    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
94449    TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
94450    TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
94451    TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
94452    TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
94453    TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
94454    TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
94455    TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,
94456    TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,
94457    TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,
94458    TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,
94459    TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,
94460    TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,
94461    TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,
94462    TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,
94463    TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,
94464    TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,
94465    TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,
94466    TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,
94467    TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,
94468    TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,
94469    TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,
94470    TK_ALL,
94471  };
94472  int h, i;
94473  if( n<2 ) return TK_ID;
94474  h = ((charMap(z[0])*4) ^
94475      (charMap(z[n-1])*3) ^
94476      n) % 127;
94477  for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
94478    if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
94479      testcase( i==0 ); /* REINDEX */
94480      testcase( i==1 ); /* INDEXED */
94481      testcase( i==2 ); /* INDEX */
94482      testcase( i==3 ); /* DESC */
94483      testcase( i==4 ); /* ESCAPE */
94484      testcase( i==5 ); /* EACH */
94485      testcase( i==6 ); /* CHECK */
94486      testcase( i==7 ); /* KEY */
94487      testcase( i==8 ); /* BEFORE */
94488      testcase( i==9 ); /* FOREIGN */
94489      testcase( i==10 ); /* FOR */
94490      testcase( i==11 ); /* IGNORE */
94491      testcase( i==12 ); /* REGEXP */
94492      testcase( i==13 ); /* EXPLAIN */
94493      testcase( i==14 ); /* INSTEAD */
94494      testcase( i==15 ); /* ADD */
94495      testcase( i==16 ); /* DATABASE */
94496      testcase( i==17 ); /* AS */
94497      testcase( i==18 ); /* SELECT */
94498      testcase( i==19 ); /* TABLE */
94499      testcase( i==20 ); /* LEFT */
94500      testcase( i==21 ); /* THEN */
94501      testcase( i==22 ); /* END */
94502      testcase( i==23 ); /* DEFERRABLE */
94503      testcase( i==24 ); /* ELSE */
94504      testcase( i==25 ); /* EXCEPT */
94505      testcase( i==26 ); /* TRANSACTION */
94506      testcase( i==27 ); /* ACTION */
94507      testcase( i==28 ); /* ON */
94508      testcase( i==29 ); /* NATURAL */
94509      testcase( i==30 ); /* ALTER */
94510      testcase( i==31 ); /* RAISE */
94511      testcase( i==32 ); /* EXCLUSIVE */
94512      testcase( i==33 ); /* EXISTS */
94513      testcase( i==34 ); /* SAVEPOINT */
94514      testcase( i==35 ); /* INTERSECT */
94515      testcase( i==36 ); /* TRIGGER */
94516      testcase( i==37 ); /* REFERENCES */
94517      testcase( i==38 ); /* CONSTRAINT */
94518      testcase( i==39 ); /* INTO */
94519      testcase( i==40 ); /* OFFSET */
94520      testcase( i==41 ); /* OF */
94521      testcase( i==42 ); /* SET */
94522      testcase( i==43 ); /* TEMPORARY */
94523      testcase( i==44 ); /* TEMP */
94524      testcase( i==45 ); /* OR */
94525      testcase( i==46 ); /* UNIQUE */
94526      testcase( i==47 ); /* QUERY */
94527      testcase( i==48 ); /* ATTACH */
94528      testcase( i==49 ); /* HAVING */
94529      testcase( i==50 ); /* GROUP */
94530      testcase( i==51 ); /* UPDATE */
94531      testcase( i==52 ); /* BEGIN */
94532      testcase( i==53 ); /* INNER */
94533      testcase( i==54 ); /* RELEASE */
94534      testcase( i==55 ); /* BETWEEN */
94535      testcase( i==56 ); /* NOTNULL */
94536      testcase( i==57 ); /* NOT */
94537      testcase( i==58 ); /* NO */
94538      testcase( i==59 ); /* NULL */
94539      testcase( i==60 ); /* LIKE */
94540      testcase( i==61 ); /* CASCADE */
94541      testcase( i==62 ); /* ASC */
94542      testcase( i==63 ); /* DELETE */
94543      testcase( i==64 ); /* CASE */
94544      testcase( i==65 ); /* COLLATE */
94545      testcase( i==66 ); /* CREATE */
94546      testcase( i==67 ); /* CURRENT_DATE */
94547      testcase( i==68 ); /* DETACH */
94548      testcase( i==69 ); /* IMMEDIATE */
94549      testcase( i==70 ); /* JOIN */
94550      testcase( i==71 ); /* INSERT */
94551      testcase( i==72 ); /* MATCH */
94552      testcase( i==73 ); /* PLAN */
94553      testcase( i==74 ); /* ANALYZE */
94554      testcase( i==75 ); /* PRAGMA */
94555      testcase( i==76 ); /* ABORT */
94556      testcase( i==77 ); /* VALUES */
94557      testcase( i==78 ); /* VIRTUAL */
94558      testcase( i==79 ); /* LIMIT */
94559      testcase( i==80 ); /* WHEN */
94560      testcase( i==81 ); /* WHERE */
94561      testcase( i==82 ); /* RENAME */
94562      testcase( i==83 ); /* AFTER */
94563      testcase( i==84 ); /* REPLACE */
94564      testcase( i==85 ); /* AND */
94565      testcase( i==86 ); /* DEFAULT */
94566      testcase( i==87 ); /* AUTOINCREMENT */
94567      testcase( i==88 ); /* TO */
94568      testcase( i==89 ); /* IN */
94569      testcase( i==90 ); /* CAST */
94570      testcase( i==91 ); /* COLUMN */
94571      testcase( i==92 ); /* COMMIT */
94572      testcase( i==93 ); /* CONFLICT */
94573      testcase( i==94 ); /* CROSS */
94574      testcase( i==95 ); /* CURRENT_TIMESTAMP */
94575      testcase( i==96 ); /* CURRENT_TIME */
94576      testcase( i==97 ); /* PRIMARY */
94577      testcase( i==98 ); /* DEFERRED */
94578      testcase( i==99 ); /* DISTINCT */
94579      testcase( i==100 ); /* IS */
94580      testcase( i==101 ); /* DROP */
94581      testcase( i==102 ); /* FAIL */
94582      testcase( i==103 ); /* FROM */
94583      testcase( i==104 ); /* FULL */
94584      testcase( i==105 ); /* GLOB */
94585      testcase( i==106 ); /* BY */
94586      testcase( i==107 ); /* IF */
94587      testcase( i==108 ); /* ISNULL */
94588      testcase( i==109 ); /* ORDER */
94589      testcase( i==110 ); /* RESTRICT */
94590      testcase( i==111 ); /* OUTER */
94591      testcase( i==112 ); /* RIGHT */
94592      testcase( i==113 ); /* ROLLBACK */
94593      testcase( i==114 ); /* ROW */
94594      testcase( i==115 ); /* UNION */
94595      testcase( i==116 ); /* USING */
94596      testcase( i==117 ); /* VACUUM */
94597      testcase( i==118 ); /* VIEW */
94598      testcase( i==119 ); /* INITIALLY */
94599      testcase( i==120 ); /* ALL */
94600      return aCode[i];
94601    }
94602  }
94603  return TK_ID;
94604}
94605SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
94606  return keywordCode((char*)z, n);
94607}
94608#define SQLITE_N_KEYWORD 121
94609
94610/************** End of keywordhash.h *****************************************/
94611/************** Continuing where we left off in tokenize.c *******************/
94612
94613
94614/*
94615** If X is a character that can be used in an identifier then
94616** IdChar(X) will be true.  Otherwise it is false.
94617**
94618** For ASCII, any character with the high-order bit set is
94619** allowed in an identifier.  For 7-bit characters,
94620** sqlite3IsIdChar[X] must be 1.
94621**
94622** For EBCDIC, the rules are more complex but have the same
94623** end result.
94624**
94625** Ticket #1066.  the SQL standard does not allow '$' in the
94626** middle of identfiers.  But many SQL implementations do.
94627** SQLite will allow '$' in identifiers for compatibility.
94628** But the feature is undocumented.
94629*/
94630#ifdef SQLITE_ASCII
94631#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
94632#endif
94633#ifdef SQLITE_EBCDIC
94634SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
94635/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
94636    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
94637    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
94638    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
94639    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
94640    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
94641    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
94642    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
94643    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
94644    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
94645    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
94646    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
94647    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
94648};
94649#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
94650#endif
94651
94652
94653/*
94654** Return the length of the token that begins at z[0].
94655** Store the token type in *tokenType before returning.
94656*/
94657SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
94658  int i, c;
94659  switch( *z ){
94660    case ' ': case '\t': case '\n': case '\f': case '\r': {
94661      testcase( z[0]==' ' );
94662      testcase( z[0]=='\t' );
94663      testcase( z[0]=='\n' );
94664      testcase( z[0]=='\f' );
94665      testcase( z[0]=='\r' );
94666      for(i=1; sqlite3Isspace(z[i]); i++){}
94667      *tokenType = TK_SPACE;
94668      return i;
94669    }
94670    case '-': {
94671      if( z[1]=='-' ){
94672        /* IMP: R-15891-05542 -- syntax diagram for comments */
94673        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
94674        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
94675        return i;
94676      }
94677      *tokenType = TK_MINUS;
94678      return 1;
94679    }
94680    case '(': {
94681      *tokenType = TK_LP;
94682      return 1;
94683    }
94684    case ')': {
94685      *tokenType = TK_RP;
94686      return 1;
94687    }
94688    case ';': {
94689      *tokenType = TK_SEMI;
94690      return 1;
94691    }
94692    case '+': {
94693      *tokenType = TK_PLUS;
94694      return 1;
94695    }
94696    case '*': {
94697      *tokenType = TK_STAR;
94698      return 1;
94699    }
94700    case '/': {
94701      if( z[1]!='*' || z[2]==0 ){
94702        *tokenType = TK_SLASH;
94703        return 1;
94704      }
94705      /* IMP: R-15891-05542 -- syntax diagram for comments */
94706      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
94707      if( c ) i++;
94708      *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
94709      return i;
94710    }
94711    case '%': {
94712      *tokenType = TK_REM;
94713      return 1;
94714    }
94715    case '=': {
94716      *tokenType = TK_EQ;
94717      return 1 + (z[1]=='=');
94718    }
94719    case '<': {
94720      if( (c=z[1])=='=' ){
94721        *tokenType = TK_LE;
94722        return 2;
94723      }else if( c=='>' ){
94724        *tokenType = TK_NE;
94725        return 2;
94726      }else if( c=='<' ){
94727        *tokenType = TK_LSHIFT;
94728        return 2;
94729      }else{
94730        *tokenType = TK_LT;
94731        return 1;
94732      }
94733    }
94734    case '>': {
94735      if( (c=z[1])=='=' ){
94736        *tokenType = TK_GE;
94737        return 2;
94738      }else if( c=='>' ){
94739        *tokenType = TK_RSHIFT;
94740        return 2;
94741      }else{
94742        *tokenType = TK_GT;
94743        return 1;
94744      }
94745    }
94746    case '!': {
94747      if( z[1]!='=' ){
94748        *tokenType = TK_ILLEGAL;
94749        return 2;
94750      }else{
94751        *tokenType = TK_NE;
94752        return 2;
94753      }
94754    }
94755    case '|': {
94756      if( z[1]!='|' ){
94757        *tokenType = TK_BITOR;
94758        return 1;
94759      }else{
94760        *tokenType = TK_CONCAT;
94761        return 2;
94762      }
94763    }
94764    case ',': {
94765      *tokenType = TK_COMMA;
94766      return 1;
94767    }
94768    case '&': {
94769      *tokenType = TK_BITAND;
94770      return 1;
94771    }
94772    case '~': {
94773      *tokenType = TK_BITNOT;
94774      return 1;
94775    }
94776    case '`':
94777    case '\'':
94778    case '"': {
94779      int delim = z[0];
94780      testcase( delim=='`' );
94781      testcase( delim=='\'' );
94782      testcase( delim=='"' );
94783      for(i=1; (c=z[i])!=0; i++){
94784        if( c==delim ){
94785          if( z[i+1]==delim ){
94786            i++;
94787          }else{
94788            break;
94789          }
94790        }
94791      }
94792      if( c=='\'' ){
94793        *tokenType = TK_STRING;
94794        return i+1;
94795      }else if( c!=0 ){
94796        *tokenType = TK_ID;
94797        return i+1;
94798      }else{
94799        *tokenType = TK_ILLEGAL;
94800        return i;
94801      }
94802    }
94803    case '.': {
94804#ifndef SQLITE_OMIT_FLOATING_POINT
94805      if( !sqlite3Isdigit(z[1]) )
94806#endif
94807      {
94808        *tokenType = TK_DOT;
94809        return 1;
94810      }
94811      /* If the next character is a digit, this is a floating point
94812      ** number that begins with ".".  Fall thru into the next case */
94813    }
94814    case '0': case '1': case '2': case '3': case '4':
94815    case '5': case '6': case '7': case '8': case '9': {
94816      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
94817      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
94818      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
94819      testcase( z[0]=='9' );
94820      *tokenType = TK_INTEGER;
94821      for(i=0; sqlite3Isdigit(z[i]); i++){}
94822#ifndef SQLITE_OMIT_FLOATING_POINT
94823      if( z[i]=='.' ){
94824        i++;
94825        while( sqlite3Isdigit(z[i]) ){ i++; }
94826        *tokenType = TK_FLOAT;
94827      }
94828      if( (z[i]=='e' || z[i]=='E') &&
94829           ( sqlite3Isdigit(z[i+1])
94830            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
94831           )
94832      ){
94833        i += 2;
94834        while( sqlite3Isdigit(z[i]) ){ i++; }
94835        *tokenType = TK_FLOAT;
94836      }
94837#endif
94838      while( IdChar(z[i]) ){
94839        *tokenType = TK_ILLEGAL;
94840        i++;
94841      }
94842      return i;
94843    }
94844    case '[': {
94845      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
94846      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
94847      return i;
94848    }
94849    case '?': {
94850      *tokenType = TK_VARIABLE;
94851      for(i=1; sqlite3Isdigit(z[i]); i++){}
94852      return i;
94853    }
94854    case '#': {
94855      for(i=1; sqlite3Isdigit(z[i]); i++){}
94856      if( i>1 ){
94857        /* Parameters of the form #NNN (where NNN is a number) are used
94858        ** internally by sqlite3NestedParse.  */
94859        *tokenType = TK_REGISTER;
94860        return i;
94861      }
94862      /* Fall through into the next case if the '#' is not followed by
94863      ** a digit. Try to match #AAAA where AAAA is a parameter name. */
94864    }
94865#ifndef SQLITE_OMIT_TCL_VARIABLE
94866    case '$':
94867#endif
94868    case '@':  /* For compatibility with MS SQL Server */
94869    case ':': {
94870      int n = 0;
94871      testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
94872      *tokenType = TK_VARIABLE;
94873      for(i=1; (c=z[i])!=0; i++){
94874        if( IdChar(c) ){
94875          n++;
94876#ifndef SQLITE_OMIT_TCL_VARIABLE
94877        }else if( c=='(' && n>0 ){
94878          do{
94879            i++;
94880          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
94881          if( c==')' ){
94882            i++;
94883          }else{
94884            *tokenType = TK_ILLEGAL;
94885          }
94886          break;
94887        }else if( c==':' && z[i+1]==':' ){
94888          i++;
94889#endif
94890        }else{
94891          break;
94892        }
94893      }
94894      if( n==0 ) *tokenType = TK_ILLEGAL;
94895      return i;
94896    }
94897#ifndef SQLITE_OMIT_BLOB_LITERAL
94898    case 'x': case 'X': {
94899      testcase( z[0]=='x' ); testcase( z[0]=='X' );
94900      if( z[1]=='\'' ){
94901        *tokenType = TK_BLOB;
94902        for(i=2; (c=z[i])!=0 && c!='\''; i++){
94903          if( !sqlite3Isxdigit(c) ){
94904            *tokenType = TK_ILLEGAL;
94905          }
94906        }
94907        if( i%2 || !c ) *tokenType = TK_ILLEGAL;
94908        if( c ) i++;
94909        return i;
94910      }
94911      /* Otherwise fall through to the next case */
94912    }
94913#endif
94914    default: {
94915      if( !IdChar(*z) ){
94916        break;
94917      }
94918      for(i=1; IdChar(z[i]); i++){}
94919      *tokenType = keywordCode((char*)z, i);
94920      return i;
94921    }
94922  }
94923  *tokenType = TK_ILLEGAL;
94924  return 1;
94925}
94926
94927/*
94928** Run the parser on the given SQL string.  The parser structure is
94929** passed in.  An SQLITE_ status code is returned.  If an error occurs
94930** then an and attempt is made to write an error message into
94931** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
94932** error message.
94933*/
94934SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
94935  int nErr = 0;                   /* Number of errors encountered */
94936  int i;                          /* Loop counter */
94937  void *pEngine;                  /* The LEMON-generated LALR(1) parser */
94938  int tokenType;                  /* type of the next token */
94939  int lastTokenParsed = -1;       /* type of the previous token */
94940  u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
94941  sqlite3 *db = pParse->db;       /* The database connection */
94942  int mxSqlLen;                   /* Max length of an SQL string */
94943
94944
94945  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
94946  if( db->activeVdbeCnt==0 ){
94947    db->u1.isInterrupted = 0;
94948  }
94949  pParse->rc = SQLITE_OK;
94950  pParse->zTail = zSql;
94951  i = 0;
94952  assert( pzErrMsg!=0 );
94953  pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
94954  if( pEngine==0 ){
94955    db->mallocFailed = 1;
94956    return SQLITE_NOMEM;
94957  }
94958  assert( pParse->pNewTable==0 );
94959  assert( pParse->pNewTrigger==0 );
94960  assert( pParse->nVar==0 );
94961  assert( pParse->nVarExpr==0 );
94962  assert( pParse->nVarExprAlloc==0 );
94963  assert( pParse->apVarExpr==0 );
94964  enableLookaside = db->lookaside.bEnabled;
94965  if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
94966  while( !db->mallocFailed && zSql[i]!=0 ){
94967    assert( i>=0 );
94968    pParse->sLastToken.z = &zSql[i];
94969    pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
94970    i += pParse->sLastToken.n;
94971    if( i>mxSqlLen ){
94972      pParse->rc = SQLITE_TOOBIG;
94973      break;
94974    }
94975    switch( tokenType ){
94976      case TK_SPACE: {
94977        if( db->u1.isInterrupted ){
94978          sqlite3ErrorMsg(pParse, "interrupt");
94979          pParse->rc = SQLITE_INTERRUPT;
94980          goto abort_parse;
94981        }
94982        break;
94983      }
94984      case TK_ILLEGAL: {
94985        sqlite3DbFree(db, *pzErrMsg);
94986        *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
94987                        &pParse->sLastToken);
94988        nErr++;
94989        goto abort_parse;
94990      }
94991      case TK_SEMI: {
94992        pParse->zTail = &zSql[i];
94993        /* Fall thru into the default case */
94994      }
94995      default: {
94996        sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
94997        lastTokenParsed = tokenType;
94998        if( pParse->rc!=SQLITE_OK ){
94999          goto abort_parse;
95000        }
95001        break;
95002      }
95003    }
95004  }
95005abort_parse:
95006  if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
95007    if( lastTokenParsed!=TK_SEMI ){
95008      sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
95009      pParse->zTail = &zSql[i];
95010    }
95011    sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
95012  }
95013#ifdef YYTRACKMAXSTACKDEPTH
95014  sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
95015      sqlite3ParserStackPeak(pEngine)
95016  );
95017#endif /* YYDEBUG */
95018  sqlite3ParserFree(pEngine, sqlite3_free);
95019  db->lookaside.bEnabled = enableLookaside;
95020  if( db->mallocFailed ){
95021    pParse->rc = SQLITE_NOMEM;
95022  }
95023  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
95024    sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
95025  }
95026  assert( pzErrMsg!=0 );
95027  if( pParse->zErrMsg ){
95028    *pzErrMsg = pParse->zErrMsg;
95029    sqlite3_log(pParse->rc, "%s", *pzErrMsg);
95030    pParse->zErrMsg = 0;
95031    nErr++;
95032  }
95033  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
95034    sqlite3VdbeDelete(pParse->pVdbe);
95035    pParse->pVdbe = 0;
95036  }
95037#ifndef SQLITE_OMIT_SHARED_CACHE
95038  if( pParse->nested==0 ){
95039    sqlite3DbFree(db, pParse->aTableLock);
95040    pParse->aTableLock = 0;
95041    pParse->nTableLock = 0;
95042  }
95043#endif
95044#ifndef SQLITE_OMIT_VIRTUALTABLE
95045  sqlite3DbFree(db, pParse->apVtabLock);
95046#endif
95047
95048  if( !IN_DECLARE_VTAB ){
95049    /* If the pParse->declareVtab flag is set, do not delete any table
95050    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
95051    ** will take responsibility for freeing the Table structure.
95052    */
95053    sqlite3DeleteTable(pParse->pNewTable);
95054  }
95055
95056  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
95057  sqlite3DbFree(db, pParse->apVarExpr);
95058  sqlite3DbFree(db, pParse->aAlias);
95059  while( pParse->pAinc ){
95060    AutoincInfo *p = pParse->pAinc;
95061    pParse->pAinc = p->pNext;
95062    sqlite3DbFree(db, p);
95063  }
95064  while( pParse->pZombieTab ){
95065    Table *p = pParse->pZombieTab;
95066    pParse->pZombieTab = p->pNextZombie;
95067    sqlite3DeleteTable(p);
95068  }
95069  if( nErr>0 && pParse->rc==SQLITE_OK ){
95070    pParse->rc = SQLITE_ERROR;
95071  }
95072  return nErr;
95073}
95074
95075/************** End of tokenize.c ********************************************/
95076/************** Begin file complete.c ****************************************/
95077/*
95078** 2001 September 15
95079**
95080** The author disclaims copyright to this source code.  In place of
95081** a legal notice, here is a blessing:
95082**
95083**    May you do good and not evil.
95084**    May you find forgiveness for yourself and forgive others.
95085**    May you share freely, never taking more than you give.
95086**
95087*************************************************************************
95088** An tokenizer for SQL
95089**
95090** This file contains C code that implements the sqlite3_complete() API.
95091** This code used to be part of the tokenizer.c source file.  But by
95092** separating it out, the code will be automatically omitted from
95093** static links that do not use it.
95094*/
95095#ifndef SQLITE_OMIT_COMPLETE
95096
95097/*
95098** This is defined in tokenize.c.  We just have to import the definition.
95099*/
95100#ifndef SQLITE_AMALGAMATION
95101#ifdef SQLITE_ASCII
95102#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
95103#endif
95104#ifdef SQLITE_EBCDIC
95105SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
95106#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
95107#endif
95108#endif /* SQLITE_AMALGAMATION */
95109
95110
95111/*
95112** Token types used by the sqlite3_complete() routine.  See the header
95113** comments on that procedure for additional information.
95114*/
95115#define tkSEMI    0
95116#define tkWS      1
95117#define tkOTHER   2
95118#ifndef SQLITE_OMIT_TRIGGER
95119#define tkEXPLAIN 3
95120#define tkCREATE  4
95121#define tkTEMP    5
95122#define tkTRIGGER 6
95123#define tkEND     7
95124#endif
95125
95126/*
95127** Return TRUE if the given SQL string ends in a semicolon.
95128**
95129** Special handling is require for CREATE TRIGGER statements.
95130** Whenever the CREATE TRIGGER keywords are seen, the statement
95131** must end with ";END;".
95132**
95133** This implementation uses a state machine with 8 states:
95134**
95135**   (0) INVALID   We have not yet seen a non-whitespace character.
95136**
95137**   (1) START     At the beginning or end of an SQL statement.  This routine
95138**                 returns 1 if it ends in the START state and 0 if it ends
95139**                 in any other state.
95140**
95141**   (2) NORMAL    We are in the middle of statement which ends with a single
95142**                 semicolon.
95143**
95144**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
95145**                 a statement.
95146**
95147**   (4) CREATE    The keyword CREATE has been seen at the beginning of a
95148**                 statement, possibly preceeded by EXPLAIN and/or followed by
95149**                 TEMP or TEMPORARY
95150**
95151**   (5) TRIGGER   We are in the middle of a trigger definition that must be
95152**                 ended by a semicolon, the keyword END, and another semicolon.
95153**
95154**   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
95155**                 the end of a trigger definition.
95156**
95157**   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
95158**                 of a trigger difinition.
95159**
95160** Transitions between states above are determined by tokens extracted
95161** from the input.  The following tokens are significant:
95162**
95163**   (0) tkSEMI      A semicolon.
95164**   (1) tkWS        Whitespace.
95165**   (2) tkOTHER     Any other SQL token.
95166**   (3) tkEXPLAIN   The "explain" keyword.
95167**   (4) tkCREATE    The "create" keyword.
95168**   (5) tkTEMP      The "temp" or "temporary" keyword.
95169**   (6) tkTRIGGER   The "trigger" keyword.
95170**   (7) tkEND       The "end" keyword.
95171**
95172** Whitespace never causes a state transition and is always ignored.
95173** This means that a SQL string of all whitespace is invalid.
95174**
95175** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
95176** to recognize the end of a trigger can be omitted.  All we have to do
95177** is look for a semicolon that is not part of an string or comment.
95178*/
95179SQLITE_API int sqlite3_complete(const char *zSql){
95180  u8 state = 0;   /* Current state, using numbers defined in header comment */
95181  u8 token;       /* Value of the next token */
95182
95183#ifndef SQLITE_OMIT_TRIGGER
95184  /* A complex statement machine used to detect the end of a CREATE TRIGGER
95185  ** statement.  This is the normal case.
95186  */
95187  static const u8 trans[8][8] = {
95188                     /* Token:                                                */
95189     /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
95190     /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
95191     /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
95192     /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
95193     /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
95194     /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
95195     /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
95196     /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
95197     /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
95198  };
95199#else
95200  /* If triggers are not supported by this compile then the statement machine
95201  ** used to detect the end of a statement is much simplier
95202  */
95203  static const u8 trans[3][3] = {
95204                     /* Token:           */
95205     /* State:       **  SEMI  WS  OTHER */
95206     /* 0 INVALID: */ {    1,  0,     2, },
95207     /* 1   START: */ {    1,  1,     2, },
95208     /* 2  NORMAL: */ {    1,  2,     2, },
95209  };
95210#endif /* SQLITE_OMIT_TRIGGER */
95211
95212  while( *zSql ){
95213    switch( *zSql ){
95214      case ';': {  /* A semicolon */
95215        token = tkSEMI;
95216        break;
95217      }
95218      case ' ':
95219      case '\r':
95220      case '\t':
95221      case '\n':
95222      case '\f': {  /* White space is ignored */
95223        token = tkWS;
95224        break;
95225      }
95226      case '/': {   /* C-style comments */
95227        if( zSql[1]!='*' ){
95228          token = tkOTHER;
95229          break;
95230        }
95231        zSql += 2;
95232        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
95233        if( zSql[0]==0 ) return 0;
95234        zSql++;
95235        token = tkWS;
95236        break;
95237      }
95238      case '-': {   /* SQL-style comments from "--" to end of line */
95239        if( zSql[1]!='-' ){
95240          token = tkOTHER;
95241          break;
95242        }
95243        while( *zSql && *zSql!='\n' ){ zSql++; }
95244        if( *zSql==0 ) return state==1;
95245        token = tkWS;
95246        break;
95247      }
95248      case '[': {   /* Microsoft-style identifiers in [...] */
95249        zSql++;
95250        while( *zSql && *zSql!=']' ){ zSql++; }
95251        if( *zSql==0 ) return 0;
95252        token = tkOTHER;
95253        break;
95254      }
95255      case '`':     /* Grave-accent quoted symbols used by MySQL */
95256      case '"':     /* single- and double-quoted strings */
95257      case '\'': {
95258        int c = *zSql;
95259        zSql++;
95260        while( *zSql && *zSql!=c ){ zSql++; }
95261        if( *zSql==0 ) return 0;
95262        token = tkOTHER;
95263        break;
95264      }
95265      default: {
95266#ifdef SQLITE_EBCDIC
95267        unsigned char c;
95268#endif
95269        if( IdChar((u8)*zSql) ){
95270          /* Keywords and unquoted identifiers */
95271          int nId;
95272          for(nId=1; IdChar(zSql[nId]); nId++){}
95273#ifdef SQLITE_OMIT_TRIGGER
95274          token = tkOTHER;
95275#else
95276          switch( *zSql ){
95277            case 'c': case 'C': {
95278              if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
95279                token = tkCREATE;
95280              }else{
95281                token = tkOTHER;
95282              }
95283              break;
95284            }
95285            case 't': case 'T': {
95286              if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
95287                token = tkTRIGGER;
95288              }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
95289                token = tkTEMP;
95290              }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
95291                token = tkTEMP;
95292              }else{
95293                token = tkOTHER;
95294              }
95295              break;
95296            }
95297            case 'e':  case 'E': {
95298              if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
95299                token = tkEND;
95300              }else
95301#ifndef SQLITE_OMIT_EXPLAIN
95302              if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
95303                token = tkEXPLAIN;
95304              }else
95305#endif
95306              {
95307                token = tkOTHER;
95308              }
95309              break;
95310            }
95311            default: {
95312              token = tkOTHER;
95313              break;
95314            }
95315          }
95316#endif /* SQLITE_OMIT_TRIGGER */
95317          zSql += nId-1;
95318        }else{
95319          /* Operators and special symbols */
95320          token = tkOTHER;
95321        }
95322        break;
95323      }
95324    }
95325    state = trans[state][token];
95326    zSql++;
95327  }
95328  return state==1;
95329}
95330
95331#ifndef SQLITE_OMIT_UTF16
95332/*
95333** This routine is the same as the sqlite3_complete() routine described
95334** above, except that the parameter is required to be UTF-16 encoded, not
95335** UTF-8.
95336*/
95337SQLITE_API int sqlite3_complete16(const void *zSql){
95338  sqlite3_value *pVal;
95339  char const *zSql8;
95340  int rc = SQLITE_NOMEM;
95341
95342#ifndef SQLITE_OMIT_AUTOINIT
95343  rc = sqlite3_initialize();
95344  if( rc ) return rc;
95345#endif
95346  pVal = sqlite3ValueNew(0);
95347  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
95348  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
95349  if( zSql8 ){
95350    rc = sqlite3_complete(zSql8);
95351  }else{
95352    rc = SQLITE_NOMEM;
95353  }
95354  sqlite3ValueFree(pVal);
95355  return sqlite3ApiExit(0, rc);
95356}
95357#endif /* SQLITE_OMIT_UTF16 */
95358#endif /* SQLITE_OMIT_COMPLETE */
95359
95360/************** End of complete.c ********************************************/
95361/************** Begin file main.c ********************************************/
95362/*
95363** 2001 September 15
95364**
95365** The author disclaims copyright to this source code.  In place of
95366** a legal notice, here is a blessing:
95367**
95368**    May you do good and not evil.
95369**    May you find forgiveness for yourself and forgive others.
95370**    May you share freely, never taking more than you give.
95371**
95372*************************************************************************
95373** Main file for the SQLite library.  The routines in this file
95374** implement the programmer interface to the library.  Routines in
95375** other files are for internal use by SQLite and should not be
95376** accessed by users of the library.
95377*/
95378
95379#ifdef SQLITE_ENABLE_FTS3
95380/************** Include fts3.h in the middle of main.c ***********************/
95381/************** Begin file fts3.h ********************************************/
95382/*
95383** 2006 Oct 10
95384**
95385** The author disclaims copyright to this source code.  In place of
95386** a legal notice, here is a blessing:
95387**
95388**    May you do good and not evil.
95389**    May you find forgiveness for yourself and forgive others.
95390**    May you share freely, never taking more than you give.
95391**
95392******************************************************************************
95393**
95394** This header file is used by programs that want to link against the
95395** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
95396*/
95397
95398#if 0
95399extern "C" {
95400#endif  /* __cplusplus */
95401
95402// Begin Android Change
95403SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db, const char* registerAs);
95404// End Android Change
95405
95406#if 0
95407}  /* extern "C" */
95408#endif  /* __cplusplus */
95409
95410/************** End of fts3.h ************************************************/
95411/************** Continuing where we left off in main.c ***********************/
95412#endif
95413#ifdef SQLITE_ENABLE_RTREE
95414/************** Include rtree.h in the middle of main.c **********************/
95415/************** Begin file rtree.h *******************************************/
95416/*
95417** 2008 May 26
95418**
95419** The author disclaims copyright to this source code.  In place of
95420** a legal notice, here is a blessing:
95421**
95422**    May you do good and not evil.
95423**    May you find forgiveness for yourself and forgive others.
95424**    May you share freely, never taking more than you give.
95425**
95426******************************************************************************
95427**
95428** This header file is used by programs that want to link against the
95429** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
95430*/
95431
95432#if 0
95433extern "C" {
95434#endif  /* __cplusplus */
95435
95436SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
95437
95438#if 0
95439}  /* extern "C" */
95440#endif  /* __cplusplus */
95441
95442/************** End of rtree.h ***********************************************/
95443/************** Continuing where we left off in main.c ***********************/
95444#endif
95445#ifdef SQLITE_ENABLE_ICU
95446/************** Include sqliteicu.h in the middle of main.c ******************/
95447/************** Begin file sqliteicu.h ***************************************/
95448/*
95449** 2008 May 26
95450**
95451** The author disclaims copyright to this source code.  In place of
95452** a legal notice, here is a blessing:
95453**
95454**    May you do good and not evil.
95455**    May you find forgiveness for yourself and forgive others.
95456**    May you share freely, never taking more than you give.
95457**
95458******************************************************************************
95459**
95460** This header file is used by programs that want to link against the
95461** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
95462*/
95463
95464#if 0
95465extern "C" {
95466#endif  /* __cplusplus */
95467
95468SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
95469
95470#if 0
95471}  /* extern "C" */
95472#endif  /* __cplusplus */
95473
95474
95475/************** End of sqliteicu.h *******************************************/
95476/************** Continuing where we left off in main.c ***********************/
95477#endif
95478
95479/*
95480** The version of the library
95481*/
95482#ifndef SQLITE_AMALGAMATION
95483SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
95484#endif
95485SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
95486SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
95487SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
95488SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
95489
95490#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
95491/*
95492** If the following function pointer is not NULL and if
95493** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
95494** I/O active are written using this function.  These messages
95495** are intended for debugging activity only.
95496*/
95497SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
95498#endif
95499
95500/*
95501** If the following global variable points to a string which is the
95502** name of a directory, then that directory will be used to store
95503** temporary files.
95504**
95505** See also the "PRAGMA temp_store_directory" SQL command.
95506*/
95507SQLITE_API char *sqlite3_temp_directory = 0;
95508
95509/*
95510** Initialize SQLite.
95511**
95512** This routine must be called to initialize the memory allocation,
95513** VFS, and mutex subsystems prior to doing any serious work with
95514** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
95515** this routine will be called automatically by key routines such as
95516** sqlite3_open().
95517**
95518** This routine is a no-op except on its very first call for the process,
95519** or for the first call after a call to sqlite3_shutdown.
95520**
95521** The first thread to call this routine runs the initialization to
95522** completion.  If subsequent threads call this routine before the first
95523** thread has finished the initialization process, then the subsequent
95524** threads must block until the first thread finishes with the initialization.
95525**
95526** The first thread might call this routine recursively.  Recursive
95527** calls to this routine should not block, of course.  Otherwise the
95528** initialization process would never complete.
95529**
95530** Let X be the first thread to enter this routine.  Let Y be some other
95531** thread.  Then while the initial invocation of this routine by X is
95532** incomplete, it is required that:
95533**
95534**    *  Calls to this routine from Y must block until the outer-most
95535**       call by X completes.
95536**
95537**    *  Recursive calls to this routine from thread X return immediately
95538**       without blocking.
95539*/
95540SQLITE_API int sqlite3_initialize(void){
95541  sqlite3_mutex *pMaster;                      /* The main static mutex */
95542  int rc;                                      /* Result code */
95543
95544#ifdef SQLITE_OMIT_WSD
95545  rc = sqlite3_wsd_init(4096, 24);
95546  if( rc!=SQLITE_OK ){
95547    return rc;
95548  }
95549#endif
95550
95551  /* If SQLite is already completely initialized, then this call
95552  ** to sqlite3_initialize() should be a no-op.  But the initialization
95553  ** must be complete.  So isInit must not be set until the very end
95554  ** of this routine.
95555  */
95556  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
95557
95558  /* Make sure the mutex subsystem is initialized.  If unable to
95559  ** initialize the mutex subsystem, return early with the error.
95560  ** If the system is so sick that we are unable to allocate a mutex,
95561  ** there is not much SQLite is going to be able to do.
95562  **
95563  ** The mutex subsystem must take care of serializing its own
95564  ** initialization.
95565  */
95566  rc = sqlite3MutexInit();
95567  if( rc ) return rc;
95568
95569  /* Initialize the malloc() system and the recursive pInitMutex mutex.
95570  ** This operation is protected by the STATIC_MASTER mutex.  Note that
95571  ** MutexAlloc() is called for a static mutex prior to initializing the
95572  ** malloc subsystem - this implies that the allocation of a static
95573  ** mutex must not require support from the malloc subsystem.
95574  */
95575  pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
95576  sqlite3_mutex_enter(pMaster);
95577  sqlite3GlobalConfig.isMutexInit = 1;
95578  if( !sqlite3GlobalConfig.isMallocInit ){
95579    rc = sqlite3MallocInit();
95580  }
95581  if( rc==SQLITE_OK ){
95582    sqlite3GlobalConfig.isMallocInit = 1;
95583    if( !sqlite3GlobalConfig.pInitMutex ){
95584      sqlite3GlobalConfig.pInitMutex =
95585           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
95586      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
95587        rc = SQLITE_NOMEM;
95588      }
95589    }
95590  }
95591  if( rc==SQLITE_OK ){
95592    sqlite3GlobalConfig.nRefInitMutex++;
95593  }
95594  sqlite3_mutex_leave(pMaster);
95595
95596  /* If rc is not SQLITE_OK at this point, then either the malloc
95597  ** subsystem could not be initialized or the system failed to allocate
95598  ** the pInitMutex mutex. Return an error in either case.  */
95599  if( rc!=SQLITE_OK ){
95600    return rc;
95601  }
95602
95603  /* Do the rest of the initialization under the recursive mutex so
95604  ** that we will be able to handle recursive calls into
95605  ** sqlite3_initialize().  The recursive calls normally come through
95606  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
95607  ** recursive calls might also be possible.
95608  */
95609  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
95610  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
95611    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
95612    sqlite3GlobalConfig.inProgress = 1;
95613    memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
95614    sqlite3RegisterGlobalFunctions();
95615    if( sqlite3GlobalConfig.isPCacheInit==0 ){
95616      rc = sqlite3PcacheInitialize();
95617    }
95618    if( rc==SQLITE_OK ){
95619      sqlite3GlobalConfig.isPCacheInit = 1;
95620      rc = sqlite3OsInit();
95621    }
95622    if( rc==SQLITE_OK ){
95623      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
95624          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
95625      sqlite3GlobalConfig.isInit = 1;
95626    }
95627    sqlite3GlobalConfig.inProgress = 0;
95628  }
95629  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
95630
95631  /* Go back under the static mutex and clean up the recursive
95632  ** mutex to prevent a resource leak.
95633  */
95634  sqlite3_mutex_enter(pMaster);
95635  sqlite3GlobalConfig.nRefInitMutex--;
95636  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
95637    assert( sqlite3GlobalConfig.nRefInitMutex==0 );
95638    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
95639    sqlite3GlobalConfig.pInitMutex = 0;
95640  }
95641  sqlite3_mutex_leave(pMaster);
95642
95643  /* The following is just a sanity check to make sure SQLite has
95644  ** been compiled correctly.  It is important to run this code, but
95645  ** we don't want to run it too often and soak up CPU cycles for no
95646  ** reason.  So we run it once during initialization.
95647  */
95648#ifndef NDEBUG
95649#ifndef SQLITE_OMIT_FLOATING_POINT
95650  /* This section of code's only "output" is via assert() statements. */
95651  if ( rc==SQLITE_OK ){
95652    u64 x = (((u64)1)<<63)-1;
95653    double y;
95654    assert(sizeof(x)==8);
95655    assert(sizeof(x)==sizeof(y));
95656    memcpy(&y, &x, 8);
95657    assert( sqlite3IsNaN(y) );
95658  }
95659#endif
95660#endif
95661
95662  return rc;
95663}
95664
95665/*
95666** Undo the effects of sqlite3_initialize().  Must not be called while
95667** there are outstanding database connections or memory allocations or
95668** while any part of SQLite is otherwise in use in any thread.  This
95669** routine is not threadsafe.  But it is safe to invoke this routine
95670** on when SQLite is already shut down.  If SQLite is already shut down
95671** when this routine is invoked, then this routine is a harmless no-op.
95672*/
95673SQLITE_API int sqlite3_shutdown(void){
95674  if( sqlite3GlobalConfig.isInit ){
95675    sqlite3_os_end();
95676    sqlite3_reset_auto_extension();
95677    sqlite3GlobalConfig.isInit = 0;
95678  }
95679  if( sqlite3GlobalConfig.isPCacheInit ){
95680    sqlite3PcacheShutdown();
95681    sqlite3GlobalConfig.isPCacheInit = 0;
95682  }
95683  if( sqlite3GlobalConfig.isMallocInit ){
95684    sqlite3MallocEnd();
95685    sqlite3GlobalConfig.isMallocInit = 0;
95686  }
95687  if( sqlite3GlobalConfig.isMutexInit ){
95688    sqlite3MutexEnd();
95689    sqlite3GlobalConfig.isMutexInit = 0;
95690  }
95691
95692  return SQLITE_OK;
95693}
95694
95695/*
95696** This API allows applications to modify the global configuration of
95697** the SQLite library at run-time.
95698**
95699** This routine should only be called when there are no outstanding
95700** database connections or memory allocations.  This routine is not
95701** threadsafe.  Failure to heed these warnings can lead to unpredictable
95702** behavior.
95703*/
95704SQLITE_API int sqlite3_config(int op, ...){
95705  va_list ap;
95706  int rc = SQLITE_OK;
95707
95708  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
95709  ** the SQLite library is in use. */
95710  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
95711
95712  va_start(ap, op);
95713  switch( op ){
95714
95715    /* Mutex configuration options are only available in a threadsafe
95716    ** compile.
95717    */
95718#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
95719    case SQLITE_CONFIG_SINGLETHREAD: {
95720      /* Disable all mutexing */
95721      sqlite3GlobalConfig.bCoreMutex = 0;
95722      sqlite3GlobalConfig.bFullMutex = 0;
95723      break;
95724    }
95725    case SQLITE_CONFIG_MULTITHREAD: {
95726      /* Disable mutexing of database connections */
95727      /* Enable mutexing of core data structures */
95728      sqlite3GlobalConfig.bCoreMutex = 1;
95729      sqlite3GlobalConfig.bFullMutex = 0;
95730      break;
95731    }
95732    case SQLITE_CONFIG_SERIALIZED: {
95733      /* Enable all mutexing */
95734      sqlite3GlobalConfig.bCoreMutex = 1;
95735      sqlite3GlobalConfig.bFullMutex = 1;
95736      break;
95737    }
95738    case SQLITE_CONFIG_MUTEX: {
95739      /* Specify an alternative mutex implementation */
95740      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
95741      break;
95742    }
95743    case SQLITE_CONFIG_GETMUTEX: {
95744      /* Retrieve the current mutex implementation */
95745      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
95746      break;
95747    }
95748#endif
95749
95750
95751    case SQLITE_CONFIG_MALLOC: {
95752      /* Specify an alternative malloc implementation */
95753      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
95754      break;
95755    }
95756    case SQLITE_CONFIG_GETMALLOC: {
95757      /* Retrieve the current malloc() implementation */
95758      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
95759      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
95760      break;
95761    }
95762    case SQLITE_CONFIG_MEMSTATUS: {
95763      /* Enable or disable the malloc status collection */
95764      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
95765      break;
95766    }
95767    case SQLITE_CONFIG_SCRATCH: {
95768      /* Designate a buffer for scratch memory space */
95769      sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
95770      sqlite3GlobalConfig.szScratch = va_arg(ap, int);
95771      sqlite3GlobalConfig.nScratch = va_arg(ap, int);
95772      break;
95773    }
95774    case SQLITE_CONFIG_PAGECACHE: {
95775      /* Designate a buffer for page cache memory space */
95776      sqlite3GlobalConfig.pPage = va_arg(ap, void*);
95777      sqlite3GlobalConfig.szPage = va_arg(ap, int);
95778      sqlite3GlobalConfig.nPage = va_arg(ap, int);
95779      break;
95780    }
95781
95782    case SQLITE_CONFIG_PCACHE: {
95783      /* Specify an alternative page cache implementation */
95784      sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
95785      break;
95786    }
95787
95788    case SQLITE_CONFIG_GETPCACHE: {
95789      if( sqlite3GlobalConfig.pcache.xInit==0 ){
95790        sqlite3PCacheSetDefault();
95791      }
95792      *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
95793      break;
95794    }
95795
95796#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
95797    case SQLITE_CONFIG_HEAP: {
95798      /* Designate a buffer for heap memory space */
95799      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
95800      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
95801      sqlite3GlobalConfig.mnReq = va_arg(ap, int);
95802
95803      if( sqlite3GlobalConfig.pHeap==0 ){
95804        /* If the heap pointer is NULL, then restore the malloc implementation
95805        ** back to NULL pointers too.  This will cause the malloc to go
95806        ** back to its default implementation when sqlite3_initialize() is
95807        ** run.
95808        */
95809        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
95810      }else{
95811        /* The heap pointer is not NULL, then install one of the
95812        ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
95813        ** ENABLE_MEMSYS5 is defined, return an error.
95814        */
95815#ifdef SQLITE_ENABLE_MEMSYS3
95816        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
95817#endif
95818#ifdef SQLITE_ENABLE_MEMSYS5
95819        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
95820#endif
95821      }
95822      break;
95823    }
95824#endif
95825
95826    case SQLITE_CONFIG_LOOKASIDE: {
95827      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
95828      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
95829      break;
95830    }
95831
95832    /* Record a pointer to the logger funcction and its first argument.
95833    ** The default is NULL.  Logging is disabled if the function pointer is
95834    ** NULL.
95835    */
95836    case SQLITE_CONFIG_LOG: {
95837      sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
95838      sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
95839      break;
95840    }
95841
95842    default: {
95843      rc = SQLITE_ERROR;
95844      break;
95845    }
95846  }
95847  va_end(ap);
95848  return rc;
95849}
95850
95851/*
95852** Set up the lookaside buffers for a database connection.
95853** Return SQLITE_OK on success.
95854** If lookaside is already active, return SQLITE_BUSY.
95855**
95856** The sz parameter is the number of bytes in each lookaside slot.
95857** The cnt parameter is the number of slots.  If pStart is NULL the
95858** space for the lookaside memory is obtained from sqlite3_malloc().
95859** If pStart is not NULL then it is sz*cnt bytes of memory to use for
95860** the lookaside memory.
95861*/
95862static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
95863  void *pStart;
95864  if( db->lookaside.nOut ){
95865    return SQLITE_BUSY;
95866  }
95867  /* Free any existing lookaside buffer for this handle before
95868  ** allocating a new one so we don't have to have space for
95869  ** both at the same time.
95870  */
95871  if( db->lookaside.bMalloced ){
95872    sqlite3_free(db->lookaside.pStart);
95873  }
95874  /* The size of a lookaside slot needs to be larger than a pointer
95875  ** to be useful.
95876  */
95877  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
95878  if( cnt<0 ) cnt = 0;
95879  if( sz==0 || cnt==0 ){
95880    sz = 0;
95881    pStart = 0;
95882  }else if( pBuf==0 ){
95883    sz = ROUND8(sz);
95884    sqlite3BeginBenignMalloc();
95885    pStart = sqlite3Malloc( sz*cnt );
95886    sqlite3EndBenignMalloc();
95887  }else{
95888    sz = ROUNDDOWN8(sz);
95889    pStart = pBuf;
95890  }
95891  db->lookaside.pStart = pStart;
95892  db->lookaside.pFree = 0;
95893  db->lookaside.sz = (u16)sz;
95894  if( pStart ){
95895    int i;
95896    LookasideSlot *p;
95897    assert( sz > (int)sizeof(LookasideSlot*) );
95898    p = (LookasideSlot*)pStart;
95899    for(i=cnt-1; i>=0; i--){
95900      p->pNext = db->lookaside.pFree;
95901      db->lookaside.pFree = p;
95902      p = (LookasideSlot*)&((u8*)p)[sz];
95903    }
95904    db->lookaside.pEnd = p;
95905    db->lookaside.bEnabled = 1;
95906    db->lookaside.bMalloced = pBuf==0 ?1:0;
95907  }else{
95908    db->lookaside.pEnd = 0;
95909    db->lookaside.bEnabled = 0;
95910    db->lookaside.bMalloced = 0;
95911  }
95912  return SQLITE_OK;
95913}
95914
95915/*
95916** Return the mutex associated with a database connection.
95917*/
95918SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
95919  return db->mutex;
95920}
95921
95922/*
95923** Configuration settings for an individual database connection
95924*/
95925SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
95926  va_list ap;
95927  int rc;
95928  va_start(ap, op);
95929  switch( op ){
95930    case SQLITE_DBCONFIG_LOOKASIDE: {
95931      void *pBuf = va_arg(ap, void*);
95932      int sz = va_arg(ap, int);
95933      int cnt = va_arg(ap, int);
95934      rc = setupLookaside(db, pBuf, sz, cnt);
95935      break;
95936    }
95937    default: {
95938      rc = SQLITE_ERROR;
95939      break;
95940    }
95941  }
95942  va_end(ap);
95943  return rc;
95944}
95945
95946
95947/*
95948** Return true if the buffer z[0..n-1] contains all spaces.
95949*/
95950static int allSpaces(const char *z, int n){
95951  while( n>0 && z[n-1]==' ' ){ n--; }
95952  return n==0;
95953}
95954
95955/*
95956** This is the default collating function named "BINARY" which is always
95957** available.
95958**
95959** If the padFlag argument is not NULL then space padding at the end
95960** of strings is ignored.  This implements the RTRIM collation.
95961*/
95962static int binCollFunc(
95963  void *padFlag,
95964  int nKey1, const void *pKey1,
95965  int nKey2, const void *pKey2
95966){
95967  int rc, n;
95968  n = nKey1<nKey2 ? nKey1 : nKey2;
95969  rc = memcmp(pKey1, pKey2, n);
95970  if( rc==0 ){
95971    if( padFlag
95972     && allSpaces(((char*)pKey1)+n, nKey1-n)
95973     && allSpaces(((char*)pKey2)+n, nKey2-n)
95974    ){
95975      /* Leave rc unchanged at 0 */
95976    }else{
95977      rc = nKey1 - nKey2;
95978    }
95979  }
95980  return rc;
95981}
95982
95983/*
95984** Another built-in collating sequence: NOCASE.
95985**
95986** This collating sequence is intended to be used for "case independant
95987** comparison". SQLite's knowledge of upper and lower case equivalents
95988** extends only to the 26 characters used in the English language.
95989**
95990** At the moment there is only a UTF-8 implementation.
95991*/
95992static int nocaseCollatingFunc(
95993  void *NotUsed,
95994  int nKey1, const void *pKey1,
95995  int nKey2, const void *pKey2
95996){
95997  int r = sqlite3StrNICmp(
95998      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
95999  UNUSED_PARAMETER(NotUsed);
96000  if( 0==r ){
96001    r = nKey1-nKey2;
96002  }
96003  return r;
96004}
96005
96006/*
96007** Return the ROWID of the most recent insert
96008*/
96009SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
96010  return db->lastRowid;
96011}
96012
96013/*
96014** Return the number of changes in the most recent call to sqlite3_exec().
96015*/
96016SQLITE_API int sqlite3_changes(sqlite3 *db){
96017  return db->nChange;
96018}
96019
96020/*
96021** Return the number of changes since the database handle was opened.
96022*/
96023SQLITE_API int sqlite3_total_changes(sqlite3 *db){
96024  return db->nTotalChange;
96025}
96026
96027/*
96028** Close all open savepoints. This function only manipulates fields of the
96029** database handle object, it does not close any savepoints that may be open
96030** at the b-tree/pager level.
96031*/
96032SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
96033  while( db->pSavepoint ){
96034    Savepoint *pTmp = db->pSavepoint;
96035    db->pSavepoint = pTmp->pNext;
96036    sqlite3DbFree(db, pTmp);
96037  }
96038  db->nSavepoint = 0;
96039  db->nStatement = 0;
96040  db->isTransactionSavepoint = 0;
96041}
96042
96043/*
96044** Close an existing SQLite database
96045*/
96046SQLITE_API int sqlite3_close(sqlite3 *db){
96047  HashElem *i;
96048  int j;
96049
96050  if( !db ){
96051    return SQLITE_OK;
96052  }
96053  if( !sqlite3SafetyCheckSickOrOk(db) ){
96054    return SQLITE_MISUSE_BKPT;
96055  }
96056  sqlite3_mutex_enter(db->mutex);
96057
96058  sqlite3ResetInternalSchema(db, 0);
96059
96060  /* If a transaction is open, the ResetInternalSchema() call above
96061  ** will not have called the xDisconnect() method on any virtual
96062  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
96063  ** call will do so. We need to do this before the check for active
96064  ** SQL statements below, as the v-table implementation may be storing
96065  ** some prepared statements internally.
96066  */
96067  sqlite3VtabRollback(db);
96068
96069  /* If there are any outstanding VMs, return SQLITE_BUSY. */
96070  if( db->pVdbe ){
96071    sqlite3Error(db, SQLITE_BUSY,
96072        "unable to close due to unfinalised statements");
96073    sqlite3_mutex_leave(db->mutex);
96074    return SQLITE_BUSY;
96075  }
96076  assert( sqlite3SafetyCheckSickOrOk(db) );
96077
96078  for(j=0; j<db->nDb; j++){
96079    Btree *pBt = db->aDb[j].pBt;
96080    if( pBt && sqlite3BtreeIsInBackup(pBt) ){
96081      sqlite3Error(db, SQLITE_BUSY,
96082          "unable to close due to unfinished backup operation");
96083      sqlite3_mutex_leave(db->mutex);
96084      return SQLITE_BUSY;
96085    }
96086  }
96087
96088  /* Free any outstanding Savepoint structures. */
96089  sqlite3CloseSavepoints(db);
96090
96091  for(j=0; j<db->nDb; j++){
96092    struct Db *pDb = &db->aDb[j];
96093    if( pDb->pBt ){
96094      sqlite3BtreeClose(pDb->pBt);
96095      pDb->pBt = 0;
96096      if( j!=1 ){
96097        pDb->pSchema = 0;
96098      }
96099    }
96100  }
96101  sqlite3ResetInternalSchema(db, 0);
96102
96103  /* Tell the code in notify.c that the connection no longer holds any
96104  ** locks and does not require any further unlock-notify callbacks.
96105  */
96106  sqlite3ConnectionClosed(db);
96107
96108  assert( db->nDb<=2 );
96109  assert( db->aDb==db->aDbStatic );
96110  for(j=0; j<ArraySize(db->aFunc.a); j++){
96111    FuncDef *pNext, *pHash, *p;
96112    for(p=db->aFunc.a[j]; p; p=pHash){
96113      pHash = p->pHash;
96114      while( p ){
96115        pNext = p->pNext;
96116        sqlite3DbFree(db, p);
96117        p = pNext;
96118      }
96119    }
96120  }
96121  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
96122    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
96123    /* Invoke any destructors registered for collation sequence user data. */
96124    for(j=0; j<3; j++){
96125      if( pColl[j].xDel ){
96126        pColl[j].xDel(pColl[j].pUser);
96127      }
96128    }
96129    sqlite3DbFree(db, pColl);
96130  }
96131  sqlite3HashClear(&db->aCollSeq);
96132#ifndef SQLITE_OMIT_VIRTUALTABLE
96133  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
96134    Module *pMod = (Module *)sqliteHashData(i);
96135    if( pMod->xDestroy ){
96136      pMod->xDestroy(pMod->pAux);
96137    }
96138    sqlite3DbFree(db, pMod);
96139  }
96140  sqlite3HashClear(&db->aModule);
96141#endif
96142
96143  sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
96144  if( db->pErr ){
96145    sqlite3ValueFree(db->pErr);
96146  }
96147  sqlite3CloseExtensions(db);
96148
96149  db->magic = SQLITE_MAGIC_ERROR;
96150
96151  /* The temp-database schema is allocated differently from the other schema
96152  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
96153  ** So it needs to be freed here. Todo: Why not roll the temp schema into
96154  ** the same sqliteMalloc() as the one that allocates the database
96155  ** structure?
96156  */
96157  sqlite3DbFree(db, db->aDb[1].pSchema);
96158  sqlite3_mutex_leave(db->mutex);
96159  db->magic = SQLITE_MAGIC_CLOSED;
96160  sqlite3_mutex_free(db->mutex);
96161  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
96162  if( db->lookaside.bMalloced ){
96163    sqlite3_free(db->lookaside.pStart);
96164  }
96165  sqlite3_free(db);
96166  return SQLITE_OK;
96167}
96168
96169/*
96170** Rollback all database files.
96171*/
96172SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
96173  int i;
96174  int inTrans = 0;
96175  assert( sqlite3_mutex_held(db->mutex) );
96176  sqlite3BeginBenignMalloc();
96177  for(i=0; i<db->nDb; i++){
96178    if( db->aDb[i].pBt ){
96179      if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
96180        inTrans = 1;
96181      }
96182      sqlite3BtreeRollback(db->aDb[i].pBt);
96183      db->aDb[i].inTrans = 0;
96184    }
96185  }
96186  sqlite3VtabRollback(db);
96187  sqlite3EndBenignMalloc();
96188
96189  if( db->flags&SQLITE_InternChanges ){
96190    sqlite3ExpirePreparedStatements(db);
96191    sqlite3ResetInternalSchema(db, 0);
96192  }
96193
96194  /* Any deferred constraint violations have now been resolved. */
96195  db->nDeferredCons = 0;
96196
96197  /* If one has been configured, invoke the rollback-hook callback */
96198  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
96199    db->xRollbackCallback(db->pRollbackArg);
96200  }
96201}
96202
96203/*
96204** Return a static string that describes the kind of error specified in the
96205** argument.
96206*/
96207SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
96208  static const char* const aMsg[] = {
96209    /* SQLITE_OK          */ "not an error",
96210    /* SQLITE_ERROR       */ "SQL logic error or missing database",
96211    /* SQLITE_INTERNAL    */ 0,
96212    /* SQLITE_PERM        */ "access permission denied",
96213    /* SQLITE_ABORT       */ "callback requested query abort",
96214    /* SQLITE_BUSY        */ "database is locked",
96215    /* SQLITE_LOCKED      */ "database table is locked",
96216    /* SQLITE_NOMEM       */ "out of memory",
96217    /* SQLITE_READONLY    */ "attempt to write a readonly database",
96218    /* SQLITE_INTERRUPT   */ "interrupted",
96219    /* SQLITE_IOERR       */ "disk I/O error",
96220    /* SQLITE_CORRUPT     */ "database disk image is malformed",
96221    /* SQLITE_NOTFOUND    */ 0,
96222    /* SQLITE_FULL        */ "database or disk is full",
96223    /* SQLITE_CANTOPEN    */ "unable to open database file",
96224    /* SQLITE_PROTOCOL    */ 0,
96225    /* SQLITE_EMPTY       */ "table contains no data",
96226    /* SQLITE_SCHEMA      */ "database schema has changed",
96227    /* SQLITE_TOOBIG      */ "string or blob too big",
96228    /* SQLITE_CONSTRAINT  */ "constraint failed",
96229    /* SQLITE_MISMATCH    */ "datatype mismatch",
96230    /* SQLITE_MISUSE      */ "library routine called out of sequence",
96231    /* SQLITE_NOLFS       */ "large file support is disabled",
96232    /* SQLITE_AUTH        */ "authorization denied",
96233    /* SQLITE_FORMAT      */ "auxiliary database format error",
96234    /* SQLITE_RANGE       */ "bind or column index out of range",
96235    /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
96236  };
96237  rc &= 0xff;
96238  if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
96239    return aMsg[rc];
96240  }else{
96241    return "unknown error";
96242  }
96243}
96244
96245/*
96246** This routine implements a busy callback that sleeps and tries
96247** again until a timeout value is reached.  The timeout value is
96248** an integer number of milliseconds passed in as the first
96249** argument.
96250*/
96251static int sqliteDefaultBusyCallback(
96252 void *ptr,               /* Database connection */
96253 int count                /* Number of times table has been busy */
96254){
96255#if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
96256  static const u8 delays[] =
96257     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
96258  static const u8 totals[] =
96259     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
96260# define NDELAY (sizeof(delays)/sizeof(delays[0]))
96261  sqlite3 *db = (sqlite3 *)ptr;
96262  int timeout = db->busyTimeout;
96263  int delay, prior;
96264
96265  assert( count>=0 );
96266  if( count < NDELAY ){
96267    delay = delays[count];
96268    prior = totals[count];
96269  }else{
96270    delay = delays[NDELAY-1];
96271    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
96272  }
96273  if( prior + delay > timeout ){
96274    delay = timeout - prior;
96275    if( delay<=0 ) return 0;
96276  }
96277  sqlite3OsSleep(db->pVfs, delay*1000);
96278  return 1;
96279#else
96280  sqlite3 *db = (sqlite3 *)ptr;
96281  int timeout = ((sqlite3 *)ptr)->busyTimeout;
96282  if( (count+1)*1000 > timeout ){
96283    return 0;
96284  }
96285  sqlite3OsSleep(db->pVfs, 1000000);
96286  return 1;
96287#endif
96288}
96289
96290/*
96291** Invoke the given busy handler.
96292**
96293** This routine is called when an operation failed with a lock.
96294** If this routine returns non-zero, the lock is retried.  If it
96295** returns 0, the operation aborts with an SQLITE_BUSY error.
96296*/
96297SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
96298  int rc;
96299  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
96300  rc = p->xFunc(p->pArg, p->nBusy);
96301  if( rc==0 ){
96302    p->nBusy = -1;
96303  }else{
96304    p->nBusy++;
96305  }
96306  return rc;
96307}
96308
96309/*
96310** This routine sets the busy callback for an Sqlite database to the
96311** given callback function with the given argument.
96312*/
96313SQLITE_API int sqlite3_busy_handler(
96314  sqlite3 *db,
96315  int (*xBusy)(void*,int),
96316  void *pArg
96317){
96318  sqlite3_mutex_enter(db->mutex);
96319  db->busyHandler.xFunc = xBusy;
96320  db->busyHandler.pArg = pArg;
96321  db->busyHandler.nBusy = 0;
96322  sqlite3_mutex_leave(db->mutex);
96323  return SQLITE_OK;
96324}
96325
96326#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
96327/*
96328** This routine sets the progress callback for an Sqlite database to the
96329** given callback function with the given argument. The progress callback will
96330** be invoked every nOps opcodes.
96331*/
96332SQLITE_API void sqlite3_progress_handler(
96333  sqlite3 *db,
96334  int nOps,
96335  int (*xProgress)(void*),
96336  void *pArg
96337){
96338  sqlite3_mutex_enter(db->mutex);
96339  if( nOps>0 ){
96340    db->xProgress = xProgress;
96341    db->nProgressOps = nOps;
96342    db->pProgressArg = pArg;
96343  }else{
96344    db->xProgress = 0;
96345    db->nProgressOps = 0;
96346    db->pProgressArg = 0;
96347  }
96348  sqlite3_mutex_leave(db->mutex);
96349}
96350#endif
96351
96352
96353/*
96354** This routine installs a default busy handler that waits for the
96355** specified number of milliseconds before returning 0.
96356*/
96357SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
96358  if( ms>0 ){
96359    db->busyTimeout = ms;
96360    sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
96361  }else{
96362    sqlite3_busy_handler(db, 0, 0);
96363  }
96364  return SQLITE_OK;
96365}
96366
96367/*
96368** Cause any pending operation to stop at its earliest opportunity.
96369*/
96370SQLITE_API void sqlite3_interrupt(sqlite3 *db){
96371  db->u1.isInterrupted = 1;
96372}
96373
96374
96375/*
96376** This function is exactly the same as sqlite3_create_function(), except
96377** that it is designed to be called by internal code. The difference is
96378** that if a malloc() fails in sqlite3_create_function(), an error code
96379** is returned and the mallocFailed flag cleared.
96380*/
96381SQLITE_PRIVATE int sqlite3CreateFunc(
96382  sqlite3 *db,
96383  const char *zFunctionName,
96384  int nArg,
96385  int enc,
96386  void *pUserData,
96387  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
96388  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
96389  void (*xFinal)(sqlite3_context*)
96390){
96391  FuncDef *p;
96392  int nName;
96393
96394  assert( sqlite3_mutex_held(db->mutex) );
96395  if( zFunctionName==0 ||
96396      (xFunc && (xFinal || xStep)) ||
96397      (!xFunc && (xFinal && !xStep)) ||
96398      (!xFunc && (!xFinal && xStep)) ||
96399      (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
96400      (255<(nName = sqlite3Strlen30( zFunctionName))) ){
96401    return SQLITE_MISUSE_BKPT;
96402  }
96403
96404#ifndef SQLITE_OMIT_UTF16
96405  /* If SQLITE_UTF16 is specified as the encoding type, transform this
96406  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
96407  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
96408  **
96409  ** If SQLITE_ANY is specified, add three versions of the function
96410  ** to the hash table.
96411  */
96412  if( enc==SQLITE_UTF16 ){
96413    enc = SQLITE_UTF16NATIVE;
96414  }else if( enc==SQLITE_ANY ){
96415    int rc;
96416    rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
96417         pUserData, xFunc, xStep, xFinal);
96418    if( rc==SQLITE_OK ){
96419      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
96420          pUserData, xFunc, xStep, xFinal);
96421    }
96422    if( rc!=SQLITE_OK ){
96423      return rc;
96424    }
96425    enc = SQLITE_UTF16BE;
96426  }
96427#else
96428  enc = SQLITE_UTF8;
96429#endif
96430
96431  /* Check if an existing function is being overridden or deleted. If so,
96432  ** and there are active VMs, then return SQLITE_BUSY. If a function
96433  ** is being overridden/deleted but there are no active VMs, allow the
96434  ** operation to continue but invalidate all precompiled statements.
96435  */
96436  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
96437  if( p && p->iPrefEnc==enc && p->nArg==nArg ){
96438    if( db->activeVdbeCnt ){
96439      sqlite3Error(db, SQLITE_BUSY,
96440        "unable to delete/modify user-function due to active statements");
96441      assert( !db->mallocFailed );
96442      return SQLITE_BUSY;
96443    }else{
96444      sqlite3ExpirePreparedStatements(db);
96445    }
96446  }
96447
96448  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
96449  assert(p || db->mallocFailed);
96450  if( !p ){
96451    return SQLITE_NOMEM;
96452  }
96453  p->flags = 0;
96454  p->xFunc = xFunc;
96455  p->xStep = xStep;
96456  p->xFinalize = xFinal;
96457  p->pUserData = pUserData;
96458  p->nArg = (u16)nArg;
96459  return SQLITE_OK;
96460}
96461
96462/*
96463** Create new user functions.
96464*/
96465SQLITE_API int sqlite3_create_function(
96466  sqlite3 *db,
96467  const char *zFunctionName,
96468  int nArg,
96469  int enc,
96470  void *p,
96471  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
96472  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
96473  void (*xFinal)(sqlite3_context*)
96474){
96475  int rc;
96476  sqlite3_mutex_enter(db->mutex);
96477  rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
96478  rc = sqlite3ApiExit(db, rc);
96479  sqlite3_mutex_leave(db->mutex);
96480  return rc;
96481}
96482
96483#ifndef SQLITE_OMIT_UTF16
96484SQLITE_API int sqlite3_create_function16(
96485  sqlite3 *db,
96486  const void *zFunctionName,
96487  int nArg,
96488  int eTextRep,
96489  void *p,
96490  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
96491  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
96492  void (*xFinal)(sqlite3_context*)
96493){
96494  int rc;
96495  char *zFunc8;
96496  sqlite3_mutex_enter(db->mutex);
96497  assert( !db->mallocFailed );
96498  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
96499  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
96500  sqlite3DbFree(db, zFunc8);
96501  rc = sqlite3ApiExit(db, rc);
96502  sqlite3_mutex_leave(db->mutex);
96503  return rc;
96504}
96505#endif
96506
96507
96508/*
96509** Declare that a function has been overloaded by a virtual table.
96510**
96511** If the function already exists as a regular global function, then
96512** this routine is a no-op.  If the function does not exist, then create
96513** a new one that always throws a run-time error.
96514**
96515** When virtual tables intend to provide an overloaded function, they
96516** should call this routine to make sure the global function exists.
96517** A global function must exist in order for name resolution to work
96518** properly.
96519*/
96520SQLITE_API int sqlite3_overload_function(
96521  sqlite3 *db,
96522  const char *zName,
96523  int nArg
96524){
96525  int nName = sqlite3Strlen30(zName);
96526  int rc;
96527  sqlite3_mutex_enter(db->mutex);
96528  if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
96529    sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
96530                      0, sqlite3InvalidFunction, 0, 0);
96531  }
96532  rc = sqlite3ApiExit(db, SQLITE_OK);
96533  sqlite3_mutex_leave(db->mutex);
96534  return rc;
96535}
96536
96537#ifndef SQLITE_OMIT_TRACE
96538/*
96539** Register a trace function.  The pArg from the previously registered trace
96540** is returned.
96541**
96542** A NULL trace function means that no tracing is executes.  A non-NULL
96543** trace is a pointer to a function that is invoked at the start of each
96544** SQL statement.
96545*/
96546SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
96547  void *pOld;
96548  sqlite3_mutex_enter(db->mutex);
96549  pOld = db->pTraceArg;
96550  db->xTrace = xTrace;
96551  db->pTraceArg = pArg;
96552  sqlite3_mutex_leave(db->mutex);
96553  return pOld;
96554}
96555/*
96556** Register a profile function.  The pArg from the previously registered
96557** profile function is returned.
96558**
96559** A NULL profile function means that no profiling is executes.  A non-NULL
96560** profile is a pointer to a function that is invoked at the conclusion of
96561** each SQL statement that is run.
96562*/
96563SQLITE_API void *sqlite3_profile(
96564  sqlite3 *db,
96565  void (*xProfile)(void*,const char*,sqlite_uint64),
96566  void *pArg
96567){
96568  void *pOld;
96569  sqlite3_mutex_enter(db->mutex);
96570  pOld = db->pProfileArg;
96571  db->xProfile = xProfile;
96572  db->pProfileArg = pArg;
96573  sqlite3_mutex_leave(db->mutex);
96574  return pOld;
96575}
96576#endif /* SQLITE_OMIT_TRACE */
96577
96578/*** EXPERIMENTAL ***
96579**
96580** Register a function to be invoked when a transaction comments.
96581** If the invoked function returns non-zero, then the commit becomes a
96582** rollback.
96583*/
96584SQLITE_API void *sqlite3_commit_hook(
96585  sqlite3 *db,              /* Attach the hook to this database */
96586  int (*xCallback)(void*),  /* Function to invoke on each commit */
96587  void *pArg                /* Argument to the function */
96588){
96589  void *pOld;
96590  sqlite3_mutex_enter(db->mutex);
96591  pOld = db->pCommitArg;
96592  db->xCommitCallback = xCallback;
96593  db->pCommitArg = pArg;
96594  sqlite3_mutex_leave(db->mutex);
96595  return pOld;
96596}
96597
96598/*
96599** Register a callback to be invoked each time a row is updated,
96600** inserted or deleted using this database connection.
96601*/
96602SQLITE_API void *sqlite3_update_hook(
96603  sqlite3 *db,              /* Attach the hook to this database */
96604  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
96605  void *pArg                /* Argument to the function */
96606){
96607  void *pRet;
96608  sqlite3_mutex_enter(db->mutex);
96609  pRet = db->pUpdateArg;
96610  db->xUpdateCallback = xCallback;
96611  db->pUpdateArg = pArg;
96612  sqlite3_mutex_leave(db->mutex);
96613  return pRet;
96614}
96615
96616/*
96617** Register a callback to be invoked each time a transaction is rolled
96618** back by this database connection.
96619*/
96620SQLITE_API void *sqlite3_rollback_hook(
96621  sqlite3 *db,              /* Attach the hook to this database */
96622  void (*xCallback)(void*), /* Callback function */
96623  void *pArg                /* Argument to the function */
96624){
96625  void *pRet;
96626  sqlite3_mutex_enter(db->mutex);
96627  pRet = db->pRollbackArg;
96628  db->xRollbackCallback = xCallback;
96629  db->pRollbackArg = pArg;
96630  sqlite3_mutex_leave(db->mutex);
96631  return pRet;
96632}
96633
96634/*
96635** This function returns true if main-memory should be used instead of
96636** a temporary file for transient pager files and statement journals.
96637** The value returned depends on the value of db->temp_store (runtime
96638** parameter) and the compile time value of SQLITE_TEMP_STORE. The
96639** following table describes the relationship between these two values
96640** and this functions return value.
96641**
96642**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
96643**   -----------------     --------------     ------------------------------
96644**   0                     any                file      (return 0)
96645**   1                     1                  file      (return 0)
96646**   1                     2                  memory    (return 1)
96647**   1                     0                  file      (return 0)
96648**   2                     1                  file      (return 0)
96649**   2                     2                  memory    (return 1)
96650**   2                     0                  memory    (return 1)
96651**   3                     any                memory    (return 1)
96652*/
96653SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
96654#if SQLITE_TEMP_STORE==1
96655  return ( db->temp_store==2 );
96656#endif
96657#if SQLITE_TEMP_STORE==2
96658  return ( db->temp_store!=1 );
96659#endif
96660#if SQLITE_TEMP_STORE==3
96661  return 1;
96662#endif
96663#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
96664  return 0;
96665#endif
96666}
96667
96668/*
96669** This routine is called to create a connection to a database BTree
96670** driver.  If zFilename is the name of a file, then that file is
96671** opened and used.  If zFilename is the magic name ":memory:" then
96672** the database is stored in memory (and is thus forgotten as soon as
96673** the connection is closed.)  If zFilename is NULL then the database
96674** is a "virtual" database for transient use only and is deleted as
96675** soon as the connection is closed.
96676**
96677** A virtual database can be either a disk file (that is automatically
96678** deleted when the file is closed) or it an be held entirely in memory.
96679** The sqlite3TempInMemory() function is used to determine which.
96680*/
96681SQLITE_PRIVATE int sqlite3BtreeFactory(
96682  sqlite3 *db,              /* Main database when opening aux otherwise 0 */
96683  const char *zFilename,    /* Name of the file containing the BTree database */
96684  int omitJournal,          /* if TRUE then do not journal this file */
96685  int nCache,               /* How many pages in the page cache */
96686  int vfsFlags,             /* Flags passed through to vfsOpen */
96687  Btree **ppBtree           /* Pointer to new Btree object written here */
96688){
96689  int btFlags = 0;
96690  int rc;
96691
96692  assert( sqlite3_mutex_held(db->mutex) );
96693  assert( ppBtree != 0);
96694  if( omitJournal ){
96695    btFlags |= BTREE_OMIT_JOURNAL;
96696  }
96697  if( db->flags & SQLITE_NoReadlock ){
96698    btFlags |= BTREE_NO_READLOCK;
96699  }
96700#ifndef SQLITE_OMIT_MEMORYDB
96701  if( zFilename==0 && sqlite3TempInMemory(db) ){
96702    zFilename = ":memory:";
96703  }
96704#endif
96705
96706  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
96707    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
96708  }
96709  rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
96710
96711  /* If the B-Tree was successfully opened, set the pager-cache size to the
96712  ** default value. Except, if the call to BtreeOpen() returned a handle
96713  ** open on an existing shared pager-cache, do not change the pager-cache
96714  ** size.
96715  */
96716  if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
96717    sqlite3BtreeSetCacheSize(*ppBtree, nCache);
96718  }
96719  return rc;
96720}
96721
96722/*
96723** Return UTF-8 encoded English language explanation of the most recent
96724** error.
96725*/
96726SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
96727  const char *z;
96728  if( !db ){
96729    return sqlite3ErrStr(SQLITE_NOMEM);
96730  }
96731  if( !sqlite3SafetyCheckSickOrOk(db) ){
96732    return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
96733  }
96734  sqlite3_mutex_enter(db->mutex);
96735  if( db->mallocFailed ){
96736    z = sqlite3ErrStr(SQLITE_NOMEM);
96737  }else{
96738    z = (char*)sqlite3_value_text(db->pErr);
96739    assert( !db->mallocFailed );
96740    if( z==0 ){
96741      z = sqlite3ErrStr(db->errCode);
96742    }
96743  }
96744  sqlite3_mutex_leave(db->mutex);
96745  return z;
96746}
96747
96748#ifndef SQLITE_OMIT_UTF16
96749/*
96750** Return UTF-16 encoded English language explanation of the most recent
96751** error.
96752*/
96753SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
96754  static const u16 outOfMem[] = {
96755    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
96756  };
96757  static const u16 misuse[] = {
96758    'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
96759    'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
96760    'c', 'a', 'l', 'l', 'e', 'd', ' ',
96761    'o', 'u', 't', ' ',
96762    'o', 'f', ' ',
96763    's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
96764  };
96765
96766  const void *z;
96767  if( !db ){
96768    return (void *)outOfMem;
96769  }
96770  if( !sqlite3SafetyCheckSickOrOk(db) ){
96771    return (void *)misuse;
96772  }
96773  sqlite3_mutex_enter(db->mutex);
96774  if( db->mallocFailed ){
96775    z = (void *)outOfMem;
96776  }else{
96777    z = sqlite3_value_text16(db->pErr);
96778    if( z==0 ){
96779      sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
96780           SQLITE_UTF8, SQLITE_STATIC);
96781      z = sqlite3_value_text16(db->pErr);
96782    }
96783    /* A malloc() may have failed within the call to sqlite3_value_text16()
96784    ** above. If this is the case, then the db->mallocFailed flag needs to
96785    ** be cleared before returning. Do this directly, instead of via
96786    ** sqlite3ApiExit(), to avoid setting the database handle error message.
96787    */
96788    db->mallocFailed = 0;
96789  }
96790  sqlite3_mutex_leave(db->mutex);
96791  return z;
96792}
96793#endif /* SQLITE_OMIT_UTF16 */
96794
96795/*
96796** Return the most recent error code generated by an SQLite routine. If NULL is
96797** passed to this function, we assume a malloc() failed during sqlite3_open().
96798*/
96799SQLITE_API int sqlite3_errcode(sqlite3 *db){
96800  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
96801    return SQLITE_MISUSE_BKPT;
96802  }
96803  if( !db || db->mallocFailed ){
96804    return SQLITE_NOMEM;
96805  }
96806  return db->errCode & db->errMask;
96807}
96808SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
96809  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
96810    return SQLITE_MISUSE_BKPT;
96811  }
96812  if( !db || db->mallocFailed ){
96813    return SQLITE_NOMEM;
96814  }
96815  return db->errCode;
96816}
96817
96818/*
96819** Create a new collating function for database "db".  The name is zName
96820** and the encoding is enc.
96821*/
96822static int createCollation(
96823  sqlite3* db,
96824  const char *zName,
96825  u8 enc,
96826  u8 collType,
96827  void* pCtx,
96828  int(*xCompare)(void*,int,const void*,int,const void*),
96829  void(*xDel)(void*)
96830){
96831  CollSeq *pColl;
96832  int enc2;
96833  int nName = sqlite3Strlen30(zName);
96834
96835  assert( sqlite3_mutex_held(db->mutex) );
96836
96837  /* If SQLITE_UTF16 is specified as the encoding type, transform this
96838  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
96839  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
96840  */
96841  enc2 = enc;
96842  testcase( enc2==SQLITE_UTF16 );
96843  testcase( enc2==SQLITE_UTF16_ALIGNED );
96844  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
96845    enc2 = SQLITE_UTF16NATIVE;
96846  }
96847  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
96848    return SQLITE_MISUSE_BKPT;
96849  }
96850
96851  /* Check if this call is removing or replacing an existing collation
96852  ** sequence. If so, and there are active VMs, return busy. If there
96853  ** are no active VMs, invalidate any pre-compiled statements.
96854  */
96855  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
96856  if( pColl && pColl->xCmp ){
96857    if( db->activeVdbeCnt ){
96858      sqlite3Error(db, SQLITE_BUSY,
96859        "unable to delete/modify collation sequence due to active statements");
96860      return SQLITE_BUSY;
96861    }
96862    sqlite3ExpirePreparedStatements(db);
96863
96864    /* If collation sequence pColl was created directly by a call to
96865    ** sqlite3_create_collation, and not generated by synthCollSeq(),
96866    ** then any copies made by synthCollSeq() need to be invalidated.
96867    ** Also, collation destructor - CollSeq.xDel() - function may need
96868    ** to be called.
96869    */
96870    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
96871      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
96872      int j;
96873      for(j=0; j<3; j++){
96874        CollSeq *p = &aColl[j];
96875        if( p->enc==pColl->enc ){
96876          if( p->xDel ){
96877            p->xDel(p->pUser);
96878          }
96879          p->xCmp = 0;
96880        }
96881      }
96882    }
96883  }
96884
96885  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
96886  if( pColl ){
96887    pColl->xCmp = xCompare;
96888    pColl->pUser = pCtx;
96889    pColl->xDel = xDel;
96890    pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
96891    pColl->type = collType;
96892  }
96893  sqlite3Error(db, SQLITE_OK, 0);
96894  return SQLITE_OK;
96895}
96896
96897
96898/*
96899** This array defines hard upper bounds on limit values.  The
96900** initializer must be kept in sync with the SQLITE_LIMIT_*
96901** #defines in sqlite3.h.
96902*/
96903static const int aHardLimit[] = {
96904  SQLITE_MAX_LENGTH,
96905  SQLITE_MAX_SQL_LENGTH,
96906  SQLITE_MAX_COLUMN,
96907  SQLITE_MAX_EXPR_DEPTH,
96908  SQLITE_MAX_COMPOUND_SELECT,
96909  SQLITE_MAX_VDBE_OP,
96910  SQLITE_MAX_FUNCTION_ARG,
96911  SQLITE_MAX_ATTACHED,
96912  SQLITE_MAX_LIKE_PATTERN_LENGTH,
96913  SQLITE_MAX_VARIABLE_NUMBER,
96914  SQLITE_MAX_TRIGGER_DEPTH,
96915};
96916
96917/*
96918** Make sure the hard limits are set to reasonable values
96919*/
96920#if SQLITE_MAX_LENGTH<100
96921# error SQLITE_MAX_LENGTH must be at least 100
96922#endif
96923#if SQLITE_MAX_SQL_LENGTH<100
96924# error SQLITE_MAX_SQL_LENGTH must be at least 100
96925#endif
96926#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
96927# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
96928#endif
96929#if SQLITE_MAX_COMPOUND_SELECT<2
96930# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
96931#endif
96932#if SQLITE_MAX_VDBE_OP<40
96933# error SQLITE_MAX_VDBE_OP must be at least 40
96934#endif
96935#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
96936# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
96937#endif
96938#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
96939# error SQLITE_MAX_ATTACHED must be between 0 and 30
96940#endif
96941#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
96942# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
96943#endif
96944#if SQLITE_MAX_COLUMN>32767
96945# error SQLITE_MAX_COLUMN must not exceed 32767
96946#endif
96947#if SQLITE_MAX_TRIGGER_DEPTH<1
96948# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
96949#endif
96950
96951
96952/*
96953** Change the value of a limit.  Report the old value.
96954** If an invalid limit index is supplied, report -1.
96955** Make no changes but still report the old value if the
96956** new limit is negative.
96957**
96958** A new lower limit does not shrink existing constructs.
96959** It merely prevents new constructs that exceed the limit
96960** from forming.
96961*/
96962SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
96963  int oldLimit;
96964  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
96965    return -1;
96966  }
96967  oldLimit = db->aLimit[limitId];
96968  if( newLimit>=0 ){
96969    if( newLimit>aHardLimit[limitId] ){
96970      newLimit = aHardLimit[limitId];
96971    }
96972    db->aLimit[limitId] = newLimit;
96973  }
96974  return oldLimit;
96975}
96976
96977/*
96978** This routine does the work of opening a database on behalf of
96979** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
96980** is UTF-8 encoded.
96981*/
96982static int openDatabase(
96983  const char *zFilename, /* Database filename UTF-8 encoded */
96984  sqlite3 **ppDb,        /* OUT: Returned database handle */
96985  unsigned flags,        /* Operational flags */
96986  const char *zVfs       /* Name of the VFS to use */
96987){
96988  sqlite3 *db;
96989  int rc;
96990  int isThreadsafe;
96991
96992  *ppDb = 0;
96993#ifndef SQLITE_OMIT_AUTOINIT
96994  rc = sqlite3_initialize();
96995  if( rc ) return rc;
96996#endif
96997
96998  if( sqlite3GlobalConfig.bCoreMutex==0 ){
96999    isThreadsafe = 0;
97000  }else if( flags & SQLITE_OPEN_NOMUTEX ){
97001    isThreadsafe = 0;
97002  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
97003    isThreadsafe = 1;
97004  }else{
97005    isThreadsafe = sqlite3GlobalConfig.bFullMutex;
97006  }
97007  if( flags & SQLITE_OPEN_PRIVATECACHE ){
97008    flags &= ~SQLITE_OPEN_SHAREDCACHE;
97009  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
97010    flags |= SQLITE_OPEN_SHAREDCACHE;
97011  }
97012
97013  /* Remove harmful bits from the flags parameter
97014  **
97015  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
97016  ** dealt with in the previous code block.  Besides these, the only
97017  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
97018  ** SQLITE_OPEN_READWRITE, and SQLITE_OPEN_CREATE.  Silently mask
97019  ** off all other flags.
97020  */
97021  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
97022               SQLITE_OPEN_EXCLUSIVE |
97023               SQLITE_OPEN_MAIN_DB |
97024               SQLITE_OPEN_TEMP_DB |
97025               SQLITE_OPEN_TRANSIENT_DB |
97026               SQLITE_OPEN_MAIN_JOURNAL |
97027               SQLITE_OPEN_TEMP_JOURNAL |
97028               SQLITE_OPEN_SUBJOURNAL |
97029               SQLITE_OPEN_MASTER_JOURNAL |
97030               SQLITE_OPEN_NOMUTEX |
97031               SQLITE_OPEN_FULLMUTEX
97032             );
97033
97034  /* Allocate the sqlite data structure */
97035  db = sqlite3MallocZero( sizeof(sqlite3) );
97036  if( db==0 ) goto opendb_out;
97037  if( isThreadsafe ){
97038    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
97039    if( db->mutex==0 ){
97040      sqlite3_free(db);
97041      db = 0;
97042      goto opendb_out;
97043    }
97044  }
97045  sqlite3_mutex_enter(db->mutex);
97046  db->errMask = 0xff;
97047  db->nDb = 2;
97048  db->magic = SQLITE_MAGIC_BUSY;
97049  db->aDb = db->aDbStatic;
97050
97051  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
97052  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
97053  db->autoCommit = 1;
97054  db->nextAutovac = -1;
97055  db->nextPagesize = 0;
97056  db->flags |= SQLITE_ShortColNames
97057#if SQLITE_DEFAULT_FILE_FORMAT<4
97058                 | SQLITE_LegacyFileFmt
97059#endif
97060#ifdef SQLITE_ENABLE_LOAD_EXTENSION
97061                 | SQLITE_LoadExtension
97062#endif
97063#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
97064                 | SQLITE_RecTriggers
97065#endif
97066      ;
97067  sqlite3HashInit(&db->aCollSeq);
97068#ifndef SQLITE_OMIT_VIRTUALTABLE
97069  sqlite3HashInit(&db->aModule);
97070#endif
97071
97072  db->pVfs = sqlite3_vfs_find(zVfs);
97073  if( !db->pVfs ){
97074    rc = SQLITE_ERROR;
97075    sqlite3Error(db, rc, "no such vfs: %s", zVfs);
97076    goto opendb_out;
97077  }
97078
97079  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
97080  ** and UTF-16, so add a version for each to avoid any unnecessary
97081  ** conversions. The only error that can occur here is a malloc() failure.
97082  */
97083  createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
97084                  binCollFunc, 0);
97085  createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
97086                  binCollFunc, 0);
97087  createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
97088                  binCollFunc, 0);
97089  createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
97090                  binCollFunc, 0);
97091  if( db->mallocFailed ){
97092    goto opendb_out;
97093  }
97094  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
97095  assert( db->pDfltColl!=0 );
97096
97097  /* Also add a UTF-8 case-insensitive collation sequence. */
97098  createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
97099                  nocaseCollatingFunc, 0);
97100
97101  /* Open the backend database driver */
97102  db->openFlags = flags;
97103  rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE,
97104                           flags | SQLITE_OPEN_MAIN_DB,
97105                           &db->aDb[0].pBt);
97106  if( rc!=SQLITE_OK ){
97107    if( rc==SQLITE_IOERR_NOMEM ){
97108      rc = SQLITE_NOMEM;
97109    }
97110    sqlite3Error(db, rc, 0);
97111    goto opendb_out;
97112  }
97113  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
97114  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
97115
97116
97117  /* The default safety_level for the main database is 'full'; for the temp
97118  ** database it is 'NONE'. This matches the pager layer defaults.
97119  */
97120  db->aDb[0].zName = "main";
97121  db->aDb[0].safety_level = 3;
97122  db->aDb[1].zName = "temp";
97123  db->aDb[1].safety_level = 1;
97124
97125  db->magic = SQLITE_MAGIC_OPEN;
97126  if( db->mallocFailed ){
97127    goto opendb_out;
97128  }
97129
97130  /* Register all built-in functions, but do not attempt to read the
97131  ** database schema yet. This is delayed until the first time the database
97132  ** is accessed.
97133  */
97134  sqlite3Error(db, SQLITE_OK, 0);
97135  sqlite3RegisterBuiltinFunctions(db);
97136
97137  /* Load automatic extensions - extensions that have been registered
97138  ** using the sqlite3_automatic_extension() API.
97139  */
97140  sqlite3AutoLoadExtensions(db);
97141  rc = sqlite3_errcode(db);
97142  if( rc!=SQLITE_OK ){
97143    goto opendb_out;
97144  }
97145
97146#ifdef SQLITE_ENABLE_FTS1
97147// Begin Android change
97148#error "Do not enable FTS1 on Android as FTS3_BACKWARDS has been in use"
97149// End Android add
97150  if( !db->mallocFailed ){
97151    extern int sqlite3Fts1Init(sqlite3*);
97152    rc = sqlite3Fts1Init(db);
97153  }
97154#endif
97155
97156#ifdef SQLITE_ENABLE_FTS2
97157// Begin Android change
97158#error "Do not enable FTS2 on Android as FTS3_BACKWARDS has been in use"
97159// End Android add
97160  if( !db->mallocFailed && rc==SQLITE_OK ){
97161    extern int sqlite3Fts2Init(sqlite3*);
97162    rc = sqlite3Fts2Init(db);
97163  }
97164#endif
97165
97166#ifdef SQLITE_ENABLE_FTS3
97167  // Begin Android change
97168  #ifdef SQLITE_ENABLE_FTS3_BACKWARDS
97169    /* Also register as fts1 and fts2, for backwards compatability on
97170    ** systems known to have never seen a pre-fts3 database.
97171    */
97172    if( !db->mallocFailed && rc==SQLITE_OK ){
97173      rc = sqlite3Fts3Init(db, "fts1");
97174    }
97175
97176    if( !db->mallocFailed && rc==SQLITE_OK ){
97177      rc = sqlite3Fts3Init(db, "fts2");
97178    }
97179  #endif
97180
97181    if( !db->mallocFailed && rc==SQLITE_OK ){
97182      rc = sqlite3Fts3Init(db, "fts3");
97183    }
97184  // End Android change
97185#endif
97186
97187#ifdef SQLITE_ENABLE_ICU
97188  if( !db->mallocFailed && rc==SQLITE_OK ){
97189    rc = sqlite3IcuInit(db);
97190  }
97191#endif
97192
97193#ifdef SQLITE_ENABLE_RTREE
97194  if( !db->mallocFailed && rc==SQLITE_OK){
97195    rc = sqlite3RtreeInit(db);
97196  }
97197#endif
97198
97199  sqlite3Error(db, rc, 0);
97200
97201  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
97202  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
97203  ** mode.  Doing nothing at all also makes NORMAL the default.
97204  */
97205#ifdef SQLITE_DEFAULT_LOCKING_MODE
97206  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
97207  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
97208                          SQLITE_DEFAULT_LOCKING_MODE);
97209#endif
97210
97211  /* Enable the lookaside-malloc subsystem */
97212  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
97213                        sqlite3GlobalConfig.nLookaside);
97214
97215opendb_out:
97216  if( db ){
97217    assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
97218    sqlite3_mutex_leave(db->mutex);
97219  }
97220  rc = sqlite3_errcode(db);
97221  if( rc==SQLITE_NOMEM ){
97222    sqlite3_close(db);
97223    db = 0;
97224  }else if( rc!=SQLITE_OK ){
97225    db->magic = SQLITE_MAGIC_SICK;
97226  }
97227  *ppDb = db;
97228  return sqlite3ApiExit(0, rc);
97229}
97230
97231/*
97232** Open a new database handle.
97233*/
97234SQLITE_API int sqlite3_open(
97235  const char *zFilename,
97236  sqlite3 **ppDb
97237){
97238  return openDatabase(zFilename, ppDb,
97239                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
97240}
97241SQLITE_API int sqlite3_open_v2(
97242  const char *filename,   /* Database filename (UTF-8) */
97243  sqlite3 **ppDb,         /* OUT: SQLite db handle */
97244  int flags,              /* Flags */
97245  const char *zVfs        /* Name of VFS module to use */
97246){
97247  return openDatabase(filename, ppDb, flags, zVfs);
97248}
97249
97250#ifndef SQLITE_OMIT_UTF16
97251/*
97252** Open a new database handle.
97253*/
97254SQLITE_API int sqlite3_open16(
97255  const void *zFilename,
97256  sqlite3 **ppDb
97257){
97258  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
97259  sqlite3_value *pVal;
97260  int rc;
97261
97262  assert( zFilename );
97263  assert( ppDb );
97264  *ppDb = 0;
97265#ifndef SQLITE_OMIT_AUTOINIT
97266  rc = sqlite3_initialize();
97267  if( rc ) return rc;
97268#endif
97269  pVal = sqlite3ValueNew(0);
97270  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
97271  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
97272  if( zFilename8 ){
97273    rc = openDatabase(zFilename8, ppDb,
97274                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
97275    assert( *ppDb || rc==SQLITE_NOMEM );
97276    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
97277      ENC(*ppDb) = SQLITE_UTF16NATIVE;
97278    }
97279  }else{
97280    rc = SQLITE_NOMEM;
97281  }
97282  sqlite3ValueFree(pVal);
97283
97284  return sqlite3ApiExit(0, rc);
97285}
97286#endif /* SQLITE_OMIT_UTF16 */
97287
97288/*
97289** Register a new collation sequence with the database handle db.
97290*/
97291SQLITE_API int sqlite3_create_collation(
97292  sqlite3* db,
97293  const char *zName,
97294  int enc,
97295  void* pCtx,
97296  int(*xCompare)(void*,int,const void*,int,const void*)
97297){
97298  int rc;
97299  sqlite3_mutex_enter(db->mutex);
97300  assert( !db->mallocFailed );
97301  rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
97302  rc = sqlite3ApiExit(db, rc);
97303  sqlite3_mutex_leave(db->mutex);
97304  return rc;
97305}
97306
97307/*
97308** Register a new collation sequence with the database handle db.
97309*/
97310SQLITE_API int sqlite3_create_collation_v2(
97311  sqlite3* db,
97312  const char *zName,
97313  int enc,
97314  void* pCtx,
97315  int(*xCompare)(void*,int,const void*,int,const void*),
97316  void(*xDel)(void*)
97317){
97318  int rc;
97319  sqlite3_mutex_enter(db->mutex);
97320  assert( !db->mallocFailed );
97321  rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
97322  rc = sqlite3ApiExit(db, rc);
97323  sqlite3_mutex_leave(db->mutex);
97324  return rc;
97325}
97326
97327#ifndef SQLITE_OMIT_UTF16
97328/*
97329** Register a new collation sequence with the database handle db.
97330*/
97331SQLITE_API int sqlite3_create_collation16(
97332  sqlite3* db,
97333  const void *zName,
97334  int enc,
97335  void* pCtx,
97336  int(*xCompare)(void*,int,const void*,int,const void*)
97337){
97338  int rc = SQLITE_OK;
97339  char *zName8;
97340  sqlite3_mutex_enter(db->mutex);
97341  assert( !db->mallocFailed );
97342  zName8 = sqlite3Utf16to8(db, zName, -1);
97343  if( zName8 ){
97344    rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
97345    sqlite3DbFree(db, zName8);
97346  }
97347  rc = sqlite3ApiExit(db, rc);
97348  sqlite3_mutex_leave(db->mutex);
97349  return rc;
97350}
97351#endif /* SQLITE_OMIT_UTF16 */
97352
97353/*
97354** Register a collation sequence factory callback with the database handle
97355** db. Replace any previously installed collation sequence factory.
97356*/
97357SQLITE_API int sqlite3_collation_needed(
97358  sqlite3 *db,
97359  void *pCollNeededArg,
97360  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
97361){
97362  sqlite3_mutex_enter(db->mutex);
97363  db->xCollNeeded = xCollNeeded;
97364  db->xCollNeeded16 = 0;
97365  db->pCollNeededArg = pCollNeededArg;
97366  sqlite3_mutex_leave(db->mutex);
97367  return SQLITE_OK;
97368}
97369
97370#ifndef SQLITE_OMIT_UTF16
97371/*
97372** Register a collation sequence factory callback with the database handle
97373** db. Replace any previously installed collation sequence factory.
97374*/
97375SQLITE_API int sqlite3_collation_needed16(
97376  sqlite3 *db,
97377  void *pCollNeededArg,
97378  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
97379){
97380  sqlite3_mutex_enter(db->mutex);
97381  db->xCollNeeded = 0;
97382  db->xCollNeeded16 = xCollNeeded16;
97383  db->pCollNeededArg = pCollNeededArg;
97384  sqlite3_mutex_leave(db->mutex);
97385  return SQLITE_OK;
97386}
97387#endif /* SQLITE_OMIT_UTF16 */
97388
97389#ifndef SQLITE_OMIT_GLOBALRECOVER
97390#ifndef SQLITE_OMIT_DEPRECATED
97391/*
97392** This function is now an anachronism. It used to be used to recover from a
97393** malloc() failure, but SQLite now does this automatically.
97394*/
97395SQLITE_API int sqlite3_global_recover(void){
97396  return SQLITE_OK;
97397}
97398#endif
97399#endif
97400
97401/*
97402** Test to see whether or not the database connection is in autocommit
97403** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
97404** by default.  Autocommit is disabled by a BEGIN statement and reenabled
97405** by the next COMMIT or ROLLBACK.
97406**
97407******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
97408*/
97409SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
97410  return db->autoCommit;
97411}
97412
97413/*
97414** The following routines are subtitutes for constants SQLITE_CORRUPT,
97415** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
97416** constants.  They server two purposes:
97417**
97418**   1.  Serve as a convenient place to set a breakpoint in a debugger
97419**       to detect when version error conditions occurs.
97420**
97421**   2.  Invoke sqlite3_log() to provide the source code location where
97422**       a low-level error is first detected.
97423*/
97424SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
97425  testcase( sqlite3GlobalConfig.xLog!=0 );
97426  sqlite3_log(SQLITE_CORRUPT,
97427              "database corruption found by source line %d", lineno);
97428  return SQLITE_CORRUPT;
97429}
97430SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
97431  testcase( sqlite3GlobalConfig.xLog!=0 );
97432  sqlite3_log(SQLITE_MISUSE, "misuse detected by source line %d", lineno);
97433  return SQLITE_MISUSE;
97434}
97435SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
97436  testcase( sqlite3GlobalConfig.xLog!=0 );
97437  sqlite3_log(SQLITE_CANTOPEN, "cannot open file at source line %d", lineno);
97438  return SQLITE_CANTOPEN;
97439}
97440
97441
97442#ifndef SQLITE_OMIT_DEPRECATED
97443/*
97444** This is a convenience routine that makes sure that all thread-specific
97445** data for this thread has been deallocated.
97446**
97447** SQLite no longer uses thread-specific data so this routine is now a
97448** no-op.  It is retained for historical compatibility.
97449*/
97450SQLITE_API void sqlite3_thread_cleanup(void){
97451}
97452#endif
97453
97454/*
97455** Return meta information about a specific column of a database table.
97456** See comment in sqlite3.h (sqlite.h.in) for details.
97457*/
97458#ifdef SQLITE_ENABLE_COLUMN_METADATA
97459SQLITE_API int sqlite3_table_column_metadata(
97460  sqlite3 *db,                /* Connection handle */
97461  const char *zDbName,        /* Database name or NULL */
97462  const char *zTableName,     /* Table name */
97463  const char *zColumnName,    /* Column name */
97464  char const **pzDataType,    /* OUTPUT: Declared data type */
97465  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
97466  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
97467  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
97468  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
97469){
97470  int rc;
97471  char *zErrMsg = 0;
97472  Table *pTab = 0;
97473  Column *pCol = 0;
97474  int iCol;
97475
97476  char const *zDataType = 0;
97477  char const *zCollSeq = 0;
97478  int notnull = 0;
97479  int primarykey = 0;
97480  int autoinc = 0;
97481
97482  /* Ensure the database schema has been loaded */
97483  sqlite3_mutex_enter(db->mutex);
97484  sqlite3BtreeEnterAll(db);
97485  rc = sqlite3Init(db, &zErrMsg);
97486  if( SQLITE_OK!=rc ){
97487    goto error_out;
97488  }
97489
97490  /* Locate the table in question */
97491  pTab = sqlite3FindTable(db, zTableName, zDbName);
97492  if( !pTab || pTab->pSelect ){
97493    pTab = 0;
97494    goto error_out;
97495  }
97496
97497  /* Find the column for which info is requested */
97498  if( sqlite3IsRowid(zColumnName) ){
97499    iCol = pTab->iPKey;
97500    if( iCol>=0 ){
97501      pCol = &pTab->aCol[iCol];
97502    }
97503  }else{
97504    for(iCol=0; iCol<pTab->nCol; iCol++){
97505      pCol = &pTab->aCol[iCol];
97506      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
97507        break;
97508      }
97509    }
97510    if( iCol==pTab->nCol ){
97511      pTab = 0;
97512      goto error_out;
97513    }
97514  }
97515
97516  /* The following block stores the meta information that will be returned
97517  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
97518  ** and autoinc. At this point there are two possibilities:
97519  **
97520  **     1. The specified column name was rowid", "oid" or "_rowid_"
97521  **        and there is no explicitly declared IPK column.
97522  **
97523  **     2. The table is not a view and the column name identified an
97524  **        explicitly declared column. Copy meta information from *pCol.
97525  */
97526  if( pCol ){
97527    zDataType = pCol->zType;
97528    zCollSeq = pCol->zColl;
97529    notnull = pCol->notNull!=0;
97530    primarykey  = pCol->isPrimKey!=0;
97531    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
97532  }else{
97533    zDataType = "INTEGER";
97534    primarykey = 1;
97535  }
97536  if( !zCollSeq ){
97537    zCollSeq = "BINARY";
97538  }
97539
97540error_out:
97541  sqlite3BtreeLeaveAll(db);
97542
97543  /* Whether the function call succeeded or failed, set the output parameters
97544  ** to whatever their local counterparts contain. If an error did occur,
97545  ** this has the effect of zeroing all output parameters.
97546  */
97547  if( pzDataType ) *pzDataType = zDataType;
97548  if( pzCollSeq ) *pzCollSeq = zCollSeq;
97549  if( pNotNull ) *pNotNull = notnull;
97550  if( pPrimaryKey ) *pPrimaryKey = primarykey;
97551  if( pAutoinc ) *pAutoinc = autoinc;
97552
97553  if( SQLITE_OK==rc && !pTab ){
97554    sqlite3DbFree(db, zErrMsg);
97555    zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
97556        zColumnName);
97557    rc = SQLITE_ERROR;
97558  }
97559  sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
97560  sqlite3DbFree(db, zErrMsg);
97561  rc = sqlite3ApiExit(db, rc);
97562  sqlite3_mutex_leave(db->mutex);
97563  return rc;
97564}
97565#endif
97566
97567/*
97568** Sleep for a little while.  Return the amount of time slept.
97569*/
97570SQLITE_API int sqlite3_sleep(int ms){
97571  sqlite3_vfs *pVfs;
97572  int rc;
97573  pVfs = sqlite3_vfs_find(0);
97574  if( pVfs==0 ) return 0;
97575
97576  /* This function works in milliseconds, but the underlying OsSleep()
97577  ** API uses microseconds. Hence the 1000's.
97578  */
97579  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
97580  return rc;
97581}
97582
97583/*
97584** Enable or disable the extended result codes.
97585*/
97586SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
97587  sqlite3_mutex_enter(db->mutex);
97588  db->errMask = onoff ? 0xffffffff : 0xff;
97589  sqlite3_mutex_leave(db->mutex);
97590  return SQLITE_OK;
97591}
97592
97593/*
97594** Invoke the xFileControl method on a particular database.
97595*/
97596SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
97597  int rc = SQLITE_ERROR;
97598  int iDb;
97599  sqlite3_mutex_enter(db->mutex);
97600  if( zDbName==0 ){
97601    iDb = 0;
97602  }else{
97603    for(iDb=0; iDb<db->nDb; iDb++){
97604      if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
97605    }
97606  }
97607  if( iDb<db->nDb ){
97608    Btree *pBtree = db->aDb[iDb].pBt;
97609    if( pBtree ){
97610      Pager *pPager;
97611      sqlite3_file *fd;
97612      sqlite3BtreeEnter(pBtree);
97613      pPager = sqlite3BtreePager(pBtree);
97614      assert( pPager!=0 );
97615      fd = sqlite3PagerFile(pPager);
97616      assert( fd!=0 );
97617      if( fd->pMethods ){
97618        rc = sqlite3OsFileControl(fd, op, pArg);
97619      }
97620      sqlite3BtreeLeave(pBtree);
97621    }
97622  }
97623  sqlite3_mutex_leave(db->mutex);
97624  return rc;
97625}
97626
97627/*
97628** Interface to the testing logic.
97629*/
97630SQLITE_API int sqlite3_test_control(int op, ...){
97631  int rc = 0;
97632#ifndef SQLITE_OMIT_BUILTIN_TEST
97633  va_list ap;
97634  va_start(ap, op);
97635  switch( op ){
97636
97637    /*
97638    ** Save the current state of the PRNG.
97639    */
97640    case SQLITE_TESTCTRL_PRNG_SAVE: {
97641      sqlite3PrngSaveState();
97642      break;
97643    }
97644
97645    /*
97646    ** Restore the state of the PRNG to the last state saved using
97647    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
97648    ** this verb acts like PRNG_RESET.
97649    */
97650    case SQLITE_TESTCTRL_PRNG_RESTORE: {
97651      sqlite3PrngRestoreState();
97652      break;
97653    }
97654
97655    /*
97656    ** Reset the PRNG back to its uninitialized state.  The next call
97657    ** to sqlite3_randomness() will reseed the PRNG using a single call
97658    ** to the xRandomness method of the default VFS.
97659    */
97660    case SQLITE_TESTCTRL_PRNG_RESET: {
97661      sqlite3PrngResetState();
97662      break;
97663    }
97664
97665    /*
97666    **  sqlite3_test_control(BITVEC_TEST, size, program)
97667    **
97668    ** Run a test against a Bitvec object of size.  The program argument
97669    ** is an array of integers that defines the test.  Return -1 on a
97670    ** memory allocation error, 0 on success, or non-zero for an error.
97671    ** See the sqlite3BitvecBuiltinTest() for additional information.
97672    */
97673    case SQLITE_TESTCTRL_BITVEC_TEST: {
97674      int sz = va_arg(ap, int);
97675      int *aProg = va_arg(ap, int*);
97676      rc = sqlite3BitvecBuiltinTest(sz, aProg);
97677      break;
97678    }
97679
97680    /*
97681    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
97682    **
97683    ** Register hooks to call to indicate which malloc() failures
97684    ** are benign.
97685    */
97686    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
97687      typedef void (*void_function)(void);
97688      void_function xBenignBegin;
97689      void_function xBenignEnd;
97690      xBenignBegin = va_arg(ap, void_function);
97691      xBenignEnd = va_arg(ap, void_function);
97692      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
97693      break;
97694    }
97695
97696    /*
97697    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
97698    **
97699    ** Set the PENDING byte to the value in the argument, if X>0.
97700    ** Make no changes if X==0.  Return the value of the pending byte
97701    ** as it existing before this routine was called.
97702    **
97703    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
97704    ** an incompatible database file format.  Changing the PENDING byte
97705    ** while any database connection is open results in undefined and
97706    ** dileterious behavior.
97707    */
97708    case SQLITE_TESTCTRL_PENDING_BYTE: {
97709      unsigned int newVal = va_arg(ap, unsigned int);
97710      rc = sqlite3PendingByte;
97711      if( newVal ) sqlite3PendingByte = newVal;
97712      break;
97713    }
97714
97715    /*
97716    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
97717    **
97718    ** This action provides a run-time test to see whether or not
97719    ** assert() was enabled at compile-time.  If X is true and assert()
97720    ** is enabled, then the return value is true.  If X is true and
97721    ** assert() is disabled, then the return value is zero.  If X is
97722    ** false and assert() is enabled, then the assertion fires and the
97723    ** process aborts.  If X is false and assert() is disabled, then the
97724    ** return value is zero.
97725    */
97726    case SQLITE_TESTCTRL_ASSERT: {
97727      volatile int x = 0;
97728      assert( (x = va_arg(ap,int))!=0 );
97729      rc = x;
97730      break;
97731    }
97732
97733
97734    /*
97735    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
97736    **
97737    ** This action provides a run-time test to see how the ALWAYS and
97738    ** NEVER macros were defined at compile-time.
97739    **
97740    ** The return value is ALWAYS(X).
97741    **
97742    ** The recommended test is X==2.  If the return value is 2, that means
97743    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
97744    ** default setting.  If the return value is 1, then ALWAYS() is either
97745    ** hard-coded to true or else it asserts if its argument is false.
97746    ** The first behavior (hard-coded to true) is the case if
97747    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
97748    ** behavior (assert if the argument to ALWAYS() is false) is the case if
97749    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
97750    **
97751    ** The run-time test procedure might look something like this:
97752    **
97753    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
97754    **      // ALWAYS() and NEVER() are no-op pass-through macros
97755    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
97756    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
97757    **    }else{
97758    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
97759    **    }
97760    */
97761    case SQLITE_TESTCTRL_ALWAYS: {
97762      int x = va_arg(ap,int);
97763      rc = ALWAYS(x);
97764      break;
97765    }
97766
97767    /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
97768    **
97769    ** Set the nReserve size to N for the main database on the database
97770    ** connection db.
97771    */
97772    case SQLITE_TESTCTRL_RESERVE: {
97773      sqlite3 *db = va_arg(ap, sqlite3*);
97774      int x = va_arg(ap,int);
97775      sqlite3_mutex_enter(db->mutex);
97776      sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
97777      sqlite3_mutex_leave(db->mutex);
97778      break;
97779    }
97780
97781    /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
97782    **
97783    ** Enable or disable various optimizations for testing purposes.  The
97784    ** argument N is a bitmask of optimizations to be disabled.  For normal
97785    ** operation N should be 0.  The idea is that a test program (like the
97786    ** SQL Logic Test or SLT test module) can run the same SQL multiple times
97787    ** with various optimizations disabled to verify that the same answer
97788    ** is obtained in every case.
97789    */
97790    case SQLITE_TESTCTRL_OPTIMIZATIONS: {
97791      sqlite3 *db = va_arg(ap, sqlite3*);
97792      int x = va_arg(ap,int);
97793      db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
97794      break;
97795    }
97796
97797#ifdef SQLITE_N_KEYWORD
97798    /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
97799    **
97800    ** If zWord is a keyword recognized by the parser, then return the
97801    ** number of keywords.  Or if zWord is not a keyword, return 0.
97802    **
97803    ** This test feature is only available in the amalgamation since
97804    ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
97805    ** is built using separate source files.
97806    */
97807    case SQLITE_TESTCTRL_ISKEYWORD: {
97808      const char *zWord = va_arg(ap, const char*);
97809      int n = sqlite3Strlen30(zWord);
97810      rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
97811      break;
97812    }
97813#endif
97814
97815  }
97816  va_end(ap);
97817#endif /* SQLITE_OMIT_BUILTIN_TEST */
97818  return rc;
97819}
97820
97821/************** End of main.c ************************************************/
97822/************** Begin file notify.c ******************************************/
97823/*
97824** 2009 March 3
97825**
97826** The author disclaims copyright to this source code.  In place of
97827** a legal notice, here is a blessing:
97828**
97829**    May you do good and not evil.
97830**    May you find forgiveness for yourself and forgive others.
97831**    May you share freely, never taking more than you give.
97832**
97833*************************************************************************
97834**
97835** This file contains the implementation of the sqlite3_unlock_notify()
97836** API method and its associated functionality.
97837*/
97838
97839/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
97840#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
97841
97842/*
97843** Public interfaces:
97844**
97845**   sqlite3ConnectionBlocked()
97846**   sqlite3ConnectionUnlocked()
97847**   sqlite3ConnectionClosed()
97848**   sqlite3_unlock_notify()
97849*/
97850
97851#define assertMutexHeld() \
97852  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
97853
97854/*
97855** Head of a linked list of all sqlite3 objects created by this process
97856** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
97857** is not NULL. This variable may only accessed while the STATIC_MASTER
97858** mutex is held.
97859*/
97860static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
97861
97862#ifndef NDEBUG
97863/*
97864** This function is a complex assert() that verifies the following
97865** properties of the blocked connections list:
97866**
97867**   1) Each entry in the list has a non-NULL value for either
97868**      pUnlockConnection or pBlockingConnection, or both.
97869**
97870**   2) All entries in the list that share a common value for
97871**      xUnlockNotify are grouped together.
97872**
97873**   3) If the argument db is not NULL, then none of the entries in the
97874**      blocked connections list have pUnlockConnection or pBlockingConnection
97875**      set to db. This is used when closing connection db.
97876*/
97877static void checkListProperties(sqlite3 *db){
97878  sqlite3 *p;
97879  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
97880    int seen = 0;
97881    sqlite3 *p2;
97882
97883    /* Verify property (1) */
97884    assert( p->pUnlockConnection || p->pBlockingConnection );
97885
97886    /* Verify property (2) */
97887    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
97888      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
97889      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
97890      assert( db==0 || p->pUnlockConnection!=db );
97891      assert( db==0 || p->pBlockingConnection!=db );
97892    }
97893  }
97894}
97895#else
97896# define checkListProperties(x)
97897#endif
97898
97899/*
97900** Remove connection db from the blocked connections list. If connection
97901** db is not currently a part of the list, this function is a no-op.
97902*/
97903static void removeFromBlockedList(sqlite3 *db){
97904  sqlite3 **pp;
97905  assertMutexHeld();
97906  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
97907    if( *pp==db ){
97908      *pp = (*pp)->pNextBlocked;
97909      break;
97910    }
97911  }
97912}
97913
97914/*
97915** Add connection db to the blocked connections list. It is assumed
97916** that it is not already a part of the list.
97917*/
97918static void addToBlockedList(sqlite3 *db){
97919  sqlite3 **pp;
97920  assertMutexHeld();
97921  for(
97922    pp=&sqlite3BlockedList;
97923    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
97924    pp=&(*pp)->pNextBlocked
97925  );
97926  db->pNextBlocked = *pp;
97927  *pp = db;
97928}
97929
97930/*
97931** Obtain the STATIC_MASTER mutex.
97932*/
97933static void enterMutex(void){
97934  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
97935  checkListProperties(0);
97936}
97937
97938/*
97939** Release the STATIC_MASTER mutex.
97940*/
97941static void leaveMutex(void){
97942  assertMutexHeld();
97943  checkListProperties(0);
97944  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
97945}
97946
97947/*
97948** Register an unlock-notify callback.
97949**
97950** This is called after connection "db" has attempted some operation
97951** but has received an SQLITE_LOCKED error because another connection
97952** (call it pOther) in the same process was busy using the same shared
97953** cache.  pOther is found by looking at db->pBlockingConnection.
97954**
97955** If there is no blocking connection, the callback is invoked immediately,
97956** before this routine returns.
97957**
97958** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
97959** a deadlock.
97960**
97961** Otherwise, make arrangements to invoke xNotify when pOther drops
97962** its locks.
97963**
97964** Each call to this routine overrides any prior callbacks registered
97965** on the same "db".  If xNotify==0 then any prior callbacks are immediately
97966** cancelled.
97967*/
97968SQLITE_API int sqlite3_unlock_notify(
97969  sqlite3 *db,
97970  void (*xNotify)(void **, int),
97971  void *pArg
97972){
97973  int rc = SQLITE_OK;
97974
97975  sqlite3_mutex_enter(db->mutex);
97976  enterMutex();
97977
97978  if( xNotify==0 ){
97979    removeFromBlockedList(db);
97980    db->pUnlockConnection = 0;
97981    db->xUnlockNotify = 0;
97982    db->pUnlockArg = 0;
97983  }else if( 0==db->pBlockingConnection ){
97984    /* The blocking transaction has been concluded. Or there never was a
97985    ** blocking transaction. In either case, invoke the notify callback
97986    ** immediately.
97987    */
97988    xNotify(&pArg, 1);
97989  }else{
97990    sqlite3 *p;
97991
97992    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
97993    if( p ){
97994      rc = SQLITE_LOCKED;              /* Deadlock detected. */
97995    }else{
97996      db->pUnlockConnection = db->pBlockingConnection;
97997      db->xUnlockNotify = xNotify;
97998      db->pUnlockArg = pArg;
97999      removeFromBlockedList(db);
98000      addToBlockedList(db);
98001    }
98002  }
98003
98004  leaveMutex();
98005  assert( !db->mallocFailed );
98006  sqlite3Error(db, rc, (rc?"database is deadlocked":0));
98007  sqlite3_mutex_leave(db->mutex);
98008  return rc;
98009}
98010
98011/*
98012** This function is called while stepping or preparing a statement
98013** associated with connection db. The operation will return SQLITE_LOCKED
98014** to the user because it requires a lock that will not be available
98015** until connection pBlocker concludes its current transaction.
98016*/
98017SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
98018  enterMutex();
98019  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
98020    addToBlockedList(db);
98021  }
98022  db->pBlockingConnection = pBlocker;
98023  leaveMutex();
98024}
98025
98026/*
98027** This function is called when
98028** the transaction opened by database db has just finished. Locks held
98029** by database connection db have been released.
98030**
98031** This function loops through each entry in the blocked connections
98032** list and does the following:
98033**
98034**   1) If the sqlite3.pBlockingConnection member of a list entry is
98035**      set to db, then set pBlockingConnection=0.
98036**
98037**   2) If the sqlite3.pUnlockConnection member of a list entry is
98038**      set to db, then invoke the configured unlock-notify callback and
98039**      set pUnlockConnection=0.
98040**
98041**   3) If the two steps above mean that pBlockingConnection==0 and
98042**      pUnlockConnection==0, remove the entry from the blocked connections
98043**      list.
98044*/
98045SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
98046  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
98047  int nArg = 0;                            /* Number of entries in aArg[] */
98048  sqlite3 **pp;                            /* Iterator variable */
98049  void **aArg;               /* Arguments to the unlock callback */
98050  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
98051  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
98052
98053  aArg = aStatic;
98054  enterMutex();         /* Enter STATIC_MASTER mutex */
98055
98056  /* This loop runs once for each entry in the blocked-connections list. */
98057  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
98058    sqlite3 *p = *pp;
98059
98060    /* Step 1. */
98061    if( p->pBlockingConnection==db ){
98062      p->pBlockingConnection = 0;
98063    }
98064
98065    /* Step 2. */
98066    if( p->pUnlockConnection==db ){
98067      assert( p->xUnlockNotify );
98068      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
98069        xUnlockNotify(aArg, nArg);
98070        nArg = 0;
98071      }
98072
98073      sqlite3BeginBenignMalloc();
98074      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
98075      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
98076      if( (!aDyn && nArg==(int)ArraySize(aStatic))
98077       || (aDyn && nArg==(int)(sqlite3DbMallocSize(db, aDyn)/sizeof(void*)))
98078      ){
98079        /* The aArg[] array needs to grow. */
98080        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
98081        if( pNew ){
98082          memcpy(pNew, aArg, nArg*sizeof(void *));
98083          sqlite3_free(aDyn);
98084          aDyn = aArg = pNew;
98085        }else{
98086          /* This occurs when the array of context pointers that need to
98087          ** be passed to the unlock-notify callback is larger than the
98088          ** aStatic[] array allocated on the stack and the attempt to
98089          ** allocate a larger array from the heap has failed.
98090          **
98091          ** This is a difficult situation to handle. Returning an error
98092          ** code to the caller is insufficient, as even if an error code
98093          ** is returned the transaction on connection db will still be
98094          ** closed and the unlock-notify callbacks on blocked connections
98095          ** will go unissued. This might cause the application to wait
98096          ** indefinitely for an unlock-notify callback that will never
98097          ** arrive.
98098          **
98099          ** Instead, invoke the unlock-notify callback with the context
98100          ** array already accumulated. We can then clear the array and
98101          ** begin accumulating any further context pointers without
98102          ** requiring any dynamic allocation. This is sub-optimal because
98103          ** it means that instead of one callback with a large array of
98104          ** context pointers the application will receive two or more
98105          ** callbacks with smaller arrays of context pointers, which will
98106          ** reduce the applications ability to prioritize multiple
98107          ** connections. But it is the best that can be done under the
98108          ** circumstances.
98109          */
98110          xUnlockNotify(aArg, nArg);
98111          nArg = 0;
98112        }
98113      }
98114      sqlite3EndBenignMalloc();
98115
98116      aArg[nArg++] = p->pUnlockArg;
98117      xUnlockNotify = p->xUnlockNotify;
98118      p->pUnlockConnection = 0;
98119      p->xUnlockNotify = 0;
98120      p->pUnlockArg = 0;
98121    }
98122
98123    /* Step 3. */
98124    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
98125      /* Remove connection p from the blocked connections list. */
98126      *pp = p->pNextBlocked;
98127      p->pNextBlocked = 0;
98128    }else{
98129      pp = &p->pNextBlocked;
98130    }
98131  }
98132
98133  if( nArg!=0 ){
98134    xUnlockNotify(aArg, nArg);
98135  }
98136  sqlite3_free(aDyn);
98137  leaveMutex();         /* Leave STATIC_MASTER mutex */
98138}
98139
98140/*
98141** This is called when the database connection passed as an argument is
98142** being closed. The connection is removed from the blocked list.
98143*/
98144SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
98145  sqlite3ConnectionUnlocked(db);
98146  enterMutex();
98147  removeFromBlockedList(db);
98148  checkListProperties(db);
98149  leaveMutex();
98150}
98151#endif
98152
98153/************** End of notify.c **********************************************/
98154/************** Begin file fts3.c ********************************************/
98155/*
98156** 2006 Oct 10
98157**
98158** The author disclaims copyright to this source code.  In place of
98159** a legal notice, here is a blessing:
98160**
98161**    May you do good and not evil.
98162**    May you find forgiveness for yourself and forgive others.
98163**    May you share freely, never taking more than you give.
98164**
98165******************************************************************************
98166**
98167** This is an SQLite module implementing full-text search.
98168*/
98169
98170/*
98171** The code in this file is only compiled if:
98172**
98173**     * The FTS3 module is being built as an extension
98174**       (in which case SQLITE_CORE is not defined), or
98175**
98176**     * The FTS3 module is being built into the core of
98177**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
98178*/
98179
98180/* TODO(shess) Consider exporting this comment to an HTML file or the
98181** wiki.
98182*/
98183/* The full-text index is stored in a series of b+tree (-like)
98184** structures called segments which map terms to doclists.  The
98185** structures are like b+trees in layout, but are constructed from the
98186** bottom up in optimal fashion and are not updatable.  Since trees
98187** are built from the bottom up, things will be described from the
98188** bottom up.
98189**
98190**
98191**** Varints ****
98192** The basic unit of encoding is a variable-length integer called a
98193** varint.  We encode variable-length integers in little-endian order
98194** using seven bits * per byte as follows:
98195**
98196** KEY:
98197**         A = 0xxxxxxx    7 bits of data and one flag bit
98198**         B = 1xxxxxxx    7 bits of data and one flag bit
98199**
98200**  7 bits - A
98201** 14 bits - BA
98202** 21 bits - BBA
98203** and so on.
98204**
98205** This is identical to how sqlite encodes varints (see util.c).
98206**
98207**
98208**** Document lists ****
98209** A doclist (document list) holds a docid-sorted list of hits for a
98210** given term.  Doclists hold docids, and can optionally associate
98211** token positions and offsets with docids.
98212**
98213** A DL_POSITIONS_OFFSETS doclist is stored like this:
98214**
98215** array {
98216**   varint docid;
98217**   array {                (position list for column 0)
98218**     varint position;     (delta from previous position plus POS_BASE)
98219**     varint startOffset;  (delta from previous startOffset)
98220**     varint endOffset;    (delta from startOffset)
98221**   }
98222**   array {
98223**     varint POS_COLUMN;   (marks start of position list for new column)
98224**     varint column;       (index of new column)
98225**     array {
98226**       varint position;   (delta from previous position plus POS_BASE)
98227**       varint startOffset;(delta from previous startOffset)
98228**       varint endOffset;  (delta from startOffset)
98229**     }
98230**   }
98231**   varint POS_END;        (marks end of positions for this document.
98232** }
98233**
98234** Here, array { X } means zero or more occurrences of X, adjacent in
98235** memory.  A "position" is an index of a token in the token stream
98236** generated by the tokenizer, while an "offset" is a byte offset,
98237** both based at 0.  Note that POS_END and POS_COLUMN occur in the
98238** same logical place as the position element, and act as sentinals
98239** ending a position list array.
98240**
98241** A DL_POSITIONS doclist omits the startOffset and endOffset
98242** information.  A DL_DOCIDS doclist omits both the position and
98243** offset information, becoming an array of varint-encoded docids.
98244**
98245** On-disk data is stored as type DL_DEFAULT, so we don't serialize
98246** the type.  Due to how deletion is implemented in the segmentation
98247** system, on-disk doclists MUST store at least positions.
98248**
98249**
98250**** Segment leaf nodes ****
98251** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
98252** nodes are written using LeafWriter, and read using LeafReader (to
98253** iterate through a single leaf node's data) and LeavesReader (to
98254** iterate through a segment's entire leaf layer).  Leaf nodes have
98255** the format:
98256**
98257** varint iHeight;             (height from leaf level, always 0)
98258** varint nTerm;               (length of first term)
98259** char pTerm[nTerm];          (content of first term)
98260** varint nDoclist;            (length of term's associated doclist)
98261** char pDoclist[nDoclist];    (content of doclist)
98262** array {
98263**                             (further terms are delta-encoded)
98264**   varint nPrefix;           (length of prefix shared with previous term)
98265**   varint nSuffix;           (length of unshared suffix)
98266**   char pTermSuffix[nSuffix];(unshared suffix of next term)
98267**   varint nDoclist;          (length of term's associated doclist)
98268**   char pDoclist[nDoclist];  (content of doclist)
98269** }
98270**
98271** Here, array { X } means zero or more occurrences of X, adjacent in
98272** memory.
98273**
98274** Leaf nodes are broken into blocks which are stored contiguously in
98275** the %_segments table in sorted order.  This means that when the end
98276** of a node is reached, the next term is in the node with the next
98277** greater node id.
98278**
98279** New data is spilled to a new leaf node when the current node
98280** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
98281** larger than STANDALONE_MIN (default 1024) is placed in a standalone
98282** node (a leaf node with a single term and doclist).  The goal of
98283** these settings is to pack together groups of small doclists while
98284** making it efficient to directly access large doclists.  The
98285** assumption is that large doclists represent terms which are more
98286** likely to be query targets.
98287**
98288** TODO(shess) It may be useful for blocking decisions to be more
98289** dynamic.  For instance, it may make more sense to have a 2.5k leaf
98290** node rather than splitting into 2k and .5k nodes.  My intuition is
98291** that this might extend through 2x or 4x the pagesize.
98292**
98293**
98294**** Segment interior nodes ****
98295** Segment interior nodes store blockids for subtree nodes and terms
98296** to describe what data is stored by the each subtree.  Interior
98297** nodes are written using InteriorWriter, and read using
98298** InteriorReader.  InteriorWriters are created as needed when
98299** SegmentWriter creates new leaf nodes, or when an interior node
98300** itself grows too big and must be split.  The format of interior
98301** nodes:
98302**
98303** varint iHeight;           (height from leaf level, always >0)
98304** varint iBlockid;          (block id of node's leftmost subtree)
98305** optional {
98306**   varint nTerm;           (length of first term)
98307**   char pTerm[nTerm];      (content of first term)
98308**   array {
98309**                                (further terms are delta-encoded)
98310**     varint nPrefix;            (length of shared prefix with previous term)
98311**     varint nSuffix;            (length of unshared suffix)
98312**     char pTermSuffix[nSuffix]; (unshared suffix of next term)
98313**   }
98314** }
98315**
98316** Here, optional { X } means an optional element, while array { X }
98317** means zero or more occurrences of X, adjacent in memory.
98318**
98319** An interior node encodes n terms separating n+1 subtrees.  The
98320** subtree blocks are contiguous, so only the first subtree's blockid
98321** is encoded.  The subtree at iBlockid will contain all terms less
98322** than the first term encoded (or all terms if no term is encoded).
98323** Otherwise, for terms greater than or equal to pTerm[i] but less
98324** than pTerm[i+1], the subtree for that term will be rooted at
98325** iBlockid+i.  Interior nodes only store enough term data to
98326** distinguish adjacent children (if the rightmost term of the left
98327** child is "something", and the leftmost term of the right child is
98328** "wicked", only "w" is stored).
98329**
98330** New data is spilled to a new interior node at the same height when
98331** the current node exceeds INTERIOR_MAX bytes (default 2048).
98332** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
98333** interior nodes and making the tree too skinny.  The interior nodes
98334** at a given height are naturally tracked by interior nodes at
98335** height+1, and so on.
98336**
98337**
98338**** Segment directory ****
98339** The segment directory in table %_segdir stores meta-information for
98340** merging and deleting segments, and also the root node of the
98341** segment's tree.
98342**
98343** The root node is the top node of the segment's tree after encoding
98344** the entire segment, restricted to ROOT_MAX bytes (default 1024).
98345** This could be either a leaf node or an interior node.  If the top
98346** node requires more than ROOT_MAX bytes, it is flushed to %_segments
98347** and a new root interior node is generated (which should always fit
98348** within ROOT_MAX because it only needs space for 2 varints, the
98349** height and the blockid of the previous root).
98350**
98351** The meta-information in the segment directory is:
98352**   level               - segment level (see below)
98353**   idx                 - index within level
98354**                       - (level,idx uniquely identify a segment)
98355**   start_block         - first leaf node
98356**   leaves_end_block    - last leaf node
98357**   end_block           - last block (including interior nodes)
98358**   root                - contents of root node
98359**
98360** If the root node is a leaf node, then start_block,
98361** leaves_end_block, and end_block are all 0.
98362**
98363**
98364**** Segment merging ****
98365** To amortize update costs, segments are grouped into levels and
98366** merged in batches.  Each increase in level represents exponentially
98367** more documents.
98368**
98369** New documents (actually, document updates) are tokenized and
98370** written individually (using LeafWriter) to a level 0 segment, with
98371** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
98372** level 0 segments are merged into a single level 1 segment.  Level 1
98373** is populated like level 0, and eventually MERGE_COUNT level 1
98374** segments are merged to a single level 2 segment (representing
98375** MERGE_COUNT^2 updates), and so on.
98376**
98377** A segment merge traverses all segments at a given level in
98378** parallel, performing a straightforward sorted merge.  Since segment
98379** leaf nodes are written in to the %_segments table in order, this
98380** merge traverses the underlying sqlite disk structures efficiently.
98381** After the merge, all segment blocks from the merged level are
98382** deleted.
98383**
98384** MERGE_COUNT controls how often we merge segments.  16 seems to be
98385** somewhat of a sweet spot for insertion performance.  32 and 64 show
98386** very similar performance numbers to 16 on insertion, though they're
98387** a tiny bit slower (perhaps due to more overhead in merge-time
98388** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
98389** 16, 2 about 66% slower than 16.
98390**
98391** At query time, high MERGE_COUNT increases the number of segments
98392** which need to be scanned and merged.  For instance, with 100k docs
98393** inserted:
98394**
98395**    MERGE_COUNT   segments
98396**       16           25
98397**        8           12
98398**        4           10
98399**        2            6
98400**
98401** This appears to have only a moderate impact on queries for very
98402** frequent terms (which are somewhat dominated by segment merge
98403** costs), and infrequent and non-existent terms still seem to be fast
98404** even with many segments.
98405**
98406** TODO(shess) That said, it would be nice to have a better query-side
98407** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
98408** optimizations to things like doclist merging will swing the sweet
98409** spot around.
98410**
98411**
98412**
98413**** Handling of deletions and updates ****
98414** Since we're using a segmented structure, with no docid-oriented
98415** index into the term index, we clearly cannot simply update the term
98416** index when a document is deleted or updated.  For deletions, we
98417** write an empty doclist (varint(docid) varint(POS_END)), for updates
98418** we simply write the new doclist.  Segment merges overwrite older
98419** data for a particular docid with newer data, so deletes or updates
98420** will eventually overtake the earlier data and knock it out.  The
98421** query logic likewise merges doclists so that newer data knocks out
98422** older data.
98423**
98424** TODO(shess) Provide a VACUUM type operation to clear out all
98425** deletions and duplications.  This would basically be a forced merge
98426** into a single segment.
98427*/
98428
98429#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
98430
98431#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
98432# define SQLITE_CORE 1
98433#endif
98434
98435/************** Include fts3Int.h in the middle of fts3.c ********************/
98436/************** Begin file fts3Int.h *****************************************/
98437/*
98438** 2009 Nov 12
98439**
98440** The author disclaims copyright to this source code.  In place of
98441** a legal notice, here is a blessing:
98442**
98443**    May you do good and not evil.
98444**    May you find forgiveness for yourself and forgive others.
98445**    May you share freely, never taking more than you give.
98446**
98447******************************************************************************
98448**
98449*/
98450
98451#ifndef _FTSINT_H
98452#define _FTSINT_H
98453
98454#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
98455# define NDEBUG 1
98456#endif
98457
98458/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
98459/************** Begin file fts3_tokenizer.h **********************************/
98460/*
98461** 2006 July 10
98462**
98463** The author disclaims copyright to this source code.
98464**
98465*************************************************************************
98466** Defines the interface to tokenizers used by fulltext-search.  There
98467** are three basic components:
98468**
98469** sqlite3_tokenizer_module is a singleton defining the tokenizer
98470** interface functions.  This is essentially the class structure for
98471** tokenizers.
98472**
98473** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
98474** including customization information defined at creation time.
98475**
98476** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
98477** tokens from a particular input.
98478*/
98479#ifndef _FTS3_TOKENIZER_H_
98480#define _FTS3_TOKENIZER_H_
98481
98482/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
98483** If tokenizers are to be allowed to call sqlite3_*() functions, then
98484** we will need a way to register the API consistently.
98485*/
98486
98487/*
98488** Structures used by the tokenizer interface. When a new tokenizer
98489** implementation is registered, the caller provides a pointer to
98490** an sqlite3_tokenizer_module containing pointers to the callback
98491** functions that make up an implementation.
98492**
98493** When an fts3 table is created, it passes any arguments passed to
98494** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
98495** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
98496** implementation. The xCreate() function in turn returns an
98497** sqlite3_tokenizer structure representing the specific tokenizer to
98498** be used for the fts3 table (customized by the tokenizer clause arguments).
98499**
98500** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
98501** method is called. It returns an sqlite3_tokenizer_cursor object
98502** that may be used to tokenize a specific input buffer based on
98503** the tokenization rules supplied by a specific sqlite3_tokenizer
98504** object.
98505*/
98506typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
98507typedef struct sqlite3_tokenizer sqlite3_tokenizer;
98508typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
98509
98510struct sqlite3_tokenizer_module {
98511
98512  /*
98513  ** Structure version. Should always be set to 0.
98514  */
98515  int iVersion;
98516
98517  /*
98518  ** Create a new tokenizer. The values in the argv[] array are the
98519  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
98520  ** TABLE statement that created the fts3 table. For example, if
98521  ** the following SQL is executed:
98522  **
98523  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
98524  **
98525  ** then argc is set to 2, and the argv[] array contains pointers
98526  ** to the strings "arg1" and "arg2".
98527  **
98528  ** This method should return either SQLITE_OK (0), or an SQLite error
98529  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
98530  ** to point at the newly created tokenizer structure. The generic
98531  ** sqlite3_tokenizer.pModule variable should not be initialised by
98532  ** this callback. The caller will do so.
98533  */
98534  int (*xCreate)(
98535    int argc,                           /* Size of argv array */
98536    const char *const*argv,             /* Tokenizer argument strings */
98537    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
98538  );
98539
98540  /*
98541  ** Destroy an existing tokenizer. The fts3 module calls this method
98542  ** exactly once for each successful call to xCreate().
98543  */
98544  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
98545
98546  /*
98547  ** Create a tokenizer cursor to tokenize an input buffer. The caller
98548  ** is responsible for ensuring that the input buffer remains valid
98549  ** until the cursor is closed (using the xClose() method).
98550  */
98551  int (*xOpen)(
98552    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
98553    const char *pInput, int nBytes,      /* Input buffer */
98554    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
98555  );
98556
98557  /*
98558  ** Destroy an existing tokenizer cursor. The fts3 module calls this
98559  ** method exactly once for each successful call to xOpen().
98560  */
98561  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
98562
98563  /*
98564  ** Retrieve the next token from the tokenizer cursor pCursor. This
98565  ** method should either return SQLITE_OK and set the values of the
98566  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
98567  ** the end of the buffer has been reached, or an SQLite error code.
98568  **
98569  ** *ppToken should be set to point at a buffer containing the
98570  ** normalized version of the token (i.e. after any case-folding and/or
98571  ** stemming has been performed). *pnBytes should be set to the length
98572  ** of this buffer in bytes. The input text that generated the token is
98573  ** identified by the byte offsets returned in *piStartOffset and
98574  ** *piEndOffset. *piStartOffset should be set to the index of the first
98575  ** byte of the token in the input buffer. *piEndOffset should be set
98576  ** to the index of the first byte just past the end of the token in
98577  ** the input buffer.
98578  **
98579  ** The buffer *ppToken is set to point at is managed by the tokenizer
98580  ** implementation. It is only required to be valid until the next call
98581  ** to xNext() or xClose().
98582  */
98583  /* TODO(shess) current implementation requires pInput to be
98584  ** nul-terminated.  This should either be fixed, or pInput/nBytes
98585  ** should be converted to zInput.
98586  */
98587  int (*xNext)(
98588    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
98589    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
98590    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
98591    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
98592    int *piPosition      /* OUT: Number of tokens returned before this one */
98593  );
98594};
98595
98596struct sqlite3_tokenizer {
98597  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
98598  /* Tokenizer implementations will typically add additional fields */
98599};
98600
98601struct sqlite3_tokenizer_cursor {
98602  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
98603  /* Tokenizer implementations will typically add additional fields */
98604};
98605
98606int fts3_global_term_cnt(int iTerm, int iCol);
98607int fts3_term_cnt(int iTerm, int iCol);
98608
98609
98610#endif /* _FTS3_TOKENIZER_H_ */
98611
98612/************** End of fts3_tokenizer.h **************************************/
98613/************** Continuing where we left off in fts3Int.h ********************/
98614/************** Include fts3_hash.h in the middle of fts3Int.h ***************/
98615/************** Begin file fts3_hash.h ***************************************/
98616/*
98617** 2001 September 22
98618**
98619** The author disclaims copyright to this source code.  In place of
98620** a legal notice, here is a blessing:
98621**
98622**    May you do good and not evil.
98623**    May you find forgiveness for yourself and forgive others.
98624**    May you share freely, never taking more than you give.
98625**
98626*************************************************************************
98627** This is the header file for the generic hash-table implemenation
98628** used in SQLite.  We've modified it slightly to serve as a standalone
98629** hash table implementation for the full-text indexing module.
98630**
98631*/
98632#ifndef _FTS3_HASH_H_
98633#define _FTS3_HASH_H_
98634
98635/* Forward declarations of structures. */
98636typedef struct Fts3Hash Fts3Hash;
98637typedef struct Fts3HashElem Fts3HashElem;
98638
98639/* A complete hash table is an instance of the following structure.
98640** The internals of this structure are intended to be opaque -- client
98641** code should not attempt to access or modify the fields of this structure
98642** directly.  Change this structure only by using the routines below.
98643** However, many of the "procedures" and "functions" for modifying and
98644** accessing this structure are really macros, so we can't really make
98645** this structure opaque.
98646*/
98647struct Fts3Hash {
98648  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
98649  char copyKey;           /* True if copy of key made on insert */
98650  int count;              /* Number of entries in this table */
98651  Fts3HashElem *first;    /* The first element of the array */
98652  int htsize;             /* Number of buckets in the hash table */
98653  struct _fts3ht {        /* the hash table */
98654    int count;               /* Number of entries with this hash */
98655    Fts3HashElem *chain;     /* Pointer to first entry with this hash */
98656  } *ht;
98657};
98658
98659/* Each element in the hash table is an instance of the following
98660** structure.  All elements are stored on a single doubly-linked list.
98661**
98662** Again, this structure is intended to be opaque, but it can't really
98663** be opaque because it is used by macros.
98664*/
98665struct Fts3HashElem {
98666  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
98667  void *data;                /* Data associated with this element */
98668  void *pKey; int nKey;      /* Key associated with this element */
98669};
98670
98671/*
98672** There are 2 different modes of operation for a hash table:
98673**
98674**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
98675**                           (including the null-terminator, if any).  Case
98676**                           is respected in comparisons.
98677**
98678**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
98679**                           memcmp() is used to compare keys.
98680**
98681** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
98682*/
98683#define FTS3_HASH_STRING    1
98684#define FTS3_HASH_BINARY    2
98685
98686/*
98687** Access routines.  To delete, insert a NULL pointer.
98688*/
98689SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
98690SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
98691SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
98692SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
98693SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
98694
98695/*
98696** Shorthand for the functions above
98697*/
98698#define fts3HashInit     sqlite3Fts3HashInit
98699#define fts3HashInsert   sqlite3Fts3HashInsert
98700#define fts3HashFind     sqlite3Fts3HashFind
98701#define fts3HashClear    sqlite3Fts3HashClear
98702#define fts3HashFindElem sqlite3Fts3HashFindElem
98703
98704/*
98705** Macros for looping over all elements of a hash table.  The idiom is
98706** like this:
98707**
98708**   Fts3Hash h;
98709**   Fts3HashElem *p;
98710**   ...
98711**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
98712**     SomeStructure *pData = fts3HashData(p);
98713**     // do something with pData
98714**   }
98715*/
98716#define fts3HashFirst(H)  ((H)->first)
98717#define fts3HashNext(E)   ((E)->next)
98718#define fts3HashData(E)   ((E)->data)
98719#define fts3HashKey(E)    ((E)->pKey)
98720#define fts3HashKeysize(E) ((E)->nKey)
98721
98722/*
98723** Number of entries in a hash table
98724*/
98725#define fts3HashCount(H)  ((H)->count)
98726
98727#endif /* _FTS3_HASH_H_ */
98728
98729/************** End of fts3_hash.h *******************************************/
98730/************** Continuing where we left off in fts3Int.h ********************/
98731
98732/*
98733** This constant controls how often segments are merged. Once there are
98734** FTS3_MERGE_COUNT segments of level N, they are merged into a single
98735** segment of level N+1.
98736*/
98737#define FTS3_MERGE_COUNT 16
98738
98739/*
98740** This is the maximum amount of data (in bytes) to store in the
98741** Fts3Table.pendingTerms hash table. Normally, the hash table is
98742** populated as documents are inserted/updated/deleted in a transaction
98743** and used to create a new segment when the transaction is committed.
98744** However if this limit is reached midway through a transaction, a new
98745** segment is created and the hash table cleared immediately.
98746*/
98747#define FTS3_MAX_PENDING_DATA (1*1024*1024)
98748
98749/*
98750** Macro to return the number of elements in an array. SQLite has a
98751** similar macro called ArraySize(). Use a different name to avoid
98752** a collision when building an amalgamation with built-in FTS3.
98753*/
98754#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
98755
98756/*
98757** Maximum length of a varint encoded integer. The varint format is different
98758** from that used by SQLite, so the maximum length is 10, not 9.
98759*/
98760#define FTS3_VARINT_MAX 10
98761
98762/*
98763** This section provides definitions to allow the
98764** FTS3 extension to be compiled outside of the
98765** amalgamation.
98766*/
98767#ifndef SQLITE_AMALGAMATION
98768/*
98769** Macros indicating that conditional expressions are always true or
98770** false.
98771*/
98772# define ALWAYS(x) (x)
98773# define NEVER(X)  (x)
98774/*
98775** Internal types used by SQLite.
98776*/
98777typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
98778typedef short int i16;            /* 2-byte (or larger) signed integer */
98779typedef unsigned int u32;         /* 4-byte unsigned integer */
98780typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
98781/*
98782** Macro used to suppress compiler warnings for unused parameters.
98783*/
98784#define UNUSED_PARAMETER(x) (void)(x)
98785#endif
98786
98787typedef struct Fts3Table Fts3Table;
98788typedef struct Fts3Cursor Fts3Cursor;
98789typedef struct Fts3Expr Fts3Expr;
98790typedef struct Fts3Phrase Fts3Phrase;
98791typedef struct Fts3SegReader Fts3SegReader;
98792typedef struct Fts3SegFilter Fts3SegFilter;
98793
98794/*
98795** A connection to a fulltext index is an instance of the following
98796** structure. The xCreate and xConnect methods create an instance
98797** of this structure and xDestroy and xDisconnect free that instance.
98798** All other methods receive a pointer to the structure as one of their
98799** arguments.
98800*/
98801struct Fts3Table {
98802  sqlite3_vtab base;              /* Base class used by SQLite core */
98803  sqlite3 *db;                    /* The database connection */
98804  const char *zDb;                /* logical database name */
98805  const char *zName;              /* virtual table name */
98806  int nColumn;                    /* number of named columns in virtual table */
98807  char **azColumn;                /* column names.  malloced */
98808  sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
98809
98810  /* Precompiled statements used by the implementation. Each of these
98811  ** statements is run and reset within a single virtual table API call.
98812  */
98813  sqlite3_stmt *aStmt[18];
98814
98815  /* Pointer to string containing the SQL:
98816  **
98817  ** "SELECT block FROM %_segments WHERE blockid BETWEEN ? AND ?
98818  **    ORDER BY blockid"
98819  */
98820  char *zSelectLeaves;
98821  int nLeavesStmt;                /* Valid statements in aLeavesStmt */
98822  int nLeavesTotal;               /* Total number of prepared leaves stmts */
98823  int nLeavesAlloc;               /* Allocated size of aLeavesStmt */
98824  sqlite3_stmt **aLeavesStmt;     /* Array of prepared zSelectLeaves stmts */
98825
98826  int nNodeSize;                  /* Soft limit for node size */
98827
98828  /* The following hash table is used to buffer pending index updates during
98829  ** transactions. Variable nPendingData estimates the memory size of the
98830  ** pending data, including hash table overhead, but not malloc overhead.
98831  ** When nPendingData exceeds nMaxPendingData, the buffer is flushed
98832  ** automatically. Variable iPrevDocid is the docid of the most recently
98833  ** inserted record.
98834  */
98835  int nMaxPendingData;
98836  int nPendingData;
98837  sqlite_int64 iPrevDocid;
98838  Fts3Hash pendingTerms;
98839};
98840
98841/*
98842** When the core wants to read from the virtual table, it creates a
98843** virtual table cursor (an instance of the following structure) using
98844** the xOpen method. Cursors are destroyed using the xClose method.
98845*/
98846struct Fts3Cursor {
98847  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
98848  i16 eSearch;                    /* Search strategy (see below) */
98849  u8 isEof;                       /* True if at End Of Results */
98850  u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
98851  sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
98852  Fts3Expr *pExpr;                /* Parsed MATCH query string */
98853  sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
98854  char *pNextId;                  /* Pointer into the body of aDoclist */
98855  char *aDoclist;                 /* List of docids for full-text queries */
98856  int nDoclist;                   /* Size of buffer at aDoclist */
98857  int isMatchinfoOk;              /* True when aMatchinfo[] matches iPrevId */
98858  u32 *aMatchinfo;
98859};
98860
98861/*
98862** The Fts3Cursor.eSearch member is always set to one of the following.
98863** Actualy, Fts3Cursor.eSearch can be greater than or equal to
98864** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
98865** of the column to be searched.  For example, in
98866**
98867**     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
98868**     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
98869**
98870** Because the LHS of the MATCH operator is 2nd column "b",
98871** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
98872** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
98873** indicating that all columns should be searched,
98874** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
98875*/
98876#define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
98877#define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
98878#define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
98879
98880/*
98881** A "phrase" is a sequence of one or more tokens that must match in
98882** sequence.  A single token is the base case and the most common case.
98883** For a sequence of tokens contained in "...", nToken will be the number
98884** of tokens in the string.
98885*/
98886struct Fts3Phrase {
98887  int nToken;                /* Number of tokens in the phrase */
98888  int iColumn;               /* Index of column this phrase must match */
98889  int isNot;                 /* Phrase prefixed by unary not (-) operator */
98890  struct PhraseToken {
98891    char *z;                 /* Text of the token */
98892    int n;                   /* Number of bytes in buffer pointed to by z */
98893    int isPrefix;            /* True if token ends in with a "*" character */
98894  } aToken[1];               /* One entry for each token in the phrase */
98895};
98896
98897/*
98898** A tree of these objects forms the RHS of a MATCH operator.
98899**
98900** If Fts3Expr.eType is either FTSQUERY_NEAR or FTSQUERY_PHRASE and isLoaded
98901** is true, then aDoclist points to a malloced buffer, size nDoclist bytes,
98902** containing the results of the NEAR or phrase query in FTS3 doclist
98903** format. As usual, the initial "Length" field found in doclists stored
98904** on disk is omitted from this buffer.
98905**
98906** Variable pCurrent always points to the start of a docid field within
98907** aDoclist. Since the doclist is usually scanned in docid order, this can
98908** be used to accelerate seeking to the required docid within the doclist.
98909*/
98910struct Fts3Expr {
98911  int eType;                 /* One of the FTSQUERY_XXX values defined below */
98912  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
98913  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
98914  Fts3Expr *pLeft;           /* Left operand */
98915  Fts3Expr *pRight;          /* Right operand */
98916  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
98917
98918  int isLoaded;              /* True if aDoclist/nDoclist are initialized. */
98919  char *aDoclist;            /* Buffer containing doclist */
98920  int nDoclist;              /* Size of aDoclist in bytes */
98921
98922  sqlite3_int64 iCurrent;
98923  char *pCurrent;
98924};
98925
98926/*
98927** Candidate values for Fts3Query.eType. Note that the order of the first
98928** four values is in order of precedence when parsing expressions. For
98929** example, the following:
98930**
98931**   "a OR b AND c NOT d NEAR e"
98932**
98933** is equivalent to:
98934**
98935**   "a OR (b AND (c NOT (d NEAR e)))"
98936*/
98937#define FTSQUERY_NEAR   1
98938#define FTSQUERY_NOT    2
98939#define FTSQUERY_AND    3
98940#define FTSQUERY_OR     4
98941#define FTSQUERY_PHRASE 5
98942
98943
98944/* fts3_init.c */
98945SQLITE_PRIVATE int sqlite3Fts3DeleteVtab(int, sqlite3_vtab *);
98946SQLITE_PRIVATE int sqlite3Fts3InitVtab(int, sqlite3*, void*, int, const char*const*,
98947                        sqlite3_vtab **, char **);
98948
98949/* fts3_write.c */
98950SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
98951SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
98952SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
98953SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
98954SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(Fts3Table *,int, sqlite3_int64,
98955  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
98956SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(Fts3Table*,const char*,int,int,Fts3SegReader**);
98957SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *, Fts3SegReader *);
98958SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
98959  Fts3Table *, Fts3SegReader **, int, Fts3SegFilter *,
98960  int (*)(Fts3Table *, void *, char *, int, char *, int),  void *
98961);
98962SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char const**, int*);
98963SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, sqlite3_stmt **);
98964
98965/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
98966#define FTS3_SEGMENT_REQUIRE_POS   0x00000001
98967#define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
98968#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
98969#define FTS3_SEGMENT_PREFIX        0x00000008
98970
98971/* Type passed as 4th argument to SegmentReaderIterate() */
98972struct Fts3SegFilter {
98973  const char *zTerm;
98974  int nTerm;
98975  int iCol;
98976  int flags;
98977};
98978
98979/* fts3.c */
98980SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
98981SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
98982SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
98983SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
98984SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
98985
98986SQLITE_PRIVATE char *sqlite3Fts3FindPositions(Fts3Expr *, sqlite3_int64, int);
98987SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *, Fts3Expr *);
98988
98989/* fts3_tokenizer.c */
98990SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
98991SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
98992SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash,
98993  const char *, sqlite3_tokenizer **, const char **, char **
98994);
98995
98996/* fts3_snippet.c */
98997SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
98998SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context*, Fts3Cursor*,
98999  const char *, const char *, const char *
99000);
99001SQLITE_PRIVATE void sqlite3Fts3Snippet2(sqlite3_context *, Fts3Cursor *, const char *,
99002  const char *, const char *, int, int
99003);
99004SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *);
99005
99006/* fts3_expr.c */
99007SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *,
99008  char **, int, int, const char *, int, Fts3Expr **
99009);
99010SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
99011#ifdef SQLITE_TEST
99012SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
99013#endif
99014
99015#endif /* _FTSINT_H */
99016
99017/************** End of fts3Int.h *********************************************/
99018/************** Continuing where we left off in fts3.c ***********************/
99019
99020
99021#ifndef SQLITE_CORE
99022  SQLITE_EXTENSION_INIT1
99023#endif
99024
99025/*
99026** Write a 64-bit variable-length integer to memory starting at p[0].
99027** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
99028** The number of bytes written is returned.
99029*/
99030SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
99031  unsigned char *q = (unsigned char *) p;
99032  sqlite_uint64 vu = v;
99033  do{
99034    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
99035    vu >>= 7;
99036  }while( vu!=0 );
99037  q[-1] &= 0x7f;  /* turn off high bit in final byte */
99038  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
99039  return (int) (q - (unsigned char *)p);
99040}
99041
99042/*
99043** Read a 64-bit variable-length integer from memory starting at p[0].
99044** Return the number of bytes read, or 0 on error.
99045** The value is stored in *v.
99046*/
99047SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
99048  const unsigned char *q = (const unsigned char *) p;
99049  sqlite_uint64 x = 0, y = 1;
99050  while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
99051    x += y * (*q++ & 0x7f);
99052    y <<= 7;
99053  }
99054  x += y * (*q++);
99055  *v = (sqlite_int64) x;
99056  return (int) (q - (unsigned char *)p);
99057}
99058
99059/*
99060** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
99061** 32-bit integer before it is returned.
99062*/
99063SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
99064 sqlite_int64 i;
99065 int ret = sqlite3Fts3GetVarint(p, &i);
99066 *pi = (int) i;
99067 return ret;
99068}
99069
99070/*
99071** Return the number of bytes required to store the value passed as the
99072** first argument in varint form.
99073*/
99074SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
99075  int i = 0;
99076  do{
99077    i++;
99078    v >>= 7;
99079  }while( v!=0 );
99080  return i;
99081}
99082
99083/*
99084** Convert an SQL-style quoted string into a normal string by removing
99085** the quote characters.  The conversion is done in-place.  If the
99086** input does not begin with a quote character, then this routine
99087** is a no-op.
99088**
99089** Examples:
99090**
99091**     "abc"   becomes   abc
99092**     'xyz'   becomes   xyz
99093**     [pqr]   becomes   pqr
99094**     `mno`   becomes   mno
99095**
99096*/
99097SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
99098  char quote;                     /* Quote character (if any ) */
99099
99100  quote = z[0];
99101  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
99102    int iIn = 1;                  /* Index of next byte to read from input */
99103    int iOut = 0;                 /* Index of next byte to write to output */
99104
99105    /* If the first byte was a '[', then the close-quote character is a ']' */
99106    if( quote=='[' ) quote = ']';
99107
99108    while( ALWAYS(z[iIn]) ){
99109      if( z[iIn]==quote ){
99110        if( z[iIn+1]!=quote ) break;
99111        z[iOut++] = quote;
99112        iIn += 2;
99113      }else{
99114        z[iOut++] = z[iIn++];
99115      }
99116    }
99117    z[iOut] = '\0';
99118  }
99119}
99120
99121static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
99122  sqlite3_int64 iVal;
99123  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
99124  *pVal += iVal;
99125}
99126
99127static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){
99128  if( *pp>=pEnd ){
99129    *pp = 0;
99130  }else{
99131    fts3GetDeltaVarint(pp, pVal);
99132  }
99133}
99134
99135/*
99136** The xDisconnect() virtual table method.
99137*/
99138static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
99139  Fts3Table *p = (Fts3Table *)pVtab;
99140  int i;
99141
99142  assert( p->nPendingData==0 );
99143
99144  /* Free any prepared statements held */
99145  for(i=0; i<SizeofArray(p->aStmt); i++){
99146    sqlite3_finalize(p->aStmt[i]);
99147  }
99148  for(i=0; i<p->nLeavesStmt; i++){
99149    sqlite3_finalize(p->aLeavesStmt[i]);
99150  }
99151  sqlite3_free(p->zSelectLeaves);
99152  sqlite3_free(p->aLeavesStmt);
99153
99154  /* Invoke the tokenizer destructor to free the tokenizer. */
99155  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
99156
99157  sqlite3_free(p);
99158  return SQLITE_OK;
99159}
99160
99161/*
99162** The xDestroy() virtual table method.
99163*/
99164static int fts3DestroyMethod(sqlite3_vtab *pVtab){
99165  int rc;                         /* Return code */
99166  Fts3Table *p = (Fts3Table *)pVtab;
99167
99168  /* Create a script to drop the underlying three storage tables. */
99169  char *zSql = sqlite3_mprintf(
99170      "DROP TABLE IF EXISTS %Q.'%q_content';"
99171      "DROP TABLE IF EXISTS %Q.'%q_segments';"
99172      "DROP TABLE IF EXISTS %Q.'%q_segdir';",
99173      p->zDb, p->zName, p->zDb, p->zName, p->zDb, p->zName
99174  );
99175
99176  /* If malloc has failed, set rc to SQLITE_NOMEM. Otherwise, try to
99177  ** execute the SQL script created above.
99178  */
99179  if( zSql ){
99180    rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
99181    sqlite3_free(zSql);
99182  }else{
99183    rc = SQLITE_NOMEM;
99184  }
99185
99186  /* If everything has worked, invoke fts3DisconnectMethod() to free the
99187  ** memory associated with the Fts3Table structure and return SQLITE_OK.
99188  ** Otherwise, return an SQLite error code.
99189  */
99190  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
99191}
99192
99193
99194/*
99195** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
99196** passed as the first argument. This is done as part of the xConnect()
99197** and xCreate() methods.
99198*/
99199static int fts3DeclareVtab(Fts3Table *p){
99200  int i;                          /* Iterator variable */
99201  int rc;                         /* Return code */
99202  char *zSql;                     /* SQL statement passed to declare_vtab() */
99203  char *zCols;                    /* List of user defined columns */
99204
99205  /* Create a list of user columns for the virtual table */
99206  zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
99207  for(i=1; zCols && i<p->nColumn; i++){
99208    zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
99209  }
99210
99211  /* Create the whole "CREATE TABLE" statement to pass to SQLite */
99212  zSql = sqlite3_mprintf(
99213      "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
99214  );
99215
99216  if( !zCols || !zSql ){
99217    rc = SQLITE_NOMEM;
99218  }else{
99219    rc = sqlite3_declare_vtab(p->db, zSql);
99220  }
99221
99222  sqlite3_free(zSql);
99223  sqlite3_free(zCols);
99224  return rc;
99225}
99226
99227/*
99228** Create the backing store tables (%_content, %_segments and %_segdir)
99229** required by the FTS3 table passed as the only argument. This is done
99230** as part of the vtab xCreate() method.
99231*/
99232static int fts3CreateTables(Fts3Table *p){
99233  int rc;                         /* Return code */
99234  int i;                          /* Iterator variable */
99235  char *zContentCols;             /* Columns of %_content table */
99236  char *zSql;                     /* SQL script to create required tables */
99237
99238  /* Create a list of user columns for the content table */
99239  zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
99240  for(i=0; zContentCols && i<p->nColumn; i++){
99241    char *z = p->azColumn[i];
99242    zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
99243  }
99244
99245  /* Create the whole SQL script */
99246  zSql = sqlite3_mprintf(
99247      "CREATE TABLE %Q.'%q_content'(%s);"
99248      "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);"
99249      "CREATE TABLE %Q.'%q_segdir'("
99250        "level INTEGER,"
99251        "idx INTEGER,"
99252        "start_block INTEGER,"
99253        "leaves_end_block INTEGER,"
99254        "end_block INTEGER,"
99255        "root BLOB,"
99256        "PRIMARY KEY(level, idx)"
99257      ");",
99258      p->zDb, p->zName, zContentCols, p->zDb, p->zName, p->zDb, p->zName
99259  );
99260
99261  /* Unless a malloc() failure has occurred, execute the SQL script to
99262  ** create the tables used to store data for this FTS3 virtual table.
99263  */
99264  if( zContentCols==0 || zSql==0 ){
99265    rc = SQLITE_NOMEM;
99266  }else{
99267    rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
99268  }
99269
99270  sqlite3_free(zSql);
99271  sqlite3_free(zContentCols);
99272  return rc;
99273}
99274
99275/*
99276** This function is the implementation of both the xConnect and xCreate
99277** methods of the FTS3 virtual table.
99278**
99279** The argv[] array contains the following:
99280**
99281**   argv[0]   -> module name
99282**   argv[1]   -> database name
99283**   argv[2]   -> table name
99284**   argv[...] -> "column name" and other module argument fields.
99285*/
99286static int fts3InitVtab(
99287  int isCreate,                   /* True for xCreate, false for xConnect */
99288  sqlite3 *db,                    /* The SQLite database connection */
99289  void *pAux,                     /* Hash table containing tokenizers */
99290  int argc,                       /* Number of elements in argv array */
99291  const char * const *argv,       /* xCreate/xConnect argument array */
99292  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
99293  char **pzErr                    /* Write any error message here */
99294){
99295  Fts3Hash *pHash = (Fts3Hash *)pAux;
99296  Fts3Table *p;                   /* Pointer to allocated vtab */
99297  int rc;                         /* Return code */
99298  int i;                          /* Iterator variable */
99299  int nByte;                      /* Size of allocation used for *p */
99300  int iCol;
99301  int nString = 0;
99302  int nCol = 0;
99303  char *zCsr;
99304  int nDb;
99305  int nName;
99306
99307  const char *zTokenizer = 0;               /* Name of tokenizer to use */
99308  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
99309
99310  nDb = (int)strlen(argv[1]) + 1;
99311  nName = (int)strlen(argv[2]) + 1;
99312  for(i=3; i<argc; i++){
99313    char const *z = argv[i];
99314    rc = sqlite3Fts3InitTokenizer(pHash, z, &pTokenizer, &zTokenizer, pzErr);
99315    if( rc!=SQLITE_OK ){
99316      return rc;
99317    }
99318    if( z!=zTokenizer ){
99319      nString += (int)(strlen(z) + 1);
99320    }
99321  }
99322  nCol = argc - 3 - (zTokenizer!=0);
99323  if( zTokenizer==0 ){
99324    rc = sqlite3Fts3InitTokenizer(pHash, 0, &pTokenizer, 0, pzErr);
99325    if( rc!=SQLITE_OK ){
99326      return rc;
99327    }
99328    assert( pTokenizer );
99329  }
99330
99331  if( nCol==0 ){
99332    nCol = 1;
99333  }
99334
99335  /* Allocate and populate the Fts3Table structure. */
99336  nByte = sizeof(Fts3Table) +              /* Fts3Table */
99337          nCol * sizeof(char *) +              /* azColumn */
99338          nName +                              /* zName */
99339          nDb +                                /* zDb */
99340          nString;                             /* Space for azColumn strings */
99341  p = (Fts3Table*)sqlite3_malloc(nByte);
99342  if( p==0 ){
99343    rc = SQLITE_NOMEM;
99344    goto fts3_init_out;
99345  }
99346  memset(p, 0, nByte);
99347
99348  p->db = db;
99349  p->nColumn = nCol;
99350  p->nPendingData = 0;
99351  p->azColumn = (char **)&p[1];
99352  p->pTokenizer = pTokenizer;
99353  p->nNodeSize = 1000;
99354  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
99355  zCsr = (char *)&p->azColumn[nCol];
99356
99357  fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1);
99358
99359  /* Fill in the zName and zDb fields of the vtab structure. */
99360  p->zName = zCsr;
99361  memcpy(zCsr, argv[2], nName);
99362  zCsr += nName;
99363  p->zDb = zCsr;
99364  memcpy(zCsr, argv[1], nDb);
99365  zCsr += nDb;
99366
99367  /* Fill in the azColumn array */
99368  iCol = 0;
99369  for(i=3; i<argc; i++){
99370    if( argv[i]!=zTokenizer ){
99371      char *z;
99372      int n;
99373      z = (char *)sqlite3Fts3NextToken(argv[i], &n);
99374      memcpy(zCsr, z, n);
99375      zCsr[n] = '\0';
99376      sqlite3Fts3Dequote(zCsr);
99377      p->azColumn[iCol++] = zCsr;
99378      zCsr += n+1;
99379      assert( zCsr <= &((char *)p)[nByte] );
99380    }
99381  }
99382  if( iCol==0 ){
99383    assert( nCol==1 );
99384    p->azColumn[0] = "content";
99385  }
99386
99387  /* If this is an xCreate call, create the underlying tables in the
99388  ** database. TODO: For xConnect(), it could verify that said tables exist.
99389  */
99390  if( isCreate ){
99391    rc = fts3CreateTables(p);
99392    if( rc!=SQLITE_OK ) goto fts3_init_out;
99393  }
99394
99395  rc = fts3DeclareVtab(p);
99396  if( rc!=SQLITE_OK ) goto fts3_init_out;
99397
99398  *ppVTab = &p->base;
99399
99400fts3_init_out:
99401  assert( p || (pTokenizer && rc!=SQLITE_OK) );
99402  if( rc!=SQLITE_OK ){
99403    if( p ){
99404      fts3DisconnectMethod((sqlite3_vtab *)p);
99405    }else{
99406      pTokenizer->pModule->xDestroy(pTokenizer);
99407    }
99408  }
99409  return rc;
99410}
99411
99412/*
99413** The xConnect() and xCreate() methods for the virtual table. All the
99414** work is done in function fts3InitVtab().
99415*/
99416static int fts3ConnectMethod(
99417  sqlite3 *db,                    /* Database connection */
99418  void *pAux,                     /* Pointer to tokenizer hash table */
99419  int argc,                       /* Number of elements in argv array */
99420  const char * const *argv,       /* xCreate/xConnect argument array */
99421  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
99422  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
99423){
99424  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
99425}
99426static int fts3CreateMethod(
99427  sqlite3 *db,                    /* Database connection */
99428  void *pAux,                     /* Pointer to tokenizer hash table */
99429  int argc,                       /* Number of elements in argv array */
99430  const char * const *argv,       /* xCreate/xConnect argument array */
99431  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
99432  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
99433){
99434  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
99435}
99436
99437/*
99438** Implementation of the xBestIndex method for FTS3 tables. There
99439** are three possible strategies, in order of preference:
99440**
99441**   1. Direct lookup by rowid or docid.
99442**   2. Full-text search using a MATCH operator on a non-docid column.
99443**   3. Linear scan of %_content table.
99444*/
99445static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
99446  Fts3Table *p = (Fts3Table *)pVTab;
99447  int i;                          /* Iterator variable */
99448  int iCons = -1;                 /* Index of constraint to use */
99449
99450  /* By default use a full table scan. This is an expensive option,
99451  ** so search through the constraints to see if a more efficient
99452  ** strategy is possible.
99453  */
99454  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
99455  pInfo->estimatedCost = 500000;
99456  for(i=0; i<pInfo->nConstraint; i++){
99457    struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
99458    if( pCons->usable==0 ) continue;
99459
99460    /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
99461    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
99462     && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
99463    ){
99464      pInfo->idxNum = FTS3_DOCID_SEARCH;
99465      pInfo->estimatedCost = 1.0;
99466      iCons = i;
99467    }
99468
99469    /* A MATCH constraint. Use a full-text search.
99470    **
99471    ** If there is more than one MATCH constraint available, use the first
99472    ** one encountered. If there is both a MATCH constraint and a direct
99473    ** rowid/docid lookup, prefer the MATCH strategy. This is done even
99474    ** though the rowid/docid lookup is faster than a MATCH query, selecting
99475    ** it would lead to an "unable to use function MATCH in the requested
99476    ** context" error.
99477    */
99478    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
99479     && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
99480    ){
99481      pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
99482      pInfo->estimatedCost = 2.0;
99483      iCons = i;
99484      break;
99485    }
99486  }
99487
99488  if( iCons>=0 ){
99489    pInfo->aConstraintUsage[iCons].argvIndex = 1;
99490    pInfo->aConstraintUsage[iCons].omit = 1;
99491  }
99492  return SQLITE_OK;
99493}
99494
99495/*
99496** Implementation of xOpen method.
99497*/
99498static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
99499  sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
99500
99501  UNUSED_PARAMETER(pVTab);
99502
99503  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
99504  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
99505  ** if the allocation fails, return SQLITE_NOMEM.
99506  */
99507  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
99508  if( !pCsr ){
99509    return SQLITE_NOMEM;
99510  }
99511  memset(pCsr, 0, sizeof(Fts3Cursor));
99512  return SQLITE_OK;
99513}
99514
99515/****************************************************************/
99516/****************************************************************/
99517/****************************************************************/
99518/****************************************************************/
99519
99520
99521/*
99522** Close the cursor.  For additional information see the documentation
99523** on the xClose method of the virtual table interface.
99524*/
99525static int fulltextClose(sqlite3_vtab_cursor *pCursor){
99526  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
99527  sqlite3_finalize(pCsr->pStmt);
99528  sqlite3Fts3ExprFree(pCsr->pExpr);
99529  sqlite3_free(pCsr->aDoclist);
99530  sqlite3_free(pCsr->aMatchinfo);
99531  sqlite3_free(pCsr);
99532  return SQLITE_OK;
99533}
99534
99535static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
99536  if( pCsr->isRequireSeek ){
99537    pCsr->isRequireSeek = 0;
99538    sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
99539    if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
99540      return SQLITE_OK;
99541    }else{
99542      int rc = sqlite3_reset(pCsr->pStmt);
99543      if( rc==SQLITE_OK ){
99544        /* If no row was found and no error has occured, then the %_content
99545        ** table is missing a row that is present in the full-text index.
99546        ** The data structures are corrupt.
99547        */
99548        rc = SQLITE_CORRUPT;
99549      }
99550      pCsr->isEof = 1;
99551      if( pContext ){
99552        sqlite3_result_error_code(pContext, rc);
99553      }
99554      return rc;
99555    }
99556  }else{
99557    return SQLITE_OK;
99558  }
99559}
99560
99561static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
99562  int rc = SQLITE_OK;             /* Return code */
99563  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
99564
99565  if( pCsr->aDoclist==0 ){
99566    if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
99567      pCsr->isEof = 1;
99568      rc = sqlite3_reset(pCsr->pStmt);
99569    }
99570  }else if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){
99571    pCsr->isEof = 1;
99572  }else{
99573    sqlite3_reset(pCsr->pStmt);
99574    fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId);
99575    pCsr->isRequireSeek = 1;
99576    pCsr->isMatchinfoOk = 1;
99577  }
99578  return rc;
99579}
99580
99581
99582/*
99583** The buffer pointed to by argument zNode (size nNode bytes) contains the
99584** root node of a b-tree segment. The segment is guaranteed to be at least
99585** one level high (i.e. the root node is not also a leaf). If successful,
99586** this function locates the leaf node of the segment that may contain the
99587** term specified by arguments zTerm and nTerm and writes its block number
99588** to *piLeaf.
99589**
99590** It is possible that the returned leaf node does not contain the specified
99591** term. However, if the segment does contain said term, it is stored on
99592** the identified leaf node. Because this function only inspects interior
99593** segment nodes (and never loads leaf nodes into memory), it is not possible
99594** to be sure.
99595**
99596** If an error occurs, an error code other than SQLITE_OK is returned.
99597*/
99598static int fts3SelectLeaf(
99599  Fts3Table *p,                   /* Virtual table handle */
99600  const char *zTerm,              /* Term to select leaves for */
99601  int nTerm,                      /* Size of term zTerm in bytes */
99602  const char *zNode,              /* Buffer containing segment interior node */
99603  int nNode,                      /* Size of buffer at zNode */
99604  sqlite3_int64 *piLeaf           /* Selected leaf node */
99605){
99606  int rc = SQLITE_OK;             /* Return code */
99607  const char *zCsr = zNode;       /* Cursor to iterate through node */
99608  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
99609  char *zBuffer = 0;              /* Buffer to load terms into */
99610  int nAlloc = 0;                 /* Size of allocated buffer */
99611
99612  while( 1 ){
99613    int isFirstTerm = 1;          /* True when processing first term on page */
99614    int iHeight;                  /* Height of this node in tree */
99615    sqlite3_int64 iChild;         /* Block id of child node to descend to */
99616    int nBlock;                   /* Size of child node in bytes */
99617
99618    zCsr += sqlite3Fts3GetVarint32(zCsr, &iHeight);
99619    zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
99620
99621    while( zCsr<zEnd ){
99622      int cmp;                    /* memcmp() result */
99623      int nSuffix;                /* Size of term suffix */
99624      int nPrefix = 0;            /* Size of term prefix */
99625      int nBuffer;                /* Total term size */
99626
99627      /* Load the next term on the node into zBuffer */
99628      if( !isFirstTerm ){
99629        zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
99630      }
99631      isFirstTerm = 0;
99632      zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
99633      if( nPrefix+nSuffix>nAlloc ){
99634        char *zNew;
99635        nAlloc = (nPrefix+nSuffix) * 2;
99636        zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
99637        if( !zNew ){
99638          sqlite3_free(zBuffer);
99639          return SQLITE_NOMEM;
99640        }
99641        zBuffer = zNew;
99642      }
99643      memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
99644      nBuffer = nPrefix + nSuffix;
99645      zCsr += nSuffix;
99646
99647      /* Compare the term we are searching for with the term just loaded from
99648      ** the interior node. If the specified term is greater than or equal
99649      ** to the term from the interior node, then all terms on the sub-tree
99650      ** headed by node iChild are smaller than zTerm. No need to search
99651      ** iChild.
99652      **
99653      ** If the interior node term is larger than the specified term, then
99654      ** the tree headed by iChild may contain the specified term.
99655      */
99656      cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
99657      if( cmp<0 || (cmp==0 && nBuffer>nTerm) ) break;
99658      iChild++;
99659    };
99660
99661    /* If (iHeight==1), the children of this interior node are leaves. The
99662    ** specified term may be present on leaf node iChild.
99663    */
99664    if( iHeight==1 ){
99665      *piLeaf = iChild;
99666      break;
99667    }
99668
99669    /* Descend to interior node iChild. */
99670    rc = sqlite3Fts3ReadBlock(p, iChild, &zCsr, &nBlock);
99671    if( rc!=SQLITE_OK ) break;
99672    zEnd = &zCsr[nBlock];
99673  }
99674  sqlite3_free(zBuffer);
99675  return rc;
99676}
99677
99678/*
99679** This function is used to create delta-encoded serialized lists of FTS3
99680** varints. Each call to this function appends a single varint to a list.
99681*/
99682static void fts3PutDeltaVarint(
99683  char **pp,                      /* IN/OUT: Output pointer */
99684  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
99685  sqlite3_int64 iVal              /* Write this value to the list */
99686){
99687  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
99688  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
99689  *piPrev = iVal;
99690}
99691
99692/*
99693** When this function is called, *ppPoslist is assumed to point to the
99694** start of a position-list.
99695*/
99696static void fts3PoslistCopy(char **pp, char **ppPoslist){
99697  char *pEnd = *ppPoslist;
99698  char c = 0;
99699
99700  /* The end of a position list is marked by a zero encoded as an FTS3
99701  ** varint. A single 0x00 byte. Except, if the 0x00 byte is preceded by
99702  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
99703  ** of some other, multi-byte, value.
99704  **
99705  ** The following block moves pEnd to point to the first byte that is not
99706  ** immediately preceded by a byte with the 0x80 bit set. Then increments
99707  ** pEnd once more so that it points to the byte immediately following the
99708  ** last byte in the position-list.
99709  */
99710  while( *pEnd | c ) c = *pEnd++ & 0x80;
99711  pEnd++;
99712
99713  if( pp ){
99714    int n = (int)(pEnd - *ppPoslist);
99715    char *p = *pp;
99716    memcpy(p, *ppPoslist, n);
99717    p += n;
99718    *pp = p;
99719  }
99720  *ppPoslist = pEnd;
99721}
99722
99723static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
99724  char *pEnd = *ppPoslist;
99725  char c = 0;
99726
99727  /* A column-list is terminated by either a 0x01 or 0x00. */
99728  while( 0xFE & (*pEnd | c) ) c = *pEnd++ & 0x80;
99729  if( pp ){
99730    int n = (int)(pEnd - *ppPoslist);
99731    char *p = *pp;
99732    memcpy(p, *ppPoslist, n);
99733    p += n;
99734    *pp = p;
99735  }
99736  *ppPoslist = pEnd;
99737}
99738
99739/*
99740** Value used to signify the end of an offset-list. This is safe because
99741** it is not possible to have a document with 2^31 terms.
99742*/
99743#define OFFSET_LIST_END 0x7fffffff
99744
99745/*
99746** This function is used to help parse offset-lists. When this function is
99747** called, *pp may point to the start of the next varint in the offset-list
99748** being parsed, or it may point to 1 byte past the end of the offset-list
99749** (in which case **pp will be 0x00 or 0x01).
99750**
99751** If *pp points past the end of the current offset list, set *pi to
99752** OFFSET_LIST_END and return. Otherwise, read the next varint from *pp,
99753** increment the current value of *pi by the value read, and set *pp to
99754** point to the next value before returning.
99755*/
99756static void fts3ReadNextPos(
99757  char **pp,                      /* IN/OUT: Pointer into offset-list buffer */
99758  sqlite3_int64 *pi               /* IN/OUT: Value read from offset-list */
99759){
99760  if( **pp&0xFE ){
99761    fts3GetDeltaVarint(pp, pi);
99762    *pi -= 2;
99763  }else{
99764    *pi = OFFSET_LIST_END;
99765  }
99766}
99767
99768/*
99769** If parameter iCol is not 0, write an 0x01 byte followed by the value of
99770** iCol encoded as a varint to *pp.
99771**
99772** Set *pp to point to the byte just after the last byte written before
99773** returning (do not modify it if iCol==0). Return the total number of bytes
99774** written (0 if iCol==0).
99775*/
99776static int fts3PutColNumber(char **pp, int iCol){
99777  int n = 0;                      /* Number of bytes written */
99778  if( iCol ){
99779    char *p = *pp;                /* Output pointer */
99780    n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
99781    *p = 0x01;
99782    *pp = &p[n];
99783  }
99784  return n;
99785}
99786
99787/*
99788**
99789*/
99790static void fts3PoslistMerge(
99791  char **pp,                      /* Output buffer */
99792  char **pp1,                     /* Left input list */
99793  char **pp2                      /* Right input list */
99794){
99795  char *p = *pp;
99796  char *p1 = *pp1;
99797  char *p2 = *pp2;
99798
99799  while( *p1 || *p2 ){
99800    int iCol1;
99801    int iCol2;
99802
99803    if( *p1==0x01 ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
99804    else if( *p1==0x00 ) iCol1 = OFFSET_LIST_END;
99805    else iCol1 = 0;
99806
99807    if( *p2==0x01 ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
99808    else if( *p2==0x00 ) iCol2 = OFFSET_LIST_END;
99809    else iCol2 = 0;
99810
99811    if( iCol1==iCol2 ){
99812      sqlite3_int64 i1 = 0;
99813      sqlite3_int64 i2 = 0;
99814      sqlite3_int64 iPrev = 0;
99815      int n = fts3PutColNumber(&p, iCol1);
99816      p1 += n;
99817      p2 += n;
99818
99819      /* At this point, both p1 and p2 point to the start of offset-lists.
99820      ** An offset-list is a list of non-negative delta-encoded varints, each
99821      ** incremented by 2 before being stored. Each list is terminated by a 0
99822      ** or 1 value (0x00 or 0x01). The following block merges the two lists
99823      ** and writes the results to buffer p. p is left pointing to the byte
99824      ** after the list written. No terminator (0x00 or 0x01) is written to
99825      ** the output.
99826      */
99827      fts3GetDeltaVarint(&p1, &i1);
99828      fts3GetDeltaVarint(&p2, &i2);
99829      do {
99830        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
99831        iPrev -= 2;
99832        if( i1==i2 ){
99833          fts3ReadNextPos(&p1, &i1);
99834          fts3ReadNextPos(&p2, &i2);
99835        }else if( i1<i2 ){
99836          fts3ReadNextPos(&p1, &i1);
99837        }else{
99838          fts3ReadNextPos(&p2, &i2);
99839        }
99840      }while( i1!=OFFSET_LIST_END || i2!=OFFSET_LIST_END );
99841    }else if( iCol1<iCol2 ){
99842      p1 += fts3PutColNumber(&p, iCol1);
99843      fts3ColumnlistCopy(&p, &p1);
99844    }else{
99845      p2 += fts3PutColNumber(&p, iCol2);
99846      fts3ColumnlistCopy(&p, &p2);
99847    }
99848  }
99849
99850  *p++ = '\0';
99851  *pp = p;
99852  *pp1 = p1 + 1;
99853  *pp2 = p2 + 1;
99854}
99855
99856/*
99857** nToken==1 searches for adjacent positions.
99858*/
99859static int fts3PoslistPhraseMerge(
99860  char **pp,                      /* Output buffer */
99861  int nToken,                     /* Maximum difference in token positions */
99862  int isSaveLeft,                 /* Save the left position */
99863  char **pp1,                     /* Left input list */
99864  char **pp2                      /* Right input list */
99865){
99866  char *p = (pp ? *pp : 0);
99867  char *p1 = *pp1;
99868  char *p2 = *pp2;
99869
99870  int iCol1 = 0;
99871  int iCol2 = 0;
99872  assert( *p1!=0 && *p2!=0 );
99873  if( *p1==0x01 ){
99874    p1++;
99875    p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
99876  }
99877  if( *p2==0x01 ){
99878    p2++;
99879    p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
99880  }
99881
99882  while( 1 ){
99883    if( iCol1==iCol2 ){
99884      char *pSave = p;
99885      sqlite3_int64 iPrev = 0;
99886      sqlite3_int64 iPos1 = 0;
99887      sqlite3_int64 iPos2 = 0;
99888
99889      if( pp && iCol1 ){
99890        *p++ = 0x01;
99891        p += sqlite3Fts3PutVarint(p, iCol1);
99892      }
99893
99894      assert( *p1!=0x00 && *p2!=0x00 && *p1!=0x01 && *p2!=0x01 );
99895      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
99896      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
99897
99898      while( 1 ){
99899        if( iPos2>iPos1 && iPos2<=iPos1+nToken ){
99900          sqlite3_int64 iSave;
99901          if( !pp ){
99902            fts3PoslistCopy(0, &p2);
99903            fts3PoslistCopy(0, &p1);
99904            *pp1 = p1;
99905            *pp2 = p2;
99906            return 1;
99907          }
99908          iSave = isSaveLeft ? iPos1 : iPos2;
99909          fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
99910          pSave = 0;
99911        }
99912        if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
99913          if( (*p2&0xFE)==0 ) break;
99914          fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
99915        }else{
99916          if( (*p1&0xFE)==0 ) break;
99917          fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
99918        }
99919      }
99920
99921      if( pSave ){
99922        assert( pp && p );
99923        p = pSave;
99924      }
99925
99926      fts3ColumnlistCopy(0, &p1);
99927      fts3ColumnlistCopy(0, &p2);
99928      assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
99929      if( 0==*p1 || 0==*p2 ) break;
99930
99931      p1++;
99932      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
99933      p2++;
99934      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
99935    }
99936
99937    /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
99938    ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
99939    ** end of the position list, or the 0x01 that precedes the next
99940    ** column-number in the position list.
99941    */
99942    else if( iCol1<iCol2 ){
99943      fts3ColumnlistCopy(0, &p1);
99944      if( 0==*p1 ) break;
99945      p1++;
99946      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
99947    }else{
99948      fts3ColumnlistCopy(0, &p2);
99949      if( 0==*p2 ) break;
99950      p2++;
99951      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
99952    }
99953  }
99954
99955  fts3PoslistCopy(0, &p2);
99956  fts3PoslistCopy(0, &p1);
99957  *pp1 = p1;
99958  *pp2 = p2;
99959  if( !pp || *pp==p ){
99960    return 0;
99961  }
99962  *p++ = 0x00;
99963  *pp = p;
99964  return 1;
99965}
99966
99967/*
99968** Merge two position-lists as required by the NEAR operator.
99969*/
99970static int fts3PoslistNearMerge(
99971  char **pp,                      /* Output buffer */
99972  char *aTmp,                     /* Temporary buffer space */
99973  int nRight,                     /* Maximum difference in token positions */
99974  int nLeft,                      /* Maximum difference in token positions */
99975  char **pp1,                     /* IN/OUT: Left input list */
99976  char **pp2                      /* IN/OUT: Right input list */
99977){
99978  char *p1 = *pp1;
99979  char *p2 = *pp2;
99980
99981  if( !pp ){
99982    if( fts3PoslistPhraseMerge(0, nRight, 0, pp1, pp2) ) return 1;
99983    *pp1 = p1;
99984    *pp2 = p2;
99985    return fts3PoslistPhraseMerge(0, nLeft, 0, pp2, pp1);
99986  }else{
99987    char *pTmp1 = aTmp;
99988    char *pTmp2;
99989    char *aTmp2;
99990    int res = 1;
99991
99992    fts3PoslistPhraseMerge(&pTmp1, nRight, 0, pp1, pp2);
99993    aTmp2 = pTmp2 = pTmp1;
99994    *pp1 = p1;
99995    *pp2 = p2;
99996    fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, pp2, pp1);
99997    if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
99998      fts3PoslistMerge(pp, &aTmp, &aTmp2);
99999    }else if( pTmp1!=aTmp ){
100000      fts3PoslistCopy(pp, &aTmp);
100001    }else if( pTmp2!=aTmp2 ){
100002      fts3PoslistCopy(pp, &aTmp2);
100003    }else{
100004      res = 0;
100005    }
100006
100007    return res;
100008  }
100009}
100010
100011/*
100012** Values that may be used as the first parameter to fts3DoclistMerge().
100013*/
100014#define MERGE_NOT        2        /* D + D -> D */
100015#define MERGE_AND        3        /* D + D -> D */
100016#define MERGE_OR         4        /* D + D -> D */
100017#define MERGE_POS_OR     5        /* P + P -> P */
100018#define MERGE_PHRASE     6        /* P + P -> D */
100019#define MERGE_POS_PHRASE 7        /* P + P -> P */
100020#define MERGE_NEAR       8        /* P + P -> D */
100021#define MERGE_POS_NEAR   9        /* P + P -> P */
100022
100023/*
100024** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2
100025** (size n2 bytes). The output is written to pre-allocated buffer aBuffer,
100026** which is guaranteed to be large enough to hold the results. The number
100027** of bytes written to aBuffer is stored in *pnBuffer before returning.
100028**
100029** If successful, SQLITE_OK is returned. Otherwise, if a malloc error
100030** occurs while allocating a temporary buffer as part of the merge operation,
100031** SQLITE_NOMEM is returned.
100032*/
100033static int fts3DoclistMerge(
100034  int mergetype,                  /* One of the MERGE_XXX constants */
100035  int nParam1,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
100036  int nParam2,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
100037  char *aBuffer,                  /* Pre-allocated output buffer */
100038  int *pnBuffer,                  /* OUT: Bytes written to aBuffer */
100039  char *a1,                       /* Buffer containing first doclist */
100040  int n1,                         /* Size of buffer a1 */
100041  char *a2,                       /* Buffer containing second doclist */
100042  int n2                          /* Size of buffer a2 */
100043){
100044  sqlite3_int64 i1 = 0;
100045  sqlite3_int64 i2 = 0;
100046  sqlite3_int64 iPrev = 0;
100047
100048  char *p = aBuffer;
100049  char *p1 = a1;
100050  char *p2 = a2;
100051  char *pEnd1 = &a1[n1];
100052  char *pEnd2 = &a2[n2];
100053
100054  assert( mergetype==MERGE_OR     || mergetype==MERGE_POS_OR
100055       || mergetype==MERGE_AND    || mergetype==MERGE_NOT
100056       || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE
100057       || mergetype==MERGE_NEAR   || mergetype==MERGE_POS_NEAR
100058  );
100059
100060  if( !aBuffer ){
100061    *pnBuffer = 0;
100062    return SQLITE_NOMEM;
100063  }
100064
100065  /* Read the first docid from each doclist */
100066  fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100067  fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100068
100069  switch( mergetype ){
100070    case MERGE_OR:
100071    case MERGE_POS_OR:
100072      while( p1 || p2 ){
100073        if( p2 && p1 && i1==i2 ){
100074          fts3PutDeltaVarint(&p, &iPrev, i1);
100075          if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2);
100076          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100077          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100078        }else if( !p2 || (p1 && i1<i2) ){
100079          fts3PutDeltaVarint(&p, &iPrev, i1);
100080          if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1);
100081          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100082        }else{
100083          fts3PutDeltaVarint(&p, &iPrev, i2);
100084          if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2);
100085          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100086        }
100087      }
100088      break;
100089
100090    case MERGE_AND:
100091      while( p1 && p2 ){
100092        if( i1==i2 ){
100093          fts3PutDeltaVarint(&p, &iPrev, i1);
100094          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100095          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100096        }else if( i1<i2 ){
100097          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100098        }else{
100099          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100100        }
100101      }
100102      break;
100103
100104    case MERGE_NOT:
100105      while( p1 ){
100106        if( p2 && i1==i2 ){
100107          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100108          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100109        }else if( !p2 || i1<i2 ){
100110          fts3PutDeltaVarint(&p, &iPrev, i1);
100111          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100112        }else{
100113          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100114        }
100115      }
100116      break;
100117
100118    case MERGE_POS_PHRASE:
100119    case MERGE_PHRASE: {
100120      char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p);
100121      while( p1 && p2 ){
100122        if( i1==i2 ){
100123          char *pSave = p;
100124          sqlite3_int64 iPrevSave = iPrev;
100125          fts3PutDeltaVarint(&p, &iPrev, i1);
100126          if( 0==fts3PoslistPhraseMerge(ppPos, 1, 0, &p1, &p2) ){
100127            p = pSave;
100128            iPrev = iPrevSave;
100129          }
100130          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100131          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100132        }else if( i1<i2 ){
100133          fts3PoslistCopy(0, &p1);
100134          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100135        }else{
100136          fts3PoslistCopy(0, &p2);
100137          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100138        }
100139      }
100140      break;
100141    }
100142
100143    default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
100144      char *aTmp = 0;
100145      char **ppPos = 0;
100146      if( mergetype==MERGE_POS_NEAR ){
100147        ppPos = &p;
100148        aTmp = sqlite3_malloc(2*(n1+n2+1));
100149        if( !aTmp ){
100150          return SQLITE_NOMEM;
100151        }
100152      }
100153
100154      while( p1 && p2 ){
100155        if( i1==i2 ){
100156          char *pSave = p;
100157          sqlite3_int64 iPrevSave = iPrev;
100158          fts3PutDeltaVarint(&p, &iPrev, i1);
100159
100160          if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){
100161            iPrev = iPrevSave;
100162            p = pSave;
100163          }
100164
100165          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100166          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100167        }else if( i1<i2 ){
100168          fts3PoslistCopy(0, &p1);
100169          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100170        }else{
100171          fts3PoslistCopy(0, &p2);
100172          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100173        }
100174      }
100175      sqlite3_free(aTmp);
100176      break;
100177    }
100178  }
100179
100180  *pnBuffer = (int)(p-aBuffer);
100181  return SQLITE_OK;
100182}
100183
100184/*
100185** A pointer to an instance of this structure is used as the context
100186** argument to sqlite3Fts3SegReaderIterate()
100187*/
100188typedef struct TermSelect TermSelect;
100189struct TermSelect {
100190  int isReqPos;
100191  char *aOutput;                  /* Malloc'd output buffer */
100192  int nOutput;                    /* Size of output in bytes */
100193};
100194
100195/*
100196** This function is used as the sqlite3Fts3SegReaderIterate() callback when
100197** querying the full-text index for a doclist associated with a term or
100198** term-prefix.
100199*/
100200static int fts3TermSelectCb(
100201  Fts3Table *p,                   /* Virtual table object */
100202  void *pContext,                 /* Pointer to TermSelect structure */
100203  char *zTerm,
100204  int nTerm,
100205  char *aDoclist,
100206  int nDoclist
100207){
100208  TermSelect *pTS = (TermSelect *)pContext;
100209  int nNew = pTS->nOutput + nDoclist;
100210  char *aNew = sqlite3_malloc(nNew);
100211
100212  UNUSED_PARAMETER(p);
100213  UNUSED_PARAMETER(zTerm);
100214  UNUSED_PARAMETER(nTerm);
100215
100216  if( !aNew ){
100217    return SQLITE_NOMEM;
100218  }
100219
100220  if( pTS->nOutput==0 ){
100221    /* If this is the first term selected, copy the doclist to the output
100222    ** buffer using memcpy(). TODO: Add a way to transfer control of the
100223    ** aDoclist buffer from the caller so as to avoid the memcpy().
100224    */
100225    memcpy(aNew, aDoclist, nDoclist);
100226  }else{
100227    /* The output buffer is not empty. Merge doclist aDoclist with the
100228    ** existing output. This can only happen with prefix-searches (as
100229    ** searches for exact terms return exactly one doclist).
100230    */
100231    int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
100232    fts3DoclistMerge(mergetype, 0, 0,
100233        aNew, &nNew, pTS->aOutput, pTS->nOutput, aDoclist, nDoclist
100234    );
100235  }
100236
100237  sqlite3_free(pTS->aOutput);
100238  pTS->aOutput = aNew;
100239  pTS->nOutput = nNew;
100240
100241  return SQLITE_OK;
100242}
100243
100244/*
100245** This function retreives the doclist for the specified term (or term
100246** prefix) from the database.
100247**
100248** The returned doclist may be in one of two formats, depending on the
100249** value of parameter isReqPos. If isReqPos is zero, then the doclist is
100250** a sorted list of delta-compressed docids. If isReqPos is non-zero,
100251** then the returned list is in the same format as is stored in the
100252** database without the found length specifier at the start of on-disk
100253** doclists.
100254*/
100255static int fts3TermSelect(
100256  Fts3Table *p,                   /* Virtual table handle */
100257  int iColumn,                    /* Column to query (or -ve for all columns) */
100258  const char *zTerm,              /* Term to query for */
100259  int nTerm,                      /* Size of zTerm in bytes */
100260  int isPrefix,                   /* True for a prefix search */
100261  int isReqPos,                   /* True to include position lists in output */
100262  int *pnOut,                     /* OUT: Size of buffer at *ppOut */
100263  char **ppOut                    /* OUT: Malloced result buffer */
100264){
100265  int i;
100266  TermSelect tsc;
100267  Fts3SegFilter filter;           /* Segment term filter configuration */
100268  Fts3SegReader **apSegment;      /* Array of segments to read data from */
100269  int nSegment = 0;               /* Size of apSegment array */
100270  int nAlloc = 16;                /* Allocated size of segment array */
100271  int rc;                         /* Return code */
100272  sqlite3_stmt *pStmt = 0;        /* SQL statement to scan %_segdir table */
100273  int iAge = 0;                   /* Used to assign ages to segments */
100274
100275  apSegment = (Fts3SegReader **)sqlite3_malloc(sizeof(Fts3SegReader*)*nAlloc);
100276  if( !apSegment ) return SQLITE_NOMEM;
100277  rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &apSegment[0]);
100278  if( rc!=SQLITE_OK ) goto finished;
100279  if( apSegment[0] ){
100280    nSegment = 1;
100281  }
100282
100283  /* Loop through the entire %_segdir table. For each segment, create a
100284  ** Fts3SegReader to iterate through the subset of the segment leaves
100285  ** that may contain a term that matches zTerm/nTerm. For non-prefix
100286  ** searches, this is always a single leaf. For prefix searches, this
100287  ** may be a contiguous block of leaves.
100288  **
100289  ** The code in this loop does not actually load any leaves into memory
100290  ** (unless the root node happens to be a leaf). It simply examines the
100291  ** b-tree structure to determine which leaves need to be inspected.
100292  */
100293  rc = sqlite3Fts3AllSegdirs(p, &pStmt);
100294  while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
100295    Fts3SegReader *pNew = 0;
100296    int nRoot = sqlite3_column_bytes(pStmt, 4);
100297    char const *zRoot = sqlite3_column_blob(pStmt, 4);
100298    if( sqlite3_column_int64(pStmt, 1)==0 ){
100299      /* The entire segment is stored on the root node (which must be a
100300      ** leaf). Do not bother inspecting any data in this case, just
100301      ** create a Fts3SegReader to scan the single leaf.
100302      */
100303      rc = sqlite3Fts3SegReaderNew(p, iAge, 0, 0, 0, zRoot, nRoot, &pNew);
100304    }else{
100305      int rc2;                    /* Return value of sqlite3Fts3ReadBlock() */
100306      sqlite3_int64 i1;           /* Blockid of leaf that may contain zTerm */
100307      rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &i1);
100308      if( rc==SQLITE_OK ){
100309        sqlite3_int64 i2 = sqlite3_column_int64(pStmt, 2);
100310        rc = sqlite3Fts3SegReaderNew(p, iAge, i1, i2, 0, 0, 0, &pNew);
100311      }
100312
100313      /* The following call to ReadBlock() serves to reset the SQL statement
100314      ** used to retrieve blocks of data from the %_segments table. If it is
100315      ** not reset here, then it may remain classified as an active statement
100316      ** by SQLite, which may lead to "DROP TABLE" or "DETACH" commands
100317      ** failing.
100318      */
100319      rc2 = sqlite3Fts3ReadBlock(p, 0, 0, 0);
100320      if( rc==SQLITE_OK ){
100321        rc = rc2;
100322      }
100323    }
100324    iAge++;
100325
100326    /* If a new Fts3SegReader was allocated, add it to the apSegment array. */
100327    assert( pNew!=0 || rc!=SQLITE_OK );
100328    if( pNew ){
100329      if( nSegment==nAlloc ){
100330        Fts3SegReader **pArray;
100331        nAlloc += 16;
100332        pArray = (Fts3SegReader **)sqlite3_realloc(
100333            apSegment, nAlloc*sizeof(Fts3SegReader *)
100334        );
100335        if( !pArray ){
100336          sqlite3Fts3SegReaderFree(p, pNew);
100337          rc = SQLITE_NOMEM;
100338          goto finished;
100339        }
100340        apSegment = pArray;
100341      }
100342      apSegment[nSegment++] = pNew;
100343    }
100344  }
100345  if( rc!=SQLITE_DONE ){
100346    assert( rc!=SQLITE_OK );
100347    goto finished;
100348  }
100349
100350  memset(&tsc, 0, sizeof(TermSelect));
100351  tsc.isReqPos = isReqPos;
100352
100353  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY
100354        | (isPrefix ? FTS3_SEGMENT_PREFIX : 0)
100355        | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
100356        | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
100357  filter.iCol = iColumn;
100358  filter.zTerm = zTerm;
100359  filter.nTerm = nTerm;
100360
100361  rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment, &filter,
100362      fts3TermSelectCb, (void *)&tsc
100363  );
100364
100365  if( rc==SQLITE_OK ){
100366    *ppOut = tsc.aOutput;
100367    *pnOut = tsc.nOutput;
100368  }else{
100369    sqlite3_free(tsc.aOutput);
100370  }
100371
100372finished:
100373  sqlite3_reset(pStmt);
100374  for(i=0; i<nSegment; i++){
100375    sqlite3Fts3SegReaderFree(p, apSegment[i]);
100376  }
100377  sqlite3_free(apSegment);
100378  return rc;
100379}
100380
100381
100382/*
100383** Return a DocList corresponding to the phrase *pPhrase.
100384*/
100385static int fts3PhraseSelect(
100386  Fts3Table *p,                   /* Virtual table handle */
100387  Fts3Phrase *pPhrase,            /* Phrase to return a doclist for */
100388  int isReqPos,                   /* True if output should contain positions */
100389  char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
100390  int *pnOut                      /* OUT: Size of buffer at *paOut */
100391){
100392  char *pOut = 0;
100393  int nOut = 0;
100394  int rc = SQLITE_OK;
100395  int ii;
100396  int iCol = pPhrase->iColumn;
100397  int isTermPos = (pPhrase->nToken>1 || isReqPos);
100398
100399  for(ii=0; ii<pPhrase->nToken; ii++){
100400    struct PhraseToken *pTok = &pPhrase->aToken[ii];
100401    char *z = pTok->z;            /* Next token of the phrase */
100402    int n = pTok->n;              /* Size of z in bytes */
100403    int isPrefix = pTok->isPrefix;/* True if token is a prefix */
100404    char *pList;                  /* Pointer to token doclist */
100405    int nList;                    /* Size of buffer at pList */
100406
100407    rc = fts3TermSelect(p, iCol, z, n, isPrefix, isTermPos, &nList, &pList);
100408    if( rc!=SQLITE_OK ) break;
100409
100410    if( ii==0 ){
100411      pOut = pList;
100412      nOut = nList;
100413    }else{
100414      /* Merge the new term list and the current output. If this is the
100415      ** last term in the phrase, and positions are not required in the
100416      ** output of this function, the positions can be dropped as part
100417      ** of this merge. Either way, the result of this merge will be
100418      ** smaller than nList bytes. The code in fts3DoclistMerge() is written
100419      ** so that it is safe to use pList as the output as well as an input
100420      ** in this case.
100421      */
100422      int mergetype = MERGE_POS_PHRASE;
100423      if( ii==pPhrase->nToken-1 && !isReqPos ){
100424        mergetype = MERGE_PHRASE;
100425      }
100426      fts3DoclistMerge(mergetype, 0, 0, pList, &nOut, pOut, nOut, pList, nList);
100427      sqlite3_free(pOut);
100428      pOut = pList;
100429    }
100430    assert( nOut==0 || pOut!=0 );
100431  }
100432
100433  if( rc==SQLITE_OK ){
100434    *paOut = pOut;
100435    *pnOut = nOut;
100436  }else{
100437    sqlite3_free(pOut);
100438  }
100439  return rc;
100440}
100441
100442/*
100443** Evaluate the full-text expression pExpr against fts3 table pTab. Store
100444** the resulting doclist in *paOut and *pnOut.
100445*/
100446static int evalFts3Expr(
100447  Fts3Table *p,                   /* Virtual table handle */
100448  Fts3Expr *pExpr,                /* Parsed fts3 expression */
100449  char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
100450  int *pnOut,                     /* OUT: Size of buffer at *paOut */
100451  int isReqPos                    /* Require positions in output buffer */
100452){
100453  int rc = SQLITE_OK;             /* Return code */
100454
100455  /* Zero the output parameters. */
100456  *paOut = 0;
100457  *pnOut = 0;
100458
100459  if( pExpr ){
100460    assert( pExpr->eType==FTSQUERY_PHRASE
100461         || pExpr->eType==FTSQUERY_NEAR
100462         || isReqPos==0
100463    );
100464    if( pExpr->eType==FTSQUERY_PHRASE ){
100465      rc = fts3PhraseSelect(p, pExpr->pPhrase,
100466          isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR),
100467          paOut, pnOut
100468      );
100469    }else{
100470      char *aLeft;
100471      char *aRight;
100472      int nLeft;
100473      int nRight;
100474
100475      if( 0==(rc = evalFts3Expr(p, pExpr->pRight, &aRight, &nRight, isReqPos))
100476       && 0==(rc = evalFts3Expr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos))
100477      ){
100478        assert( pExpr->eType==FTSQUERY_NEAR || pExpr->eType==FTSQUERY_OR
100479            || pExpr->eType==FTSQUERY_AND  || pExpr->eType==FTSQUERY_NOT
100480        );
100481        switch( pExpr->eType ){
100482          case FTSQUERY_NEAR: {
100483            Fts3Expr *pLeft;
100484            Fts3Expr *pRight;
100485            int mergetype = isReqPos ? MERGE_POS_NEAR : MERGE_NEAR;
100486            int nParam1;
100487            int nParam2;
100488            char *aBuffer;
100489
100490            if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
100491              mergetype = MERGE_POS_NEAR;
100492            }
100493            pLeft = pExpr->pLeft;
100494            while( pLeft->eType==FTSQUERY_NEAR ){
100495              pLeft=pLeft->pRight;
100496            }
100497            pRight = pExpr->pRight;
100498            assert( pRight->eType==FTSQUERY_PHRASE );
100499            assert( pLeft->eType==FTSQUERY_PHRASE );
100500
100501            nParam1 = pExpr->nNear+1;
100502            nParam2 = nParam1+pLeft->pPhrase->nToken+pRight->pPhrase->nToken-2;
100503            aBuffer = sqlite3_malloc(nLeft+nRight+1);
100504            rc = fts3DoclistMerge(mergetype, nParam1, nParam2, aBuffer,
100505                pnOut, aLeft, nLeft, aRight, nRight
100506            );
100507            if( rc!=SQLITE_OK ){
100508              sqlite3_free(aBuffer);
100509            }else{
100510              *paOut = aBuffer;
100511            }
100512            sqlite3_free(aLeft);
100513            break;
100514          }
100515
100516          case FTSQUERY_OR: {
100517            /* Allocate a buffer for the output. The maximum size is the
100518            ** sum of the sizes of the two input buffers. The +1 term is
100519            ** so that a buffer of zero bytes is never allocated - this can
100520            ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM.
100521            */
100522            char *aBuffer = sqlite3_malloc(nRight+nLeft+1);
100523            rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut,
100524                aLeft, nLeft, aRight, nRight
100525            );
100526            *paOut = aBuffer;
100527            sqlite3_free(aLeft);
100528            break;
100529          }
100530
100531          default: {
100532            assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND );
100533            fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut,
100534                aLeft, nLeft, aRight, nRight
100535            );
100536            *paOut = aLeft;
100537            break;
100538          }
100539        }
100540      }
100541      sqlite3_free(aRight);
100542    }
100543  }
100544
100545  return rc;
100546}
100547
100548/*
100549** This is the xFilter interface for the virtual table.  See
100550** the virtual table xFilter method documentation for additional
100551** information.
100552**
100553** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
100554** the %_content table.
100555**
100556** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
100557** in the %_content table.
100558**
100559** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
100560** column on the left-hand side of the MATCH operator is column
100561** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
100562** side of the MATCH operator.
100563*/
100564/* TODO(shess) Upgrade the cursor initialization and destruction to
100565** account for fts3FilterMethod() being called multiple times on the
100566** same cursor. The current solution is very fragile. Apply fix to
100567** fts3 as appropriate.
100568*/
100569static int fts3FilterMethod(
100570  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
100571  int idxNum,                     /* Strategy index */
100572  const char *idxStr,             /* Unused */
100573  int nVal,                       /* Number of elements in apVal */
100574  sqlite3_value **apVal           /* Arguments for the indexing scheme */
100575){
100576  const char *azSql[] = {
100577    "SELECT * FROM %Q.'%q_content' WHERE docid = ?", /* non-full-table-scan */
100578    "SELECT * FROM %Q.'%q_content'",                 /* full-table-scan */
100579  };
100580  int rc;                         /* Return code */
100581  char *zSql;                     /* SQL statement used to access %_content */
100582  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
100583  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
100584
100585  UNUSED_PARAMETER(idxStr);
100586  UNUSED_PARAMETER(nVal);
100587
100588  assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
100589  assert( nVal==0 || nVal==1 );
100590  assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
100591
100592  /* In case the cursor has been used before, clear it now. */
100593  sqlite3_finalize(pCsr->pStmt);
100594  sqlite3_free(pCsr->aDoclist);
100595  sqlite3Fts3ExprFree(pCsr->pExpr);
100596  memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
100597
100598  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
100599  ** statement loops through all rows of the %_content table. For a
100600  ** full-text query or docid lookup, the statement retrieves a single
100601  ** row by docid.
100602  */
100603  zSql = sqlite3_mprintf(azSql[idxNum==FTS3_FULLSCAN_SEARCH], p->zDb, p->zName);
100604  if( !zSql ){
100605    rc = SQLITE_NOMEM;
100606  }else{
100607    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
100608    sqlite3_free(zSql);
100609  }
100610  if( rc!=SQLITE_OK ) return rc;
100611  pCsr->eSearch = (i16)idxNum;
100612
100613  if( idxNum==FTS3_DOCID_SEARCH ){
100614    rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
100615  }else if( idxNum!=FTS3_FULLSCAN_SEARCH ){
100616    int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
100617    const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
100618
100619    if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
100620      return SQLITE_NOMEM;
100621    }
100622
100623    rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn,
100624        iCol, zQuery, -1, &pCsr->pExpr
100625    );
100626    if( rc!=SQLITE_OK ) return rc;
100627
100628    rc = evalFts3Expr(p, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
100629    pCsr->pNextId = pCsr->aDoclist;
100630    pCsr->iPrevId = 0;
100631  }
100632
100633  if( rc!=SQLITE_OK ) return rc;
100634  return fts3NextMethod(pCursor);
100635}
100636
100637/*
100638** This is the xEof method of the virtual table. SQLite calls this
100639** routine to find out if it has reached the end of a result set.
100640*/
100641static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
100642  return ((Fts3Cursor *)pCursor)->isEof;
100643}
100644
100645/*
100646** This is the xRowid method. The SQLite core calls this routine to
100647** retrieve the rowid for the current row of the result set. fts3
100648** exposes %_content.docid as the rowid for the virtual table. The
100649** rowid should be written to *pRowid.
100650*/
100651static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
100652  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
100653  if( pCsr->aDoclist ){
100654    *pRowid = pCsr->iPrevId;
100655  }else{
100656    *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
100657  }
100658  return SQLITE_OK;
100659}
100660
100661/*
100662** This is the xColumn method, called by SQLite to request a value from
100663** the row that the supplied cursor currently points to.
100664*/
100665static int fts3ColumnMethod(
100666  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
100667  sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
100668  int iCol                        /* Index of column to read value from */
100669){
100670  int rc;                         /* Return Code */
100671  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
100672  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
100673
100674  /* The column value supplied by SQLite must be in range. */
100675  assert( iCol>=0 && iCol<=p->nColumn+1 );
100676
100677  if( iCol==p->nColumn+1 ){
100678    /* This call is a request for the "docid" column. Since "docid" is an
100679    ** alias for "rowid", use the xRowid() method to obtain the value.
100680    */
100681    sqlite3_int64 iRowid;
100682    rc = fts3RowidMethod(pCursor, &iRowid);
100683    sqlite3_result_int64(pContext, iRowid);
100684  }else if( iCol==p->nColumn ){
100685    /* The extra column whose name is the same as the table.
100686    ** Return a blob which is a pointer to the cursor.
100687    */
100688    sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
100689    rc = SQLITE_OK;
100690  }else{
100691    rc = fts3CursorSeek(0, pCsr);
100692    if( rc==SQLITE_OK ){
100693      sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
100694    }
100695  }
100696  return rc;
100697}
100698
100699/*
100700** This function is the implementation of the xUpdate callback used by
100701** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
100702** inserted, updated or deleted.
100703*/
100704static int fts3UpdateMethod(
100705  sqlite3_vtab *pVtab,            /* Virtual table handle */
100706  int nArg,                       /* Size of argument array */
100707  sqlite3_value **apVal,          /* Array of arguments */
100708  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
100709){
100710  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
100711}
100712
100713/*
100714** Implementation of xSync() method. Flush the contents of the pending-terms
100715** hash-table to the database.
100716*/
100717static int fts3SyncMethod(sqlite3_vtab *pVtab){
100718  return sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
100719}
100720
100721/*
100722** Implementation of xBegin() method. This is a no-op.
100723*/
100724static int fts3BeginMethod(sqlite3_vtab *pVtab){
100725  UNUSED_PARAMETER(pVtab);
100726  assert( ((Fts3Table *)pVtab)->nPendingData==0 );
100727  return SQLITE_OK;
100728}
100729
100730/*
100731** Implementation of xCommit() method. This is a no-op. The contents of
100732** the pending-terms hash-table have already been flushed into the database
100733** by fts3SyncMethod().
100734*/
100735static int fts3CommitMethod(sqlite3_vtab *pVtab){
100736  UNUSED_PARAMETER(pVtab);
100737  assert( ((Fts3Table *)pVtab)->nPendingData==0 );
100738  return SQLITE_OK;
100739}
100740
100741/*
100742** Implementation of xRollback(). Discard the contents of the pending-terms
100743** hash-table. Any changes made to the database are reverted by SQLite.
100744*/
100745static int fts3RollbackMethod(sqlite3_vtab *pVtab){
100746  sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab);
100747  return SQLITE_OK;
100748}
100749
100750/*
100751** Load the doclist associated with expression pExpr to pExpr->aDoclist.
100752** The loaded doclist contains positions as well as the document ids.
100753** This is used by the matchinfo(), snippet() and offsets() auxillary
100754** functions.
100755*/
100756SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *pTab, Fts3Expr *pExpr){
100757  return evalFts3Expr(pTab, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1);
100758}
100759
100760/*
100761** After ExprLoadDoclist() (see above) has been called, this function is
100762** used to iterate through the position lists that make up the doclist
100763** stored in pExpr->aDoclist.
100764*/
100765SQLITE_PRIVATE char *sqlite3Fts3FindPositions(
100766  Fts3Expr *pExpr,                /* Access this expressions doclist */
100767  sqlite3_int64 iDocid,           /* Docid associated with requested pos-list */
100768  int iCol                        /* Column of requested pos-list */
100769){
100770  assert( pExpr->isLoaded );
100771  if( pExpr->aDoclist ){
100772    char *pEnd = &pExpr->aDoclist[pExpr->nDoclist];
100773    char *pCsr = pExpr->pCurrent;
100774
100775    assert( pCsr );
100776    while( pCsr<pEnd ){
100777      if( pExpr->iCurrent<iDocid ){
100778        fts3PoslistCopy(0, &pCsr);
100779        fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent);
100780        pExpr->pCurrent = pCsr;
100781      }else{
100782        if( pExpr->iCurrent==iDocid ){
100783          int iThis = 0;
100784          if( iCol<0 ){
100785            /* If iCol is negative, return a pointer to the start of the
100786            ** position-list (instead of a pointer to the start of a list
100787            ** of offsets associated with a specific column).
100788            */
100789            return pCsr;
100790          }
100791          while( iThis<iCol ){
100792            fts3ColumnlistCopy(0, &pCsr);
100793            if( *pCsr==0x00 ) return 0;
100794            pCsr++;
100795            pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis);
100796          }
100797          if( iCol==iThis ) return pCsr;
100798        }
100799        return 0;
100800      }
100801    }
100802  }
100803
100804  return 0;
100805}
100806
100807/*
100808** Helper function used by the implementation of the overloaded snippet(),
100809** offsets() and optimize() SQL functions.
100810**
100811** If the value passed as the third argument is a blob of size
100812** sizeof(Fts3Cursor*), then the blob contents are copied to the
100813** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
100814** message is written to context pContext and SQLITE_ERROR returned. The
100815** string passed via zFunc is used as part of the error message.
100816*/
100817static int fts3FunctionArg(
100818  sqlite3_context *pContext,      /* SQL function call context */
100819  const char *zFunc,              /* Function name */
100820  sqlite3_value *pVal,            /* argv[0] passed to function */
100821  Fts3Cursor **ppCsr         /* OUT: Store cursor handle here */
100822){
100823  Fts3Cursor *pRet;
100824  if( sqlite3_value_type(pVal)!=SQLITE_BLOB
100825   || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
100826  ){
100827    char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
100828    sqlite3_result_error(pContext, zErr, -1);
100829    sqlite3_free(zErr);
100830    return SQLITE_ERROR;
100831  }
100832  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
100833  *ppCsr = pRet;
100834  return SQLITE_OK;
100835}
100836
100837/*
100838** Implementation of the snippet() function for FTS3
100839*/
100840static void fts3SnippetFunc(
100841  sqlite3_context *pContext,      /* SQLite function call context */
100842  int nVal,                       /* Size of apVal[] array */
100843  sqlite3_value **apVal           /* Array of arguments */
100844){
100845  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
100846  const char *zStart = "<b>";
100847  const char *zEnd = "</b>";
100848  const char *zEllipsis = "<b>...</b>";
100849
100850  /* There must be at least one argument passed to this function (otherwise
100851  ** the non-overloaded version would have been called instead of this one).
100852  */
100853  assert( nVal>=1 );
100854
100855  if( nVal>4 ){
100856    sqlite3_result_error(pContext,
100857        "wrong number of arguments to function snippet()", -1);
100858    return;
100859  }
100860  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
100861
100862  switch( nVal ){
100863    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
100864    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
100865    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
100866  }
100867  if( !zEllipsis || !zEnd || !zStart ){
100868    sqlite3_result_error_nomem(pContext);
100869  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
100870    sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis);
100871  }
100872}
100873
100874/*
100875** Implementation of the snippet2() function for FTS3
100876*/
100877static void fts3Snippet2Func(
100878  sqlite3_context *pContext,      /* SQLite function call context */
100879  int nVal,                       /* Size of apVal[] array */
100880  sqlite3_value **apVal           /* Array of arguments */
100881){
100882  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
100883  const char *zStart = "<b>";
100884  const char *zEnd = "</b>";
100885  const char *zEllipsis = "<b>...</b>";
100886  int iCol = -1;
100887  int nToken = 10;
100888
100889  /* There must be at least one argument passed to this function (otherwise
100890  ** the non-overloaded version would have been called instead of this one).
100891  */
100892  assert( nVal>=1 );
100893
100894  if( nVal>6 ){
100895    sqlite3_result_error(pContext,
100896        "wrong number of arguments to function snippet()", -1);
100897    return;
100898  }
100899  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
100900
100901  switch( nVal ){
100902    case 6: nToken = sqlite3_value_int(apVal[5]);
100903    case 5: iCol = sqlite3_value_int(apVal[4]);
100904    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
100905    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
100906    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
100907  }
100908  if( !zEllipsis || !zEnd || !zStart ){
100909    sqlite3_result_error_nomem(pContext);
100910  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
100911    sqlite3Fts3Snippet2(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
100912  }
100913}
100914
100915/*
100916** Implementation of the offsets() function for FTS3
100917*/
100918static void fts3OffsetsFunc(
100919  sqlite3_context *pContext,      /* SQLite function call context */
100920  int nVal,                       /* Size of argument array */
100921  sqlite3_value **apVal           /* Array of arguments */
100922){
100923  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
100924
100925  UNUSED_PARAMETER(nVal);
100926
100927  assert( nVal==1 );
100928  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
100929  assert( pCsr );
100930  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
100931    sqlite3Fts3Offsets(pContext, pCsr);
100932  }
100933}
100934
100935/*
100936** Implementation of the special optimize() function for FTS3. This
100937** function merges all segments in the database to a single segment.
100938** Example usage is:
100939**
100940**   SELECT optimize(t) FROM t LIMIT 1;
100941**
100942** where 't' is the name of an FTS3 table.
100943*/
100944static void fts3OptimizeFunc(
100945  sqlite3_context *pContext,      /* SQLite function call context */
100946  int nVal,                       /* Size of argument array */
100947  sqlite3_value **apVal           /* Array of arguments */
100948){
100949  int rc;                         /* Return code */
100950  Fts3Table *p;                   /* Virtual table handle */
100951  Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
100952
100953  UNUSED_PARAMETER(nVal);
100954
100955  assert( nVal==1 );
100956  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
100957  p = (Fts3Table *)pCursor->base.pVtab;
100958  assert( p );
100959
100960  rc = sqlite3Fts3Optimize(p);
100961
100962  switch( rc ){
100963    case SQLITE_OK:
100964      sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
100965      break;
100966    case SQLITE_DONE:
100967      sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
100968      break;
100969    default:
100970      sqlite3_result_error_code(pContext, rc);
100971      break;
100972  }
100973}
100974
100975/*
100976** Implementation of the matchinfo() function for FTS3
100977*/
100978static void fts3MatchinfoFunc(
100979  sqlite3_context *pContext,      /* SQLite function call context */
100980  int nVal,                       /* Size of argument array */
100981  sqlite3_value **apVal           /* Array of arguments */
100982){
100983  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
100984
100985  if( nVal!=1 ){
100986    sqlite3_result_error(pContext,
100987        "wrong number of arguments to function matchinfo()", -1);
100988    return;
100989  }
100990
100991  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
100992    sqlite3Fts3Matchinfo(pContext, pCsr);
100993  }
100994}
100995
100996/*
100997** This routine implements the xFindFunction method for the FTS3
100998** virtual table.
100999*/
101000static int fts3FindFunctionMethod(
101001  sqlite3_vtab *pVtab,            /* Virtual table handle */
101002  int nArg,                       /* Number of SQL function arguments */
101003  const char *zName,              /* Name of SQL function */
101004  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
101005  void **ppArg                    /* Unused */
101006){
101007  struct Overloaded {
101008    const char *zName;
101009    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
101010  } aOverload[] = {
101011    { "snippet", fts3SnippetFunc },
101012    { "snippet2", fts3Snippet2Func },
101013    { "offsets", fts3OffsetsFunc },
101014    { "optimize", fts3OptimizeFunc },
101015    { "matchinfo", fts3MatchinfoFunc },
101016  };
101017  int i;                          /* Iterator variable */
101018
101019  UNUSED_PARAMETER(pVtab);
101020  UNUSED_PARAMETER(nArg);
101021  UNUSED_PARAMETER(ppArg);
101022
101023  for(i=0; i<SizeofArray(aOverload); i++){
101024    if( strcmp(zName, aOverload[i].zName)==0 ){
101025      *pxFunc = aOverload[i].xFunc;
101026      return 1;
101027    }
101028  }
101029
101030  /* No function of the specified name was found. Return 0. */
101031  return 0;
101032}
101033
101034/*
101035** Implementation of FTS3 xRename method. Rename an fts3 table.
101036*/
101037static int fts3RenameMethod(
101038  sqlite3_vtab *pVtab,            /* Virtual table handle */
101039  const char *zName               /* New name of table */
101040){
101041  Fts3Table *p = (Fts3Table *)pVtab;
101042  int rc = SQLITE_NOMEM;          /* Return Code */
101043  char *zSql;                     /* SQL script to run to rename tables */
101044
101045  zSql = sqlite3_mprintf(
101046    "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';"
101047    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
101048    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';"
101049    , p->zDb, p->zName, zName
101050    , p->zDb, p->zName, zName
101051    , p->zDb, p->zName, zName
101052  );
101053  if( zSql ){
101054    rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
101055    sqlite3_free(zSql);
101056  }
101057  return rc;
101058}
101059
101060static const sqlite3_module fts3Module = {
101061  /* iVersion      */ 0,
101062  /* xCreate       */ fts3CreateMethod,
101063  /* xConnect      */ fts3ConnectMethod,
101064  /* xBestIndex    */ fts3BestIndexMethod,
101065  /* xDisconnect   */ fts3DisconnectMethod,
101066  /* xDestroy      */ fts3DestroyMethod,
101067  /* xOpen         */ fts3OpenMethod,
101068  /* xClose        */ fulltextClose,
101069  /* xFilter       */ fts3FilterMethod,
101070  /* xNext         */ fts3NextMethod,
101071  /* xEof          */ fts3EofMethod,
101072  /* xColumn       */ fts3ColumnMethod,
101073  /* xRowid        */ fts3RowidMethod,
101074  /* xUpdate       */ fts3UpdateMethod,
101075  /* xBegin        */ fts3BeginMethod,
101076  /* xSync         */ fts3SyncMethod,
101077  /* xCommit       */ fts3CommitMethod,
101078  /* xRollback     */ fts3RollbackMethod,
101079  /* xFindFunction */ fts3FindFunctionMethod,
101080  /* xRename */       fts3RenameMethod,
101081};
101082
101083/*
101084** This function is registered as the module destructor (called when an
101085** FTS3 enabled database connection is closed). It frees the memory
101086** allocated for the tokenizer hash table.
101087*/
101088static void hashDestroy(void *p){
101089  Fts3Hash *pHash = (Fts3Hash *)p;
101090  sqlite3Fts3HashClear(pHash);
101091  sqlite3_free(pHash);
101092}
101093
101094/*
101095** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
101096** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
101097** two forward declarations are for functions declared in these files
101098** used to retrieve the respective implementations.
101099**
101100** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
101101** to by the argument to point a the "simple" tokenizer implementation.
101102** Function ...PorterTokenizerModule() sets *pModule to point to the
101103** porter tokenizer/stemmer implementation.
101104*/
101105SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
101106SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
101107SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
101108
101109/*
101110** Initialise the fts3 extension. If this extension is built as part
101111** of the sqlite library, then this function is called directly by
101112** SQLite. If fts3 is built as a dynamically loadable extension, this
101113** function is called by the sqlite3_extension_init() entry point.
101114*/
101115// Begin Android change
101116SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db, const char* registerAs){
101117// End Android change
101118
101119  int rc = SQLITE_OK;
101120  Fts3Hash *pHash = 0;
101121  const sqlite3_tokenizer_module *pSimple = 0;
101122  const sqlite3_tokenizer_module *pPorter = 0;
101123
101124#ifdef SQLITE_ENABLE_ICU
101125  const sqlite3_tokenizer_module *pIcu = 0;
101126  sqlite3Fts3IcuTokenizerModule(&pIcu);
101127#endif
101128
101129  sqlite3Fts3SimpleTokenizerModule(&pSimple);
101130  sqlite3Fts3PorterTokenizerModule(&pPorter);
101131
101132  /* Allocate and initialise the hash-table used to store tokenizers. */
101133  pHash = sqlite3_malloc(sizeof(Fts3Hash));
101134  if( !pHash ){
101135    rc = SQLITE_NOMEM;
101136  }else{
101137    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
101138  }
101139
101140  /* Load the built-in tokenizers into the hash table */
101141  if( rc==SQLITE_OK ){
101142    if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
101143     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
101144#ifdef SQLITE_ENABLE_ICU
101145     || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
101146#endif
101147    ){
101148      rc = SQLITE_NOMEM;
101149    }
101150  }
101151
101152#ifdef SQLITE_TEST
101153  if( rc==SQLITE_OK ){
101154    rc = sqlite3Fts3ExprInitTestInterface(db);
101155  }
101156#endif
101157
101158  /* Create the virtual table wrapper around the hash-table and overload
101159  ** the two scalar functions. If this is successful, register the
101160  ** module with sqlite.
101161  */
101162  if( SQLITE_OK==rc
101163   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
101164   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
101165   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet2", -1))
101166   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
101167   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", -1))
101168   && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
101169  ){
101170    // Begin Android change
101171    /* Also register as fts1 and fts2 */
101172    return sqlite3_create_module_v2(
101173        db, registerAs, &fts3Module, (void *)pHash, hashDestroy
101174    // End Android change
101175    );
101176  }
101177
101178  /* An error has occurred. Delete the hash table and return the error code. */
101179  assert( rc!=SQLITE_OK );
101180  if( pHash ){
101181    sqlite3Fts3HashClear(pHash);
101182    sqlite3_free(pHash);
101183  }
101184  return rc;
101185}
101186
101187#if !SQLITE_CORE
101188SQLITE_API int sqlite3_extension_init(
101189  sqlite3 *db,
101190  char **pzErrMsg,
101191  const sqlite3_api_routines *pApi
101192){
101193  SQLITE_EXTENSION_INIT2(pApi)
101194  return sqlite3Fts3Init(db);
101195}
101196#endif
101197
101198#endif
101199
101200/************** End of fts3.c ************************************************/
101201/************** Begin file fts3_expr.c ***************************************/
101202/*
101203** 2008 Nov 28
101204**
101205** The author disclaims copyright to this source code.  In place of
101206** a legal notice, here is a blessing:
101207**
101208**    May you do good and not evil.
101209**    May you find forgiveness for yourself and forgive others.
101210**    May you share freely, never taking more than you give.
101211**
101212******************************************************************************
101213**
101214** This module contains code that implements a parser for fts3 query strings
101215** (the right-hand argument to the MATCH operator). Because the supported
101216** syntax is relatively simple, the whole tokenizer/parser system is
101217** hand-coded.
101218*/
101219#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
101220
101221/*
101222** By default, this module parses the legacy syntax that has been
101223** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
101224** is defined, then it uses the new syntax. The differences between
101225** the new and the old syntaxes are:
101226**
101227**  a) The new syntax supports parenthesis. The old does not.
101228**
101229**  b) The new syntax supports the AND and NOT operators. The old does not.
101230**
101231**  c) The old syntax supports the "-" token qualifier. This is not
101232**     supported by the new syntax (it is replaced by the NOT operator).
101233**
101234**  d) When using the old syntax, the OR operator has a greater precedence
101235**     than an implicit AND. When using the new, both implicity and explicit
101236**     AND operators have a higher precedence than OR.
101237**
101238** If compiled with SQLITE_TEST defined, then this module exports the
101239** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
101240** to zero causes the module to use the old syntax. If it is set to
101241** non-zero the new syntax is activated. This is so both syntaxes can
101242** be tested using a single build of testfixture.
101243**
101244** The following describes the syntax supported by the fts3 MATCH
101245** operator in a similar format to that used by the lemon parser
101246** generator. This module does not use actually lemon, it uses a
101247** custom parser.
101248**
101249**   query ::= andexpr (OR andexpr)*.
101250**
101251**   andexpr ::= notexpr (AND? notexpr)*.
101252**
101253**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
101254**   notexpr ::= LP query RP.
101255**
101256**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
101257**
101258**   distance_opt ::= .
101259**   distance_opt ::= / INTEGER.
101260**
101261**   phrase ::= TOKEN.
101262**   phrase ::= COLUMN:TOKEN.
101263**   phrase ::= "TOKEN TOKEN TOKEN...".
101264*/
101265
101266#ifdef SQLITE_TEST
101267SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
101268#else
101269# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
101270#  define sqlite3_fts3_enable_parentheses 1
101271# else
101272#  define sqlite3_fts3_enable_parentheses 0
101273# endif
101274#endif
101275
101276/*
101277** Default span for NEAR operators.
101278*/
101279#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
101280
101281
101282typedef struct ParseContext ParseContext;
101283struct ParseContext {
101284  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
101285  const char **azCol;                 /* Array of column names for fts3 table */
101286  int nCol;                           /* Number of entries in azCol[] */
101287  int iDefaultCol;                    /* Default column to query */
101288  sqlite3_context *pCtx;              /* Write error message here */
101289  int nNest;                          /* Number of nested brackets */
101290};
101291
101292/*
101293** This function is equivalent to the standard isspace() function.
101294**
101295** The standard isspace() can be awkward to use safely, because although it
101296** is defined to accept an argument of type int, its behaviour when passed
101297** an integer that falls outside of the range of the unsigned char type
101298** is undefined (and sometimes, "undefined" means segfault). This wrapper
101299** is defined to accept an argument of type char, and always returns 0 for
101300** any values that fall outside of the range of the unsigned char type (i.e.
101301** negative values).
101302*/
101303static int fts3isspace(char c){
101304  return (c&0x80)==0 ? isspace(c) : 0;
101305}
101306
101307/*
101308** Extract the next token from buffer z (length n) using the tokenizer
101309** and other information (column names etc.) in pParse. Create an Fts3Expr
101310** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
101311** single token and set *ppExpr to point to it. If the end of the buffer is
101312** reached before a token is found, set *ppExpr to zero. It is the
101313** responsibility of the caller to eventually deallocate the allocated
101314** Fts3Expr structure (if any) by passing it to sqlite3_free().
101315**
101316** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
101317** fails.
101318*/
101319static int getNextToken(
101320  ParseContext *pParse,                   /* fts3 query parse context */
101321  int iCol,                               /* Value for Fts3Phrase.iColumn */
101322  const char *z, int n,                   /* Input string */
101323  Fts3Expr **ppExpr,                      /* OUT: expression */
101324  int *pnConsumed                         /* OUT: Number of bytes consumed */
101325){
101326  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
101327  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
101328  int rc;
101329  sqlite3_tokenizer_cursor *pCursor;
101330  Fts3Expr *pRet = 0;
101331  int nConsumed = 0;
101332
101333  rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
101334  if( rc==SQLITE_OK ){
101335    const char *zToken;
101336    int nToken, iStart, iEnd, iPosition;
101337    int nByte;                               /* total space to allocate */
101338
101339    pCursor->pTokenizer = pTokenizer;
101340    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
101341
101342    if( rc==SQLITE_OK ){
101343      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
101344      pRet = (Fts3Expr *)sqlite3_malloc(nByte);
101345      if( !pRet ){
101346        rc = SQLITE_NOMEM;
101347      }else{
101348        memset(pRet, 0, nByte);
101349        pRet->eType = FTSQUERY_PHRASE;
101350        pRet->pPhrase = (Fts3Phrase *)&pRet[1];
101351        pRet->pPhrase->nToken = 1;
101352        pRet->pPhrase->iColumn = iCol;
101353        pRet->pPhrase->aToken[0].n = nToken;
101354        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
101355        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
101356
101357        if( iEnd<n && z[iEnd]=='*' ){
101358          pRet->pPhrase->aToken[0].isPrefix = 1;
101359          iEnd++;
101360        }
101361        if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
101362          pRet->pPhrase->isNot = 1;
101363        }
101364      }
101365      nConsumed = iEnd;
101366    }
101367
101368    pModule->xClose(pCursor);
101369  }
101370
101371  *pnConsumed = nConsumed;
101372  *ppExpr = pRet;
101373  return rc;
101374}
101375
101376
101377/*
101378** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
101379** then free the old allocation.
101380*/
101381static void *fts3ReallocOrFree(void *pOrig, int nNew){
101382  void *pRet = sqlite3_realloc(pOrig, nNew);
101383  if( !pRet ){
101384    sqlite3_free(pOrig);
101385  }
101386  return pRet;
101387}
101388
101389/*
101390** Buffer zInput, length nInput, contains the contents of a quoted string
101391** that appeared as part of an fts3 query expression. Neither quote character
101392** is included in the buffer. This function attempts to tokenize the entire
101393** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
101394** containing the results.
101395**
101396** If successful, SQLITE_OK is returned and *ppExpr set to point at the
101397** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
101398** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
101399** to 0.
101400*/
101401static int getNextString(
101402  ParseContext *pParse,                   /* fts3 query parse context */
101403  const char *zInput, int nInput,         /* Input string */
101404  Fts3Expr **ppExpr                       /* OUT: expression */
101405){
101406  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
101407  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
101408  int rc;
101409  Fts3Expr *p = 0;
101410  sqlite3_tokenizer_cursor *pCursor = 0;
101411  char *zTemp = 0;
101412  int nTemp = 0;
101413
101414  rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
101415  if( rc==SQLITE_OK ){
101416    int ii;
101417    pCursor->pTokenizer = pTokenizer;
101418    for(ii=0; rc==SQLITE_OK; ii++){
101419      const char *zToken;
101420      int nToken, iBegin, iEnd, iPos;
101421      rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
101422      if( rc==SQLITE_OK ){
101423        int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
101424        p = fts3ReallocOrFree(p, nByte+ii*sizeof(struct PhraseToken));
101425        zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
101426        if( !p || !zTemp ){
101427          goto no_mem;
101428        }
101429        if( ii==0 ){
101430          memset(p, 0, nByte);
101431          p->pPhrase = (Fts3Phrase *)&p[1];
101432        }
101433        p->pPhrase = (Fts3Phrase *)&p[1];
101434        p->pPhrase->nToken = ii+1;
101435        p->pPhrase->aToken[ii].n = nToken;
101436        memcpy(&zTemp[nTemp], zToken, nToken);
101437        nTemp += nToken;
101438        if( iEnd<nInput && zInput[iEnd]=='*' ){
101439          p->pPhrase->aToken[ii].isPrefix = 1;
101440        }else{
101441          p->pPhrase->aToken[ii].isPrefix = 0;
101442        }
101443      }
101444    }
101445
101446    pModule->xClose(pCursor);
101447    pCursor = 0;
101448  }
101449
101450  if( rc==SQLITE_DONE ){
101451    int jj;
101452    char *zNew = NULL;
101453    int nNew = 0;
101454    int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
101455    nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(struct PhraseToken);
101456    p = fts3ReallocOrFree(p, nByte + nTemp);
101457    if( !p ){
101458      goto no_mem;
101459    }
101460    if( zTemp ){
101461      zNew = &(((char *)p)[nByte]);
101462      memcpy(zNew, zTemp, nTemp);
101463    }else{
101464      memset(p, 0, nByte+nTemp);
101465    }
101466    p->pPhrase = (Fts3Phrase *)&p[1];
101467    for(jj=0; jj<p->pPhrase->nToken; jj++){
101468      p->pPhrase->aToken[jj].z = &zNew[nNew];
101469      nNew += p->pPhrase->aToken[jj].n;
101470    }
101471    sqlite3_free(zTemp);
101472    p->eType = FTSQUERY_PHRASE;
101473    p->pPhrase->iColumn = pParse->iDefaultCol;
101474    rc = SQLITE_OK;
101475  }
101476
101477  *ppExpr = p;
101478  return rc;
101479no_mem:
101480
101481  if( pCursor ){
101482    pModule->xClose(pCursor);
101483  }
101484  sqlite3_free(zTemp);
101485  sqlite3_free(p);
101486  *ppExpr = 0;
101487  return SQLITE_NOMEM;
101488}
101489
101490/*
101491** Function getNextNode(), which is called by fts3ExprParse(), may itself
101492** call fts3ExprParse(). So this forward declaration is required.
101493*/
101494static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
101495
101496/*
101497** The output variable *ppExpr is populated with an allocated Fts3Expr
101498** structure, or set to 0 if the end of the input buffer is reached.
101499**
101500** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
101501** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
101502** If SQLITE_ERROR is returned, pContext is populated with an error message.
101503*/
101504static int getNextNode(
101505  ParseContext *pParse,                   /* fts3 query parse context */
101506  const char *z, int n,                   /* Input string */
101507  Fts3Expr **ppExpr,                      /* OUT: expression */
101508  int *pnConsumed                         /* OUT: Number of bytes consumed */
101509){
101510  static const struct Fts3Keyword {
101511    char *z;                              /* Keyword text */
101512    unsigned char n;                      /* Length of the keyword */
101513    unsigned char parenOnly;              /* Only valid in paren mode */
101514    unsigned char eType;                  /* Keyword code */
101515  } aKeyword[] = {
101516    { "OR" ,  2, 0, FTSQUERY_OR   },
101517    { "AND",  3, 1, FTSQUERY_AND  },
101518    { "NOT",  3, 1, FTSQUERY_NOT  },
101519    { "NEAR", 4, 0, FTSQUERY_NEAR }
101520  };
101521  int ii;
101522  int iCol;
101523  int iColLen;
101524  int rc;
101525  Fts3Expr *pRet = 0;
101526
101527  const char *zInput = z;
101528  int nInput = n;
101529
101530  /* Skip over any whitespace before checking for a keyword, an open or
101531  ** close bracket, or a quoted string.
101532  */
101533  while( nInput>0 && fts3isspace(*zInput) ){
101534    nInput--;
101535    zInput++;
101536  }
101537  if( nInput==0 ){
101538    return SQLITE_DONE;
101539  }
101540
101541  /* See if we are dealing with a keyword. */
101542  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
101543    const struct Fts3Keyword *pKey = &aKeyword[ii];
101544
101545    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
101546      continue;
101547    }
101548
101549    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
101550      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
101551      int nKey = pKey->n;
101552      char cNext;
101553
101554      /* If this is a "NEAR" keyword, check for an explicit nearness. */
101555      if( pKey->eType==FTSQUERY_NEAR ){
101556        assert( nKey==4 );
101557        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
101558          nNear = 0;
101559          for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
101560            nNear = nNear * 10 + (zInput[nKey] - '0');
101561          }
101562        }
101563      }
101564
101565      /* At this point this is probably a keyword. But for that to be true,
101566      ** the next byte must contain either whitespace, an open or close
101567      ** parenthesis, a quote character, or EOF.
101568      */
101569      cNext = zInput[nKey];
101570      if( fts3isspace(cNext)
101571       || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
101572      ){
101573        pRet = (Fts3Expr *)sqlite3_malloc(sizeof(Fts3Expr));
101574        if( !pRet ){
101575          return SQLITE_NOMEM;
101576        }
101577        memset(pRet, 0, sizeof(Fts3Expr));
101578        pRet->eType = pKey->eType;
101579        pRet->nNear = nNear;
101580        *ppExpr = pRet;
101581        *pnConsumed = (int)((zInput - z) + nKey);
101582        return SQLITE_OK;
101583      }
101584
101585      /* Turns out that wasn't a keyword after all. This happens if the
101586      ** user has supplied a token such as "ORacle". Continue.
101587      */
101588    }
101589  }
101590
101591  /* Check for an open bracket. */
101592  if( sqlite3_fts3_enable_parentheses ){
101593    if( *zInput=='(' ){
101594      int nConsumed;
101595      int rc;
101596      pParse->nNest++;
101597      rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
101598      if( rc==SQLITE_OK && !*ppExpr ){
101599        rc = SQLITE_DONE;
101600      }
101601      *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
101602      return rc;
101603    }
101604
101605    /* Check for a close bracket. */
101606    if( *zInput==')' ){
101607      pParse->nNest--;
101608      *pnConsumed = (int)((zInput - z) + 1);
101609      return SQLITE_DONE;
101610    }
101611  }
101612
101613  /* See if we are dealing with a quoted phrase. If this is the case, then
101614  ** search for the closing quote and pass the whole string to getNextString()
101615  ** for processing. This is easy to do, as fts3 has no syntax for escaping
101616  ** a quote character embedded in a string.
101617  */
101618  if( *zInput=='"' ){
101619    for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
101620    *pnConsumed = (int)((zInput - z) + ii + 1);
101621    if( ii==nInput ){
101622      return SQLITE_ERROR;
101623    }
101624    return getNextString(pParse, &zInput[1], ii-1, ppExpr);
101625  }
101626
101627
101628  /* If control flows to this point, this must be a regular token, or
101629  ** the end of the input. Read a regular token using the sqlite3_tokenizer
101630  ** interface. Before doing so, figure out if there is an explicit
101631  ** column specifier for the token.
101632  **
101633  ** TODO: Strangely, it is not possible to associate a column specifier
101634  ** with a quoted phrase, only with a single token. Not sure if this was
101635  ** an implementation artifact or an intentional decision when fts3 was
101636  ** first implemented. Whichever it was, this module duplicates the
101637  ** limitation.
101638  */
101639  iCol = pParse->iDefaultCol;
101640  iColLen = 0;
101641  for(ii=0; ii<pParse->nCol; ii++){
101642    const char *zStr = pParse->azCol[ii];
101643    int nStr = (int)strlen(zStr);
101644    if( nInput>nStr && zInput[nStr]==':'
101645     && sqlite3_strnicmp(zStr, zInput, nStr)==0
101646    ){
101647      iCol = ii;
101648      iColLen = (int)((zInput - z) + nStr + 1);
101649      break;
101650    }
101651  }
101652  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
101653  *pnConsumed += iColLen;
101654  return rc;
101655}
101656
101657/*
101658** The argument is an Fts3Expr structure for a binary operator (any type
101659** except an FTSQUERY_PHRASE). Return an integer value representing the
101660** precedence of the operator. Lower values have a higher precedence (i.e.
101661** group more tightly). For example, in the C language, the == operator
101662** groups more tightly than ||, and would therefore have a higher precedence.
101663**
101664** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
101665** is defined), the order of the operators in precedence from highest to
101666** lowest is:
101667**
101668**   NEAR
101669**   NOT
101670**   AND (including implicit ANDs)
101671**   OR
101672**
101673** Note that when using the old query syntax, the OR operator has a higher
101674** precedence than the AND operator.
101675*/
101676static int opPrecedence(Fts3Expr *p){
101677  assert( p->eType!=FTSQUERY_PHRASE );
101678  if( sqlite3_fts3_enable_parentheses ){
101679    return p->eType;
101680  }else if( p->eType==FTSQUERY_NEAR ){
101681    return 1;
101682  }else if( p->eType==FTSQUERY_OR ){
101683    return 2;
101684  }
101685  assert( p->eType==FTSQUERY_AND );
101686  return 3;
101687}
101688
101689/*
101690** Argument ppHead contains a pointer to the current head of a query
101691** expression tree being parsed. pPrev is the expression node most recently
101692** inserted into the tree. This function adds pNew, which is always a binary
101693** operator node, into the expression tree based on the relative precedence
101694** of pNew and the existing nodes of the tree. This may result in the head
101695** of the tree changing, in which case *ppHead is set to the new root node.
101696*/
101697static void insertBinaryOperator(
101698  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
101699  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
101700  Fts3Expr *pNew           /* New binary node to insert into expression tree */
101701){
101702  Fts3Expr *pSplit = pPrev;
101703  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
101704    pSplit = pSplit->pParent;
101705  }
101706
101707  if( pSplit->pParent ){
101708    assert( pSplit->pParent->pRight==pSplit );
101709    pSplit->pParent->pRight = pNew;
101710    pNew->pParent = pSplit->pParent;
101711  }else{
101712    *ppHead = pNew;
101713  }
101714  pNew->pLeft = pSplit;
101715  pSplit->pParent = pNew;
101716}
101717
101718/*
101719** Parse the fts3 query expression found in buffer z, length n. This function
101720** returns either when the end of the buffer is reached or an unmatched
101721** closing bracket - ')' - is encountered.
101722**
101723** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
101724** parsed form of the expression and *pnConsumed is set to the number of
101725** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
101726** (out of memory error) or SQLITE_ERROR (parse error) is returned.
101727*/
101728static int fts3ExprParse(
101729  ParseContext *pParse,                   /* fts3 query parse context */
101730  const char *z, int n,                   /* Text of MATCH query */
101731  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
101732  int *pnConsumed                         /* OUT: Number of bytes consumed */
101733){
101734  Fts3Expr *pRet = 0;
101735  Fts3Expr *pPrev = 0;
101736  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
101737  int nIn = n;
101738  const char *zIn = z;
101739  int rc = SQLITE_OK;
101740  int isRequirePhrase = 1;
101741
101742  while( rc==SQLITE_OK ){
101743    Fts3Expr *p = 0;
101744    int nByte = 0;
101745    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
101746    if( rc==SQLITE_OK ){
101747      int isPhrase;
101748
101749      if( !sqlite3_fts3_enable_parentheses
101750       && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot
101751      ){
101752        /* Create an implicit NOT operator. */
101753        Fts3Expr *pNot = sqlite3_malloc(sizeof(Fts3Expr));
101754        if( !pNot ){
101755          sqlite3Fts3ExprFree(p);
101756          rc = SQLITE_NOMEM;
101757          goto exprparse_out;
101758        }
101759        memset(pNot, 0, sizeof(Fts3Expr));
101760        pNot->eType = FTSQUERY_NOT;
101761        pNot->pRight = p;
101762        if( pNotBranch ){
101763          pNot->pLeft = pNotBranch;
101764        }
101765        pNotBranch = pNot;
101766        p = pPrev;
101767      }else{
101768        int eType = p->eType;
101769        assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
101770        isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
101771
101772        /* The isRequirePhrase variable is set to true if a phrase or
101773        ** an expression contained in parenthesis is required. If a
101774        ** binary operator (AND, OR, NOT or NEAR) is encounted when
101775        ** isRequirePhrase is set, this is a syntax error.
101776        */
101777        if( !isPhrase && isRequirePhrase ){
101778          sqlite3Fts3ExprFree(p);
101779          rc = SQLITE_ERROR;
101780          goto exprparse_out;
101781        }
101782
101783        if( isPhrase && !isRequirePhrase ){
101784          /* Insert an implicit AND operator. */
101785          Fts3Expr *pAnd;
101786          assert( pRet && pPrev );
101787          pAnd = sqlite3_malloc(sizeof(Fts3Expr));
101788          if( !pAnd ){
101789            sqlite3Fts3ExprFree(p);
101790            rc = SQLITE_NOMEM;
101791            goto exprparse_out;
101792          }
101793          memset(pAnd, 0, sizeof(Fts3Expr));
101794          pAnd->eType = FTSQUERY_AND;
101795          insertBinaryOperator(&pRet, pPrev, pAnd);
101796          pPrev = pAnd;
101797        }
101798
101799        /* This test catches attempts to make either operand of a NEAR
101800        ** operator something other than a phrase. For example, either of
101801        ** the following:
101802        **
101803        **    (bracketed expression) NEAR phrase
101804        **    phrase NEAR (bracketed expression)
101805        **
101806        ** Return an error in either case.
101807        */
101808        if( pPrev && (
101809            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
101810         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
101811        )){
101812          sqlite3Fts3ExprFree(p);
101813          rc = SQLITE_ERROR;
101814          goto exprparse_out;
101815        }
101816
101817        if( isPhrase ){
101818          if( pRet ){
101819            assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
101820            pPrev->pRight = p;
101821            p->pParent = pPrev;
101822          }else{
101823            pRet = p;
101824          }
101825        }else{
101826          insertBinaryOperator(&pRet, pPrev, p);
101827        }
101828        isRequirePhrase = !isPhrase;
101829      }
101830      assert( nByte>0 );
101831    }
101832    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
101833    nIn -= nByte;
101834    zIn += nByte;
101835    pPrev = p;
101836  }
101837
101838  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
101839    rc = SQLITE_ERROR;
101840  }
101841
101842  if( rc==SQLITE_DONE ){
101843    rc = SQLITE_OK;
101844    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
101845      if( !pRet ){
101846        rc = SQLITE_ERROR;
101847      }else{
101848        Fts3Expr *pIter = pNotBranch;
101849        while( pIter->pLeft ){
101850          pIter = pIter->pLeft;
101851        }
101852        pIter->pLeft = pRet;
101853        pRet = pNotBranch;
101854      }
101855    }
101856  }
101857  *pnConsumed = n - nIn;
101858
101859exprparse_out:
101860  if( rc!=SQLITE_OK ){
101861    sqlite3Fts3ExprFree(pRet);
101862    sqlite3Fts3ExprFree(pNotBranch);
101863    pRet = 0;
101864  }
101865  *ppExpr = pRet;
101866  return rc;
101867}
101868
101869/*
101870** Parameters z and n contain a pointer to and length of a buffer containing
101871** an fts3 query expression, respectively. This function attempts to parse the
101872** query expression and create a tree of Fts3Expr structures representing the
101873** parsed expression. If successful, *ppExpr is set to point to the head
101874** of the parsed expression tree and SQLITE_OK is returned. If an error
101875** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
101876** error) is returned and *ppExpr is set to 0.
101877**
101878** If parameter n is a negative number, then z is assumed to point to a
101879** nul-terminated string and the length is determined using strlen().
101880**
101881** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
101882** use to normalize query tokens while parsing the expression. The azCol[]
101883** array, which is assumed to contain nCol entries, should contain the names
101884** of each column in the target fts3 table, in order from left to right.
101885** Column names must be nul-terminated strings.
101886**
101887** The iDefaultCol parameter should be passed the index of the table column
101888** that appears on the left-hand-side of the MATCH operator (the default
101889** column to match against for tokens for which a column name is not explicitly
101890** specified as part of the query string), or -1 if tokens may by default
101891** match any table column.
101892*/
101893SQLITE_PRIVATE int sqlite3Fts3ExprParse(
101894  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
101895  char **azCol,                       /* Array of column names for fts3 table */
101896  int nCol,                           /* Number of entries in azCol[] */
101897  int iDefaultCol,                    /* Default column to query */
101898  const char *z, int n,               /* Text of MATCH query */
101899  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
101900){
101901  int nParsed;
101902  int rc;
101903  ParseContext sParse;
101904  sParse.pTokenizer = pTokenizer;
101905  sParse.azCol = (const char **)azCol;
101906  sParse.nCol = nCol;
101907  sParse.iDefaultCol = iDefaultCol;
101908  sParse.nNest = 0;
101909  if( z==0 ){
101910    *ppExpr = 0;
101911    return SQLITE_OK;
101912  }
101913  if( n<0 ){
101914    n = (int)strlen(z);
101915  }
101916  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
101917
101918  /* Check for mismatched parenthesis */
101919  if( rc==SQLITE_OK && sParse.nNest ){
101920    rc = SQLITE_ERROR;
101921    sqlite3Fts3ExprFree(*ppExpr);
101922    *ppExpr = 0;
101923  }
101924
101925  return rc;
101926}
101927
101928/*
101929** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
101930*/
101931SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
101932  if( p ){
101933    sqlite3Fts3ExprFree(p->pLeft);
101934    sqlite3Fts3ExprFree(p->pRight);
101935    sqlite3_free(p->aDoclist);
101936    sqlite3_free(p);
101937  }
101938}
101939
101940/****************************************************************************
101941*****************************************************************************
101942** Everything after this point is just test code.
101943*/
101944
101945#ifdef SQLITE_TEST
101946
101947
101948/*
101949** Function to query the hash-table of tokenizers (see README.tokenizers).
101950*/
101951static int queryTestTokenizer(
101952  sqlite3 *db,
101953  const char *zName,
101954  const sqlite3_tokenizer_module **pp
101955){
101956  int rc;
101957  sqlite3_stmt *pStmt;
101958  const char zSql[] = "SELECT fts3_tokenizer(?)";
101959
101960  *pp = 0;
101961  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
101962  if( rc!=SQLITE_OK ){
101963    return rc;
101964  }
101965
101966  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
101967  if( SQLITE_ROW==sqlite3_step(pStmt) ){
101968    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
101969      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
101970    }
101971  }
101972
101973  return sqlite3_finalize(pStmt);
101974}
101975
101976/*
101977** This function is part of the test interface for the query parser. It
101978** writes a text representation of the query expression pExpr into the
101979** buffer pointed to by argument zBuf. It is assumed that zBuf is large
101980** enough to store the required text representation.
101981*/
101982static void exprToString(Fts3Expr *pExpr, char *zBuf){
101983  switch( pExpr->eType ){
101984    case FTSQUERY_PHRASE: {
101985      Fts3Phrase *pPhrase = pExpr->pPhrase;
101986      int i;
101987      zBuf += sprintf(zBuf, "PHRASE %d %d", pPhrase->iColumn, pPhrase->isNot);
101988      for(i=0; i<pPhrase->nToken; i++){
101989        zBuf += sprintf(zBuf," %.*s",pPhrase->aToken[i].n,pPhrase->aToken[i].z);
101990        zBuf += sprintf(zBuf,"%s", (pPhrase->aToken[i].isPrefix?"+":""));
101991      }
101992      return;
101993    }
101994
101995    case FTSQUERY_NEAR:
101996      zBuf += sprintf(zBuf, "NEAR/%d ", pExpr->nNear);
101997      break;
101998    case FTSQUERY_NOT:
101999      zBuf += sprintf(zBuf, "NOT ");
102000      break;
102001    case FTSQUERY_AND:
102002      zBuf += sprintf(zBuf, "AND ");
102003      break;
102004    case FTSQUERY_OR:
102005      zBuf += sprintf(zBuf, "OR ");
102006      break;
102007  }
102008
102009  zBuf += sprintf(zBuf, "{");
102010  exprToString(pExpr->pLeft, zBuf);
102011  zBuf += strlen(zBuf);
102012  zBuf += sprintf(zBuf, "} ");
102013
102014  zBuf += sprintf(zBuf, "{");
102015  exprToString(pExpr->pRight, zBuf);
102016  zBuf += strlen(zBuf);
102017  zBuf += sprintf(zBuf, "}");
102018}
102019
102020/*
102021** This is the implementation of a scalar SQL function used to test the
102022** expression parser. It should be called as follows:
102023**
102024**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
102025**
102026** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
102027** to parse the query expression (see README.tokenizers). The second argument
102028** is the query expression to parse. Each subsequent argument is the name
102029** of a column of the fts3 table that the query expression may refer to.
102030** For example:
102031**
102032**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
102033*/
102034static void fts3ExprTest(
102035  sqlite3_context *context,
102036  int argc,
102037  sqlite3_value **argv
102038){
102039  sqlite3_tokenizer_module const *pModule = 0;
102040  sqlite3_tokenizer *pTokenizer = 0;
102041  int rc;
102042  char **azCol = 0;
102043  const char *zExpr;
102044  int nExpr;
102045  int nCol;
102046  int ii;
102047  Fts3Expr *pExpr;
102048  sqlite3 *db = sqlite3_context_db_handle(context);
102049
102050  if( argc<3 ){
102051    sqlite3_result_error(context,
102052        "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
102053    );
102054    return;
102055  }
102056
102057  rc = queryTestTokenizer(db,
102058                          (const char *)sqlite3_value_text(argv[0]), &pModule);
102059  if( rc==SQLITE_NOMEM ){
102060    sqlite3_result_error_nomem(context);
102061    goto exprtest_out;
102062  }else if( !pModule ){
102063    sqlite3_result_error(context, "No such tokenizer module", -1);
102064    goto exprtest_out;
102065  }
102066
102067  rc = pModule->xCreate(0, 0, &pTokenizer);
102068  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
102069  if( rc==SQLITE_NOMEM ){
102070    sqlite3_result_error_nomem(context);
102071    goto exprtest_out;
102072  }
102073  pTokenizer->pModule = pModule;
102074
102075  zExpr = (const char *)sqlite3_value_text(argv[1]);
102076  nExpr = sqlite3_value_bytes(argv[1]);
102077  nCol = argc-2;
102078  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
102079  if( !azCol ){
102080    sqlite3_result_error_nomem(context);
102081    goto exprtest_out;
102082  }
102083  for(ii=0; ii<nCol; ii++){
102084    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
102085  }
102086
102087  rc = sqlite3Fts3ExprParse(
102088      pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
102089  );
102090  if( rc==SQLITE_NOMEM ){
102091    sqlite3_result_error_nomem(context);
102092    goto exprtest_out;
102093  }else if( rc==SQLITE_OK ){
102094    char zBuf[4096];
102095    exprToString(pExpr, zBuf);
102096    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
102097    sqlite3Fts3ExprFree(pExpr);
102098  }else{
102099    sqlite3_result_error(context, "Error parsing expression", -1);
102100  }
102101
102102exprtest_out:
102103  if( pModule && pTokenizer ){
102104    rc = pModule->xDestroy(pTokenizer);
102105  }
102106  sqlite3_free(azCol);
102107}
102108
102109/*
102110** Register the query expression parser test function fts3_exprtest()
102111** with database connection db.
102112*/
102113SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
102114  return sqlite3_create_function(
102115      db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
102116  );
102117}
102118
102119#endif
102120#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
102121
102122/************** End of fts3_expr.c *******************************************/
102123/************** Begin file fts3_hash.c ***************************************/
102124/*
102125** 2001 September 22
102126**
102127** The author disclaims copyright to this source code.  In place of
102128** a legal notice, here is a blessing:
102129**
102130**    May you do good and not evil.
102131**    May you find forgiveness for yourself and forgive others.
102132**    May you share freely, never taking more than you give.
102133**
102134*************************************************************************
102135** This is the implementation of generic hash-tables used in SQLite.
102136** We've modified it slightly to serve as a standalone hash table
102137** implementation for the full-text indexing module.
102138*/
102139
102140/*
102141** The code in this file is only compiled if:
102142**
102143**     * The FTS3 module is being built as an extension
102144**       (in which case SQLITE_CORE is not defined), or
102145**
102146**     * The FTS3 module is being built into the core of
102147**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
102148*/
102149#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
102150
102151
102152
102153/*
102154** Malloc and Free functions
102155*/
102156static void *fts3HashMalloc(int n){
102157  void *p = sqlite3_malloc(n);
102158  if( p ){
102159    memset(p, 0, n);
102160  }
102161  return p;
102162}
102163static void fts3HashFree(void *p){
102164  sqlite3_free(p);
102165}
102166
102167/* Turn bulk memory into a hash table object by initializing the
102168** fields of the Hash structure.
102169**
102170** "pNew" is a pointer to the hash table that is to be initialized.
102171** keyClass is one of the constants
102172** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
102173** determines what kind of key the hash table will use.  "copyKey" is
102174** true if the hash table should make its own private copy of keys and
102175** false if it should just use the supplied pointer.
102176*/
102177SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
102178  assert( pNew!=0 );
102179  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
102180  pNew->keyClass = keyClass;
102181  pNew->copyKey = copyKey;
102182  pNew->first = 0;
102183  pNew->count = 0;
102184  pNew->htsize = 0;
102185  pNew->ht = 0;
102186}
102187
102188/* Remove all entries from a hash table.  Reclaim all memory.
102189** Call this routine to delete a hash table or to reset a hash table
102190** to the empty state.
102191*/
102192SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
102193  Fts3HashElem *elem;         /* For looping over all elements of the table */
102194
102195  assert( pH!=0 );
102196  elem = pH->first;
102197  pH->first = 0;
102198  fts3HashFree(pH->ht);
102199  pH->ht = 0;
102200  pH->htsize = 0;
102201  while( elem ){
102202    Fts3HashElem *next_elem = elem->next;
102203    if( pH->copyKey && elem->pKey ){
102204      fts3HashFree(elem->pKey);
102205    }
102206    fts3HashFree(elem);
102207    elem = next_elem;
102208  }
102209  pH->count = 0;
102210}
102211
102212/*
102213** Hash and comparison functions when the mode is FTS3_HASH_STRING
102214*/
102215static int fts3StrHash(const void *pKey, int nKey){
102216  const char *z = (const char *)pKey;
102217  int h = 0;
102218  if( nKey<=0 ) nKey = (int) strlen(z);
102219  while( nKey > 0  ){
102220    h = (h<<3) ^ h ^ *z++;
102221    nKey--;
102222  }
102223  return h & 0x7fffffff;
102224}
102225static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
102226  if( n1!=n2 ) return 1;
102227  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
102228}
102229
102230/*
102231** Hash and comparison functions when the mode is FTS3_HASH_BINARY
102232*/
102233static int fts3BinHash(const void *pKey, int nKey){
102234  int h = 0;
102235  const char *z = (const char *)pKey;
102236  while( nKey-- > 0 ){
102237    h = (h<<3) ^ h ^ *(z++);
102238  }
102239  return h & 0x7fffffff;
102240}
102241static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
102242  if( n1!=n2 ) return 1;
102243  return memcmp(pKey1,pKey2,n1);
102244}
102245
102246/*
102247** Return a pointer to the appropriate hash function given the key class.
102248**
102249** The C syntax in this function definition may be unfamilar to some
102250** programmers, so we provide the following additional explanation:
102251**
102252** The name of the function is "ftsHashFunction".  The function takes a
102253** single parameter "keyClass".  The return value of ftsHashFunction()
102254** is a pointer to another function.  Specifically, the return value
102255** of ftsHashFunction() is a pointer to a function that takes two parameters
102256** with types "const void*" and "int" and returns an "int".
102257*/
102258static int (*ftsHashFunction(int keyClass))(const void*,int){
102259  if( keyClass==FTS3_HASH_STRING ){
102260    return &fts3StrHash;
102261  }else{
102262    assert( keyClass==FTS3_HASH_BINARY );
102263    return &fts3BinHash;
102264  }
102265}
102266
102267/*
102268** Return a pointer to the appropriate hash function given the key class.
102269**
102270** For help in interpreted the obscure C code in the function definition,
102271** see the header comment on the previous function.
102272*/
102273static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
102274  if( keyClass==FTS3_HASH_STRING ){
102275    return &fts3StrCompare;
102276  }else{
102277    assert( keyClass==FTS3_HASH_BINARY );
102278    return &fts3BinCompare;
102279  }
102280}
102281
102282/* Link an element into the hash table
102283*/
102284static void fts3HashInsertElement(
102285  Fts3Hash *pH,            /* The complete hash table */
102286  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
102287  Fts3HashElem *pNew       /* The element to be inserted */
102288){
102289  Fts3HashElem *pHead;     /* First element already in pEntry */
102290  pHead = pEntry->chain;
102291  if( pHead ){
102292    pNew->next = pHead;
102293    pNew->prev = pHead->prev;
102294    if( pHead->prev ){ pHead->prev->next = pNew; }
102295    else             { pH->first = pNew; }
102296    pHead->prev = pNew;
102297  }else{
102298    pNew->next = pH->first;
102299    if( pH->first ){ pH->first->prev = pNew; }
102300    pNew->prev = 0;
102301    pH->first = pNew;
102302  }
102303  pEntry->count++;
102304  pEntry->chain = pNew;
102305}
102306
102307
102308/* Resize the hash table so that it cantains "new_size" buckets.
102309** "new_size" must be a power of 2.  The hash table might fail
102310** to resize if sqliteMalloc() fails.
102311**
102312** Return non-zero if a memory allocation error occurs.
102313*/
102314static int fts3Rehash(Fts3Hash *pH, int new_size){
102315  struct _fts3ht *new_ht;          /* The new hash table */
102316  Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
102317  int (*xHash)(const void*,int);   /* The hash function */
102318
102319  assert( (new_size & (new_size-1))==0 );
102320  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
102321  if( new_ht==0 ) return 1;
102322  fts3HashFree(pH->ht);
102323  pH->ht = new_ht;
102324  pH->htsize = new_size;
102325  xHash = ftsHashFunction(pH->keyClass);
102326  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
102327    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
102328    next_elem = elem->next;
102329    fts3HashInsertElement(pH, &new_ht[h], elem);
102330  }
102331  return 0;
102332}
102333
102334/* This function (for internal use only) locates an element in an
102335** hash table that matches the given key.  The hash for this key has
102336** already been computed and is passed as the 4th parameter.
102337*/
102338static Fts3HashElem *fts3FindElementByHash(
102339  const Fts3Hash *pH, /* The pH to be searched */
102340  const void *pKey,   /* The key we are searching for */
102341  int nKey,
102342  int h               /* The hash for this key. */
102343){
102344  Fts3HashElem *elem;            /* Used to loop thru the element list */
102345  int count;                     /* Number of elements left to test */
102346  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
102347
102348  if( pH->ht ){
102349    struct _fts3ht *pEntry = &pH->ht[h];
102350    elem = pEntry->chain;
102351    count = pEntry->count;
102352    xCompare = ftsCompareFunction(pH->keyClass);
102353    while( count-- && elem ){
102354      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
102355        return elem;
102356      }
102357      elem = elem->next;
102358    }
102359  }
102360  return 0;
102361}
102362
102363/* Remove a single entry from the hash table given a pointer to that
102364** element and a hash on the element's key.
102365*/
102366static void fts3RemoveElementByHash(
102367  Fts3Hash *pH,         /* The pH containing "elem" */
102368  Fts3HashElem* elem,   /* The element to be removed from the pH */
102369  int h                 /* Hash value for the element */
102370){
102371  struct _fts3ht *pEntry;
102372  if( elem->prev ){
102373    elem->prev->next = elem->next;
102374  }else{
102375    pH->first = elem->next;
102376  }
102377  if( elem->next ){
102378    elem->next->prev = elem->prev;
102379  }
102380  pEntry = &pH->ht[h];
102381  if( pEntry->chain==elem ){
102382    pEntry->chain = elem->next;
102383  }
102384  pEntry->count--;
102385  if( pEntry->count<=0 ){
102386    pEntry->chain = 0;
102387  }
102388  if( pH->copyKey && elem->pKey ){
102389    fts3HashFree(elem->pKey);
102390  }
102391  fts3HashFree( elem );
102392  pH->count--;
102393  if( pH->count<=0 ){
102394    assert( pH->first==0 );
102395    assert( pH->count==0 );
102396    fts3HashClear(pH);
102397  }
102398}
102399
102400SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
102401  const Fts3Hash *pH,
102402  const void *pKey,
102403  int nKey
102404){
102405  int h;                          /* A hash on key */
102406  int (*xHash)(const void*,int);  /* The hash function */
102407
102408  if( pH==0 || pH->ht==0 ) return 0;
102409  xHash = ftsHashFunction(pH->keyClass);
102410  assert( xHash!=0 );
102411  h = (*xHash)(pKey,nKey);
102412  assert( (pH->htsize & (pH->htsize-1))==0 );
102413  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
102414}
102415
102416/*
102417** Attempt to locate an element of the hash table pH with a key
102418** that matches pKey,nKey.  Return the data for this element if it is
102419** found, or NULL if there is no match.
102420*/
102421SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
102422  Fts3HashElem *pElem;            /* The element that matches key (if any) */
102423
102424  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
102425  return pElem ? pElem->data : 0;
102426}
102427
102428/* Insert an element into the hash table pH.  The key is pKey,nKey
102429** and the data is "data".
102430**
102431** If no element exists with a matching key, then a new
102432** element is created.  A copy of the key is made if the copyKey
102433** flag is set.  NULL is returned.
102434**
102435** If another element already exists with the same key, then the
102436** new data replaces the old data and the old data is returned.
102437** The key is not copied in this instance.  If a malloc fails, then
102438** the new data is returned and the hash table is unchanged.
102439**
102440** If the "data" parameter to this function is NULL, then the
102441** element corresponding to "key" is removed from the hash table.
102442*/
102443SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
102444  Fts3Hash *pH,        /* The hash table to insert into */
102445  const void *pKey,    /* The key */
102446  int nKey,            /* Number of bytes in the key */
102447  void *data           /* The data */
102448){
102449  int hraw;                 /* Raw hash value of the key */
102450  int h;                    /* the hash of the key modulo hash table size */
102451  Fts3HashElem *elem;       /* Used to loop thru the element list */
102452  Fts3HashElem *new_elem;   /* New element added to the pH */
102453  int (*xHash)(const void*,int);  /* The hash function */
102454
102455  assert( pH!=0 );
102456  xHash = ftsHashFunction(pH->keyClass);
102457  assert( xHash!=0 );
102458  hraw = (*xHash)(pKey, nKey);
102459  assert( (pH->htsize & (pH->htsize-1))==0 );
102460  h = hraw & (pH->htsize-1);
102461  elem = fts3FindElementByHash(pH,pKey,nKey,h);
102462  if( elem ){
102463    void *old_data = elem->data;
102464    if( data==0 ){
102465      fts3RemoveElementByHash(pH,elem,h);
102466    }else{
102467      elem->data = data;
102468    }
102469    return old_data;
102470  }
102471  if( data==0 ) return 0;
102472  if( (pH->htsize==0 && fts3Rehash(pH,8))
102473   || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
102474  ){
102475    pH->count = 0;
102476    return data;
102477  }
102478  assert( pH->htsize>0 );
102479  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
102480  if( new_elem==0 ) return data;
102481  if( pH->copyKey && pKey!=0 ){
102482    new_elem->pKey = fts3HashMalloc( nKey );
102483    if( new_elem->pKey==0 ){
102484      fts3HashFree(new_elem);
102485      return data;
102486    }
102487    memcpy((void*)new_elem->pKey, pKey, nKey);
102488  }else{
102489    new_elem->pKey = (void*)pKey;
102490  }
102491  new_elem->nKey = nKey;
102492  pH->count++;
102493  assert( pH->htsize>0 );
102494  assert( (pH->htsize & (pH->htsize-1))==0 );
102495  h = hraw & (pH->htsize-1);
102496  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
102497  new_elem->data = data;
102498  return 0;
102499}
102500
102501#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
102502
102503/************** End of fts3_hash.c *******************************************/
102504/************** Begin file fts3_porter.c *************************************/
102505/*
102506** 2006 September 30
102507**
102508** The author disclaims copyright to this source code.  In place of
102509** a legal notice, here is a blessing:
102510**
102511**    May you do good and not evil.
102512**    May you find forgiveness for yourself and forgive others.
102513**    May you share freely, never taking more than you give.
102514**
102515*************************************************************************
102516** Implementation of the full-text-search tokenizer that implements
102517** a Porter stemmer.
102518*/
102519
102520/*
102521** The code in this file is only compiled if:
102522**
102523**     * The FTS3 module is being built as an extension
102524**       (in which case SQLITE_CORE is not defined), or
102525**
102526**     * The FTS3 module is being built into the core of
102527**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
102528*/
102529#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
102530
102531
102532
102533
102534/*
102535** Class derived from sqlite3_tokenizer
102536*/
102537typedef struct porter_tokenizer {
102538  sqlite3_tokenizer base;      /* Base class */
102539} porter_tokenizer;
102540
102541/*
102542** Class derived from sqlit3_tokenizer_cursor
102543*/
102544typedef struct porter_tokenizer_cursor {
102545  sqlite3_tokenizer_cursor base;
102546  const char *zInput;          /* input we are tokenizing */
102547  int nInput;                  /* size of the input */
102548  int iOffset;                 /* current position in zInput */
102549  int iToken;                  /* index of next token to be returned */
102550  char *zToken;                /* storage for current token */
102551  int nAllocated;              /* space allocated to zToken buffer */
102552} porter_tokenizer_cursor;
102553
102554
102555/*
102556** Create a new tokenizer instance.
102557*/
102558static int porterCreate(
102559  int argc, const char * const *argv,
102560  sqlite3_tokenizer **ppTokenizer
102561){
102562  porter_tokenizer *t;
102563
102564  UNUSED_PARAMETER(argc);
102565  UNUSED_PARAMETER(argv);
102566
102567  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
102568  if( t==NULL ) return SQLITE_NOMEM;
102569  memset(t, 0, sizeof(*t));
102570  *ppTokenizer = &t->base;
102571  return SQLITE_OK;
102572}
102573
102574/*
102575** Destroy a tokenizer
102576*/
102577static int porterDestroy(sqlite3_tokenizer *pTokenizer){
102578  sqlite3_free(pTokenizer);
102579  return SQLITE_OK;
102580}
102581
102582/*
102583** Prepare to begin tokenizing a particular string.  The input
102584** string to be tokenized is zInput[0..nInput-1].  A cursor
102585** used to incrementally tokenize this string is returned in
102586** *ppCursor.
102587*/
102588static int porterOpen(
102589  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
102590  const char *zInput, int nInput,        /* String to be tokenized */
102591  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
102592){
102593  porter_tokenizer_cursor *c;
102594
102595  UNUSED_PARAMETER(pTokenizer);
102596
102597  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
102598  if( c==NULL ) return SQLITE_NOMEM;
102599
102600  c->zInput = zInput;
102601  if( zInput==0 ){
102602    c->nInput = 0;
102603  }else if( nInput<0 ){
102604    c->nInput = (int)strlen(zInput);
102605  }else{
102606    c->nInput = nInput;
102607  }
102608  c->iOffset = 0;                 /* start tokenizing at the beginning */
102609  c->iToken = 0;
102610  c->zToken = NULL;               /* no space allocated, yet. */
102611  c->nAllocated = 0;
102612
102613  *ppCursor = &c->base;
102614  return SQLITE_OK;
102615}
102616
102617/*
102618** Close a tokenization cursor previously opened by a call to
102619** porterOpen() above.
102620*/
102621static int porterClose(sqlite3_tokenizer_cursor *pCursor){
102622  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
102623  sqlite3_free(c->zToken);
102624  sqlite3_free(c);
102625  return SQLITE_OK;
102626}
102627/*
102628** Vowel or consonant
102629*/
102630static const char cType[] = {
102631   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
102632   1, 1, 1, 2, 1
102633};
102634
102635/*
102636** isConsonant() and isVowel() determine if their first character in
102637** the string they point to is a consonant or a vowel, according
102638** to Porter ruls.
102639**
102640** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
102641** 'Y' is a consonant unless it follows another consonant,
102642** in which case it is a vowel.
102643**
102644** In these routine, the letters are in reverse order.  So the 'y' rule
102645** is that 'y' is a consonant unless it is followed by another
102646** consonent.
102647*/
102648static int isVowel(const char*);
102649static int isConsonant(const char *z){
102650  int j;
102651  char x = *z;
102652  if( x==0 ) return 0;
102653  assert( x>='a' && x<='z' );
102654  j = cType[x-'a'];
102655  if( j<2 ) return j;
102656  return z[1]==0 || isVowel(z + 1);
102657}
102658static int isVowel(const char *z){
102659  int j;
102660  char x = *z;
102661  if( x==0 ) return 0;
102662  assert( x>='a' && x<='z' );
102663  j = cType[x-'a'];
102664  if( j<2 ) return 1-j;
102665  return isConsonant(z + 1);
102666}
102667
102668/*
102669** Let any sequence of one or more vowels be represented by V and let
102670** C be sequence of one or more consonants.  Then every word can be
102671** represented as:
102672**
102673**           [C] (VC){m} [V]
102674**
102675** In prose:  A word is an optional consonant followed by zero or
102676** vowel-consonant pairs followed by an optional vowel.  "m" is the
102677** number of vowel consonant pairs.  This routine computes the value
102678** of m for the first i bytes of a word.
102679**
102680** Return true if the m-value for z is 1 or more.  In other words,
102681** return true if z contains at least one vowel that is followed
102682** by a consonant.
102683**
102684** In this routine z[] is in reverse order.  So we are really looking
102685** for an instance of of a consonant followed by a vowel.
102686*/
102687static int m_gt_0(const char *z){
102688  while( isVowel(z) ){ z++; }
102689  if( *z==0 ) return 0;
102690  while( isConsonant(z) ){ z++; }
102691  return *z!=0;
102692}
102693
102694/* Like mgt0 above except we are looking for a value of m which is
102695** exactly 1
102696*/
102697static int m_eq_1(const char *z){
102698  while( isVowel(z) ){ z++; }
102699  if( *z==0 ) return 0;
102700  while( isConsonant(z) ){ z++; }
102701  if( *z==0 ) return 0;
102702  while( isVowel(z) ){ z++; }
102703  if( *z==0 ) return 1;
102704  while( isConsonant(z) ){ z++; }
102705  return *z==0;
102706}
102707
102708/* Like mgt0 above except we are looking for a value of m>1 instead
102709** or m>0
102710*/
102711static int m_gt_1(const char *z){
102712  while( isVowel(z) ){ z++; }
102713  if( *z==0 ) return 0;
102714  while( isConsonant(z) ){ z++; }
102715  if( *z==0 ) return 0;
102716  while( isVowel(z) ){ z++; }
102717  if( *z==0 ) return 0;
102718  while( isConsonant(z) ){ z++; }
102719  return *z!=0;
102720}
102721
102722/*
102723** Return TRUE if there is a vowel anywhere within z[0..n-1]
102724*/
102725static int hasVowel(const char *z){
102726  while( isConsonant(z) ){ z++; }
102727  return *z!=0;
102728}
102729
102730/*
102731** Return TRUE if the word ends in a double consonant.
102732**
102733** The text is reversed here. So we are really looking at
102734** the first two characters of z[].
102735*/
102736static int doubleConsonant(const char *z){
102737  return isConsonant(z) && z[0]==z[1];
102738}
102739
102740/*
102741** Return TRUE if the word ends with three letters which
102742** are consonant-vowel-consonent and where the final consonant
102743** is not 'w', 'x', or 'y'.
102744**
102745** The word is reversed here.  So we are really checking the
102746** first three letters and the first one cannot be in [wxy].
102747*/
102748static int star_oh(const char *z){
102749  return
102750    isConsonant(z) &&
102751    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
102752    isVowel(z+1) &&
102753    isConsonant(z+2);
102754}
102755
102756/*
102757** If the word ends with zFrom and xCond() is true for the stem
102758** of the word that preceeds the zFrom ending, then change the
102759** ending to zTo.
102760**
102761** The input word *pz and zFrom are both in reverse order.  zTo
102762** is in normal order.
102763**
102764** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
102765** match.  Not that TRUE is returned even if xCond() fails and
102766** no substitution occurs.
102767*/
102768static int stem(
102769  char **pz,             /* The word being stemmed (Reversed) */
102770  const char *zFrom,     /* If the ending matches this... (Reversed) */
102771  const char *zTo,       /* ... change the ending to this (not reversed) */
102772  int (*xCond)(const char*)   /* Condition that must be true */
102773){
102774  char *z = *pz;
102775  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
102776  if( *zFrom!=0 ) return 0;
102777  if( xCond && !xCond(z) ) return 1;
102778  while( *zTo ){
102779    *(--z) = *(zTo++);
102780  }
102781  *pz = z;
102782  return 1;
102783}
102784
102785/*
102786** This is the fallback stemmer used when the porter stemmer is
102787** inappropriate.  The input word is copied into the output with
102788** US-ASCII case folding.  If the input word is too long (more
102789** than 20 bytes if it contains no digits or more than 6 bytes if
102790** it contains digits) then word is truncated to 20 or 6 bytes
102791** by taking 10 or 3 bytes from the beginning and end.
102792*/
102793static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
102794  int i, mx, j;
102795  int hasDigit = 0;
102796  for(i=0; i<nIn; i++){
102797    char c = zIn[i];
102798    if( c>='A' && c<='Z' ){
102799      zOut[i] = c - 'A' + 'a';
102800    }else{
102801      if( c>='0' && c<='9' ) hasDigit = 1;
102802      zOut[i] = c;
102803    }
102804  }
102805  mx = hasDigit ? 3 : 10;
102806  if( nIn>mx*2 ){
102807    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
102808      zOut[j] = zOut[i];
102809    }
102810    i = j;
102811  }
102812  zOut[i] = 0;
102813  *pnOut = i;
102814}
102815
102816
102817/*
102818** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
102819** zOut is at least big enough to hold nIn bytes.  Write the actual
102820** size of the output word (exclusive of the '\0' terminator) into *pnOut.
102821**
102822** Any upper-case characters in the US-ASCII character set ([A-Z])
102823** are converted to lower case.  Upper-case UTF characters are
102824** unchanged.
102825**
102826** Words that are longer than about 20 bytes are stemmed by retaining
102827** a few bytes from the beginning and the end of the word.  If the
102828** word contains digits, 3 bytes are taken from the beginning and
102829** 3 bytes from the end.  For long words without digits, 10 bytes
102830** are taken from each end.  US-ASCII case folding still applies.
102831**
102832** If the input word contains not digits but does characters not
102833** in [a-zA-Z] then no stemming is attempted and this routine just
102834** copies the input into the input into the output with US-ASCII
102835** case folding.
102836**
102837** Stemming never increases the length of the word.  So there is
102838** no chance of overflowing the zOut buffer.
102839*/
102840static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
102841  int i, j;
102842  char zReverse[28];
102843  char *z, *z2;
102844  if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
102845    /* The word is too big or too small for the porter stemmer.
102846    ** Fallback to the copy stemmer */
102847    copy_stemmer(zIn, nIn, zOut, pnOut);
102848    return;
102849  }
102850  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
102851    char c = zIn[i];
102852    if( c>='A' && c<='Z' ){
102853      zReverse[j] = c + 'a' - 'A';
102854    }else if( c>='a' && c<='z' ){
102855      zReverse[j] = c;
102856    }else{
102857      /* The use of a character not in [a-zA-Z] means that we fallback
102858      ** to the copy stemmer */
102859      copy_stemmer(zIn, nIn, zOut, pnOut);
102860      return;
102861    }
102862  }
102863  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
102864  z = &zReverse[j+1];
102865
102866
102867  /* Step 1a */
102868  if( z[0]=='s' ){
102869    if(
102870     !stem(&z, "sess", "ss", 0) &&
102871     !stem(&z, "sei", "i", 0)  &&
102872     !stem(&z, "ss", "ss", 0)
102873    ){
102874      z++;
102875    }
102876  }
102877
102878  /* Step 1b */
102879  z2 = z;
102880  if( stem(&z, "dee", "ee", m_gt_0) ){
102881    /* Do nothing.  The work was all in the test */
102882  }else if(
102883     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
102884      && z!=z2
102885  ){
102886     if( stem(&z, "ta", "ate", 0) ||
102887         stem(&z, "lb", "ble", 0) ||
102888         stem(&z, "zi", "ize", 0) ){
102889       /* Do nothing.  The work was all in the test */
102890     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
102891       z++;
102892     }else if( m_eq_1(z) && star_oh(z) ){
102893       *(--z) = 'e';
102894     }
102895  }
102896
102897  /* Step 1c */
102898  if( z[0]=='y' && hasVowel(z+1) ){
102899    z[0] = 'i';
102900  }
102901
102902  /* Step 2 */
102903  switch( z[1] ){
102904   case 'a':
102905     stem(&z, "lanoita", "ate", m_gt_0) ||
102906     stem(&z, "lanoit", "tion", m_gt_0);
102907     break;
102908   case 'c':
102909     stem(&z, "icne", "ence", m_gt_0) ||
102910     stem(&z, "icna", "ance", m_gt_0);
102911     break;
102912   case 'e':
102913     stem(&z, "rezi", "ize", m_gt_0);
102914     break;
102915   case 'g':
102916     stem(&z, "igol", "log", m_gt_0);
102917     break;
102918   case 'l':
102919     stem(&z, "ilb", "ble", m_gt_0) ||
102920     stem(&z, "illa", "al", m_gt_0) ||
102921     stem(&z, "iltne", "ent", m_gt_0) ||
102922     stem(&z, "ile", "e", m_gt_0) ||
102923     stem(&z, "ilsuo", "ous", m_gt_0);
102924     break;
102925   case 'o':
102926     stem(&z, "noitazi", "ize", m_gt_0) ||
102927     stem(&z, "noita", "ate", m_gt_0) ||
102928     stem(&z, "rota", "ate", m_gt_0);
102929     break;
102930   case 's':
102931     stem(&z, "msila", "al", m_gt_0) ||
102932     stem(&z, "ssenevi", "ive", m_gt_0) ||
102933     stem(&z, "ssenluf", "ful", m_gt_0) ||
102934     stem(&z, "ssensuo", "ous", m_gt_0);
102935     break;
102936   case 't':
102937     stem(&z, "itila", "al", m_gt_0) ||
102938     stem(&z, "itivi", "ive", m_gt_0) ||
102939     stem(&z, "itilib", "ble", m_gt_0);
102940     break;
102941  }
102942
102943  /* Step 3 */
102944  switch( z[0] ){
102945   case 'e':
102946     stem(&z, "etaci", "ic", m_gt_0) ||
102947     stem(&z, "evita", "", m_gt_0)   ||
102948     stem(&z, "ezila", "al", m_gt_0);
102949     break;
102950   case 'i':
102951     stem(&z, "itici", "ic", m_gt_0);
102952     break;
102953   case 'l':
102954     stem(&z, "laci", "ic", m_gt_0) ||
102955     stem(&z, "luf", "", m_gt_0);
102956     break;
102957   case 's':
102958     stem(&z, "ssen", "", m_gt_0);
102959     break;
102960  }
102961
102962  /* Step 4 */
102963  switch( z[1] ){
102964   case 'a':
102965     if( z[0]=='l' && m_gt_1(z+2) ){
102966       z += 2;
102967     }
102968     break;
102969   case 'c':
102970     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
102971       z += 4;
102972     }
102973     break;
102974   case 'e':
102975     if( z[0]=='r' && m_gt_1(z+2) ){
102976       z += 2;
102977     }
102978     break;
102979   case 'i':
102980     if( z[0]=='c' && m_gt_1(z+2) ){
102981       z += 2;
102982     }
102983     break;
102984   case 'l':
102985     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
102986       z += 4;
102987     }
102988     break;
102989   case 'n':
102990     if( z[0]=='t' ){
102991       if( z[2]=='a' ){
102992         if( m_gt_1(z+3) ){
102993           z += 3;
102994         }
102995       }else if( z[2]=='e' ){
102996         stem(&z, "tneme", "", m_gt_1) ||
102997         stem(&z, "tnem", "", m_gt_1) ||
102998         stem(&z, "tne", "", m_gt_1);
102999       }
103000     }
103001     break;
103002   case 'o':
103003     if( z[0]=='u' ){
103004       if( m_gt_1(z+2) ){
103005         z += 2;
103006       }
103007     }else if( z[3]=='s' || z[3]=='t' ){
103008       stem(&z, "noi", "", m_gt_1);
103009     }
103010     break;
103011   case 's':
103012     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
103013       z += 3;
103014     }
103015     break;
103016   case 't':
103017     stem(&z, "eta", "", m_gt_1) ||
103018     stem(&z, "iti", "", m_gt_1);
103019     break;
103020   case 'u':
103021     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
103022       z += 3;
103023     }
103024     break;
103025   case 'v':
103026   case 'z':
103027     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
103028       z += 3;
103029     }
103030     break;
103031  }
103032
103033  /* Step 5a */
103034  if( z[0]=='e' ){
103035    if( m_gt_1(z+1) ){
103036      z++;
103037    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
103038      z++;
103039    }
103040  }
103041
103042  /* Step 5b */
103043  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
103044    z++;
103045  }
103046
103047  /* z[] is now the stemmed word in reverse order.  Flip it back
103048  ** around into forward order and return.
103049  */
103050  *pnOut = i = (int)strlen(z);
103051  zOut[i] = 0;
103052  while( *z ){
103053    zOut[--i] = *(z++);
103054  }
103055}
103056
103057/*
103058** Characters that can be part of a token.  We assume any character
103059** whose value is greater than 0x80 (any UTF character) can be
103060** part of a token.  In other words, delimiters all must have
103061** values of 0x7f or lower.
103062*/
103063static const char porterIdChar[] = {
103064/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
103065    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
103066    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
103067    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
103068    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
103069    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
103070};
103071#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
103072
103073/*
103074** Extract the next token from a tokenization cursor.  The cursor must
103075** have been opened by a prior call to porterOpen().
103076*/
103077static int porterNext(
103078  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
103079  const char **pzToken,               /* OUT: *pzToken is the token text */
103080  int *pnBytes,                       /* OUT: Number of bytes in token */
103081  int *piStartOffset,                 /* OUT: Starting offset of token */
103082  int *piEndOffset,                   /* OUT: Ending offset of token */
103083  int *piPosition                     /* OUT: Position integer of token */
103084){
103085  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
103086  const char *z = c->zInput;
103087
103088  while( c->iOffset<c->nInput ){
103089    int iStartOffset, ch;
103090
103091    /* Scan past delimiter characters */
103092    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
103093      c->iOffset++;
103094    }
103095
103096    /* Count non-delimiter characters. */
103097    iStartOffset = c->iOffset;
103098    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
103099      c->iOffset++;
103100    }
103101
103102    if( c->iOffset>iStartOffset ){
103103      int n = c->iOffset-iStartOffset;
103104      if( n>c->nAllocated ){
103105        c->nAllocated = n+20;
103106        c->zToken = sqlite3_realloc(c->zToken, c->nAllocated);
103107        if( c->zToken==NULL ) return SQLITE_NOMEM;
103108      }
103109      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
103110      *pzToken = c->zToken;
103111      *piStartOffset = iStartOffset;
103112      *piEndOffset = c->iOffset;
103113      *piPosition = c->iToken++;
103114      return SQLITE_OK;
103115    }
103116  }
103117  return SQLITE_DONE;
103118}
103119
103120/*
103121** The set of routines that implement the porter-stemmer tokenizer
103122*/
103123static const sqlite3_tokenizer_module porterTokenizerModule = {
103124  0,
103125  porterCreate,
103126  porterDestroy,
103127  porterOpen,
103128  porterClose,
103129  porterNext,
103130};
103131
103132/*
103133** Allocate a new porter tokenizer.  Return a pointer to the new
103134** tokenizer in *ppModule
103135*/
103136SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
103137  sqlite3_tokenizer_module const**ppModule
103138){
103139  *ppModule = &porterTokenizerModule;
103140}
103141
103142#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
103143
103144/************** End of fts3_porter.c *****************************************/
103145/************** Begin file fts3_tokenizer.c **********************************/
103146/*
103147** 2007 June 22
103148**
103149** The author disclaims copyright to this source code.  In place of
103150** a legal notice, here is a blessing:
103151**
103152**    May you do good and not evil.
103153**    May you find forgiveness for yourself and forgive others.
103154**    May you share freely, never taking more than you give.
103155**
103156******************************************************************************
103157**
103158** This is part of an SQLite module implementing full-text search.
103159** This particular file implements the generic tokenizer interface.
103160*/
103161
103162/*
103163** The code in this file is only compiled if:
103164**
103165**     * The FTS3 module is being built as an extension
103166**       (in which case SQLITE_CORE is not defined), or
103167**
103168**     * The FTS3 module is being built into the core of
103169**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
103170*/
103171#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
103172
103173#ifndef SQLITE_CORE
103174  SQLITE_EXTENSION_INIT1
103175#endif
103176
103177
103178/*
103179** Implementation of the SQL scalar function for accessing the underlying
103180** hash table. This function may be called as follows:
103181**
103182**   SELECT <function-name>(<key-name>);
103183**   SELECT <function-name>(<key-name>, <pointer>);
103184**
103185** where <function-name> is the name passed as the second argument
103186** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
103187**
103188** If the <pointer> argument is specified, it must be a blob value
103189** containing a pointer to be stored as the hash data corresponding
103190** to the string <key-name>. If <pointer> is not specified, then
103191** the string <key-name> must already exist in the has table. Otherwise,
103192** an error is returned.
103193**
103194** Whether or not the <pointer> argument is specified, the value returned
103195** is a blob containing the pointer stored as the hash data corresponding
103196** to string <key-name> (after the hash-table is updated, if applicable).
103197*/
103198static void scalarFunc(
103199  sqlite3_context *context,
103200  int argc,
103201  sqlite3_value **argv
103202){
103203  Fts3Hash *pHash;
103204  void *pPtr = 0;
103205  const unsigned char *zName;
103206  int nName;
103207
103208  assert( argc==1 || argc==2 );
103209
103210  pHash = (Fts3Hash *)sqlite3_user_data(context);
103211
103212  zName = sqlite3_value_text(argv[0]);
103213  nName = sqlite3_value_bytes(argv[0])+1;
103214
103215  if( argc==2 ){
103216    void *pOld;
103217    int n = sqlite3_value_bytes(argv[1]);
103218    if( n!=sizeof(pPtr) ){
103219      sqlite3_result_error(context, "argument type mismatch", -1);
103220      return;
103221    }
103222    pPtr = *(void **)sqlite3_value_blob(argv[1]);
103223    pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
103224    if( pOld==pPtr ){
103225      sqlite3_result_error(context, "out of memory", -1);
103226      return;
103227    }
103228  }else{
103229    pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
103230    if( !pPtr ){
103231      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
103232      sqlite3_result_error(context, zErr, -1);
103233      sqlite3_free(zErr);
103234      return;
103235    }
103236  }
103237
103238  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
103239}
103240
103241static int fts3IsIdChar(char c){
103242  static const char isFtsIdChar[] = {
103243      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
103244      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
103245      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
103246      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
103247      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
103248      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
103249      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
103250      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
103251  };
103252  return (c&0x80 || isFtsIdChar[(int)(c)]);
103253}
103254
103255SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
103256  const char *z1;
103257  const char *z2 = 0;
103258
103259  /* Find the start of the next token. */
103260  z1 = zStr;
103261  while( z2==0 ){
103262    char c = *z1;
103263    switch( c ){
103264      case '\0': return 0;        /* No more tokens here */
103265      case '\'':
103266      case '"':
103267      case '`': {
103268        z2 = z1;
103269        while( *++z2 && (*z2!=c || *++z2==c) );
103270        break;
103271      }
103272      case '[':
103273        z2 = &z1[1];
103274        while( *z2 && z2[0]!=']' ) z2++;
103275        if( *z2 ) z2++;
103276        break;
103277
103278      default:
103279        if( fts3IsIdChar(*z1) ){
103280          z2 = &z1[1];
103281          while( fts3IsIdChar(*z2) ) z2++;
103282        }else{
103283          z1++;
103284        }
103285    }
103286  }
103287
103288  *pn = (int)(z2-z1);
103289  return z1;
103290}
103291
103292SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
103293  Fts3Hash *pHash,                /* Tokenizer hash table */
103294  const char *zArg,               /* Possible tokenizer specification */
103295  sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
103296  const char **pzTokenizer,       /* OUT: Set to zArg if is tokenizer */
103297  char **pzErr                    /* OUT: Set to malloced error message */
103298){
103299  int rc;
103300  char *z = (char *)zArg;
103301  int n;
103302  char *zCopy;
103303  char *zEnd;                     /* Pointer to nul-term of zCopy */
103304  sqlite3_tokenizer_module *m;
103305
103306  if( !z ){
103307    zCopy = sqlite3_mprintf("simple");
103308  }else{
103309    if( sqlite3_strnicmp(z, "tokenize", 8) || fts3IsIdChar(z[8])){
103310      return SQLITE_OK;
103311    }
103312    zCopy = sqlite3_mprintf("%s", &z[8]);
103313    *pzTokenizer = zArg;
103314  }
103315  if( !zCopy ){
103316    return SQLITE_NOMEM;
103317  }
103318
103319  zEnd = &zCopy[strlen(zCopy)];
103320
103321  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
103322  z[n] = '\0';
103323  sqlite3Fts3Dequote(z);
103324
103325  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, z, (int)strlen(z)+1);
103326  if( !m ){
103327    *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
103328    rc = SQLITE_ERROR;
103329  }else{
103330    char const **aArg = 0;
103331    int iArg = 0;
103332    z = &z[n+1];
103333    while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
103334      int nNew = sizeof(char *)*(iArg+1);
103335      char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
103336      if( !aNew ){
103337        sqlite3_free(zCopy);
103338        sqlite3_free((void *)aArg);
103339        return SQLITE_NOMEM;
103340      }
103341      aArg = aNew;
103342      aArg[iArg++] = z;
103343      z[n] = '\0';
103344      sqlite3Fts3Dequote(z);
103345      z = &z[n+1];
103346    }
103347    rc = m->xCreate(iArg, aArg, ppTok);
103348    assert( rc!=SQLITE_OK || *ppTok );
103349    if( rc!=SQLITE_OK ){
103350      *pzErr = sqlite3_mprintf("unknown tokenizer");
103351    }else{
103352      (*ppTok)->pModule = m;
103353    }
103354    sqlite3_free((void *)aArg);
103355  }
103356
103357  sqlite3_free(zCopy);
103358  return rc;
103359}
103360
103361
103362#ifdef SQLITE_TEST
103363
103364
103365/*
103366** Implementation of a special SQL scalar function for testing tokenizers
103367** designed to be used in concert with the Tcl testing framework. This
103368** function must be called with two arguments:
103369**
103370**   SELECT <function-name>(<key-name>, <input-string>);
103371**   SELECT <function-name>(<key-name>, <pointer>);
103372**
103373** where <function-name> is the name passed as the second argument
103374** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
103375** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
103376**
103377** The return value is a string that may be interpreted as a Tcl
103378** list. For each token in the <input-string>, three elements are
103379** added to the returned list. The first is the token position, the
103380** second is the token text (folded, stemmed, etc.) and the third is the
103381** substring of <input-string> associated with the token. For example,
103382** using the built-in "simple" tokenizer:
103383**
103384**   SELECT fts_tokenizer_test('simple', 'I don't see how');
103385**
103386** will return the string:
103387**
103388**   "{0 i I 1 dont don't 2 see see 3 how how}"
103389**
103390*/
103391static void testFunc(
103392  sqlite3_context *context,
103393  int argc,
103394  sqlite3_value **argv
103395){
103396  Fts3Hash *pHash;
103397  sqlite3_tokenizer_module *p;
103398  sqlite3_tokenizer *pTokenizer = 0;
103399  sqlite3_tokenizer_cursor *pCsr = 0;
103400
103401  const char *zErr = 0;
103402
103403  const char *zName;
103404  int nName;
103405  const char *zInput;
103406  int nInput;
103407
103408  const char *zArg = 0;
103409
103410  const char *zToken;
103411  int nToken;
103412  int iStart;
103413  int iEnd;
103414  int iPos;
103415
103416  Tcl_Obj *pRet;
103417
103418  assert( argc==2 || argc==3 );
103419
103420  nName = sqlite3_value_bytes(argv[0]);
103421  zName = (const char *)sqlite3_value_text(argv[0]);
103422  nInput = sqlite3_value_bytes(argv[argc-1]);
103423  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
103424
103425  if( argc==3 ){
103426    zArg = (const char *)sqlite3_value_text(argv[1]);
103427  }
103428
103429  pHash = (Fts3Hash *)sqlite3_user_data(context);
103430  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
103431
103432  if( !p ){
103433    char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
103434    sqlite3_result_error(context, zErr, -1);
103435    sqlite3_free(zErr);
103436    return;
103437  }
103438
103439  pRet = Tcl_NewObj();
103440  Tcl_IncrRefCount(pRet);
103441
103442  if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
103443    zErr = "error in xCreate()";
103444    goto finish;
103445  }
103446  pTokenizer->pModule = p;
103447  if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
103448    zErr = "error in xOpen()";
103449    goto finish;
103450  }
103451  pCsr->pTokenizer = pTokenizer;
103452
103453  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
103454    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
103455    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
103456    zToken = &zInput[iStart];
103457    nToken = iEnd-iStart;
103458    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
103459  }
103460
103461  if( SQLITE_OK!=p->xClose(pCsr) ){
103462    zErr = "error in xClose()";
103463    goto finish;
103464  }
103465  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
103466    zErr = "error in xDestroy()";
103467    goto finish;
103468  }
103469
103470finish:
103471  if( zErr ){
103472    sqlite3_result_error(context, zErr, -1);
103473  }else{
103474    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
103475  }
103476  Tcl_DecrRefCount(pRet);
103477}
103478
103479static
103480int registerTokenizer(
103481  sqlite3 *db,
103482  char *zName,
103483  const sqlite3_tokenizer_module *p
103484){
103485  int rc;
103486  sqlite3_stmt *pStmt;
103487  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
103488
103489  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
103490  if( rc!=SQLITE_OK ){
103491    return rc;
103492  }
103493
103494  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
103495  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
103496  sqlite3_step(pStmt);
103497
103498  return sqlite3_finalize(pStmt);
103499}
103500
103501static
103502int queryTokenizer(
103503  sqlite3 *db,
103504  char *zName,
103505  const sqlite3_tokenizer_module **pp
103506){
103507  int rc;
103508  sqlite3_stmt *pStmt;
103509  const char zSql[] = "SELECT fts3_tokenizer(?)";
103510
103511  *pp = 0;
103512  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
103513  if( rc!=SQLITE_OK ){
103514    return rc;
103515  }
103516
103517  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
103518  if( SQLITE_ROW==sqlite3_step(pStmt) ){
103519    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
103520      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
103521    }
103522  }
103523
103524  return sqlite3_finalize(pStmt);
103525}
103526
103527SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
103528
103529/*
103530** Implementation of the scalar function fts3_tokenizer_internal_test().
103531** This function is used for testing only, it is not included in the
103532** build unless SQLITE_TEST is defined.
103533**
103534** The purpose of this is to test that the fts3_tokenizer() function
103535** can be used as designed by the C-code in the queryTokenizer and
103536** registerTokenizer() functions above. These two functions are repeated
103537** in the README.tokenizer file as an example, so it is important to
103538** test them.
103539**
103540** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
103541** function with no arguments. An assert() will fail if a problem is
103542** detected. i.e.:
103543**
103544**     SELECT fts3_tokenizer_internal_test();
103545**
103546*/
103547static void intTestFunc(
103548  sqlite3_context *context,
103549  int argc,
103550  sqlite3_value **argv
103551){
103552  int rc;
103553  const sqlite3_tokenizer_module *p1;
103554  const sqlite3_tokenizer_module *p2;
103555  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
103556
103557  UNUSED_PARAMETER(argc);
103558  UNUSED_PARAMETER(argv);
103559
103560  /* Test the query function */
103561  sqlite3Fts3SimpleTokenizerModule(&p1);
103562  rc = queryTokenizer(db, "simple", &p2);
103563  assert( rc==SQLITE_OK );
103564  assert( p1==p2 );
103565  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
103566  assert( rc==SQLITE_ERROR );
103567  assert( p2==0 );
103568  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
103569
103570  /* Test the storage function */
103571  rc = registerTokenizer(db, "nosuchtokenizer", p1);
103572  assert( rc==SQLITE_OK );
103573  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
103574  assert( rc==SQLITE_OK );
103575  assert( p2==p1 );
103576
103577  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
103578}
103579
103580#endif
103581
103582/*
103583** Set up SQL objects in database db used to access the contents of
103584** the hash table pointed to by argument pHash. The hash table must
103585** been initialised to use string keys, and to take a private copy
103586** of the key when a value is inserted. i.e. by a call similar to:
103587**
103588**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
103589**
103590** This function adds a scalar function (see header comment above
103591** scalarFunc() in this file for details) and, if ENABLE_TABLE is
103592** defined at compilation time, a temporary virtual table (see header
103593** comment above struct HashTableVtab) to the database schema. Both
103594** provide read/write access to the contents of *pHash.
103595**
103596** The third argument to this function, zName, is used as the name
103597** of both the scalar and, if created, the virtual table.
103598*/
103599SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
103600  sqlite3 *db,
103601  Fts3Hash *pHash,
103602  const char *zName
103603){
103604  int rc = SQLITE_OK;
103605  void *p = (void *)pHash;
103606  const int any = SQLITE_ANY;
103607
103608#ifdef SQLITE_TEST
103609  char *zTest = 0;
103610  char *zTest2 = 0;
103611  void *pdb = (void *)db;
103612  zTest = sqlite3_mprintf("%s_test", zName);
103613  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
103614  if( !zTest || !zTest2 ){
103615    rc = SQLITE_NOMEM;
103616  }
103617#endif
103618
103619  if( SQLITE_OK!=rc
103620   || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
103621   || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
103622#ifdef SQLITE_TEST
103623   || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
103624   || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
103625   || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
103626#endif
103627   );
103628
103629#ifdef SQLITE_TEST
103630  sqlite3_free(zTest);
103631  sqlite3_free(zTest2);
103632#endif
103633
103634  return rc;
103635}
103636
103637#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
103638
103639/************** End of fts3_tokenizer.c **************************************/
103640/************** Begin file fts3_tokenizer1.c *********************************/
103641/*
103642** 2006 Oct 10
103643**
103644** The author disclaims copyright to this source code.  In place of
103645** a legal notice, here is a blessing:
103646**
103647**    May you do good and not evil.
103648**    May you find forgiveness for yourself and forgive others.
103649**    May you share freely, never taking more than you give.
103650**
103651******************************************************************************
103652**
103653** Implementation of the "simple" full-text-search tokenizer.
103654*/
103655
103656/*
103657** The code in this file is only compiled if:
103658**
103659**     * The FTS3 module is being built as an extension
103660**       (in which case SQLITE_CORE is not defined), or
103661**
103662**     * The FTS3 module is being built into the core of
103663**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
103664*/
103665#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
103666
103667
103668
103669
103670typedef struct simple_tokenizer {
103671  sqlite3_tokenizer base;
103672  char delim[128];             /* flag ASCII delimiters */
103673} simple_tokenizer;
103674
103675typedef struct simple_tokenizer_cursor {
103676  sqlite3_tokenizer_cursor base;
103677  const char *pInput;          /* input we are tokenizing */
103678  int nBytes;                  /* size of the input */
103679  int iOffset;                 /* current position in pInput */
103680  int iToken;                  /* index of next token to be returned */
103681  char *pToken;                /* storage for current token */
103682  int nTokenAllocated;         /* space allocated to zToken buffer */
103683} simple_tokenizer_cursor;
103684
103685
103686static int simpleDelim(simple_tokenizer *t, unsigned char c){
103687  return c<0x80 && t->delim[c];
103688}
103689
103690/*
103691** Create a new tokenizer instance.
103692*/
103693static int simpleCreate(
103694  int argc, const char * const *argv,
103695  sqlite3_tokenizer **ppTokenizer
103696){
103697  simple_tokenizer *t;
103698
103699  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
103700  if( t==NULL ) return SQLITE_NOMEM;
103701  memset(t, 0, sizeof(*t));
103702
103703  /* TODO(shess) Delimiters need to remain the same from run to run,
103704  ** else we need to reindex.  One solution would be a meta-table to
103705  ** track such information in the database, then we'd only want this
103706  ** information on the initial create.
103707  */
103708  if( argc>1 ){
103709    int i, n = (int)strlen(argv[1]);
103710    for(i=0; i<n; i++){
103711      unsigned char ch = argv[1][i];
103712      /* We explicitly don't support UTF-8 delimiters for now. */
103713      if( ch>=0x80 ){
103714        sqlite3_free(t);
103715        return SQLITE_ERROR;
103716      }
103717      t->delim[ch] = 1;
103718    }
103719  } else {
103720    /* Mark non-alphanumeric ASCII characters as delimiters */
103721    int i;
103722    for(i=1; i<0x80; i++){
103723      t->delim[i] = !isalnum(i) ? -1 : 0;
103724    }
103725  }
103726
103727  *ppTokenizer = &t->base;
103728  return SQLITE_OK;
103729}
103730
103731/*
103732** Destroy a tokenizer
103733*/
103734static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
103735  sqlite3_free(pTokenizer);
103736  return SQLITE_OK;
103737}
103738
103739/*
103740** Prepare to begin tokenizing a particular string.  The input
103741** string to be tokenized is pInput[0..nBytes-1].  A cursor
103742** used to incrementally tokenize this string is returned in
103743** *ppCursor.
103744*/
103745static int simpleOpen(
103746  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
103747  const char *pInput, int nBytes,        /* String to be tokenized */
103748  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
103749){
103750  simple_tokenizer_cursor *c;
103751
103752  UNUSED_PARAMETER(pTokenizer);
103753
103754  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
103755  if( c==NULL ) return SQLITE_NOMEM;
103756
103757  c->pInput = pInput;
103758  if( pInput==0 ){
103759    c->nBytes = 0;
103760  }else if( nBytes<0 ){
103761    c->nBytes = (int)strlen(pInput);
103762  }else{
103763    c->nBytes = nBytes;
103764  }
103765  c->iOffset = 0;                 /* start tokenizing at the beginning */
103766  c->iToken = 0;
103767  c->pToken = NULL;               /* no space allocated, yet. */
103768  c->nTokenAllocated = 0;
103769
103770  *ppCursor = &c->base;
103771  return SQLITE_OK;
103772}
103773
103774/*
103775** Close a tokenization cursor previously opened by a call to
103776** simpleOpen() above.
103777*/
103778static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
103779  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
103780  sqlite3_free(c->pToken);
103781  sqlite3_free(c);
103782  return SQLITE_OK;
103783}
103784
103785/*
103786** Extract the next token from a tokenization cursor.  The cursor must
103787** have been opened by a prior call to simpleOpen().
103788*/
103789static int simpleNext(
103790  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
103791  const char **ppToken,               /* OUT: *ppToken is the token text */
103792  int *pnBytes,                       /* OUT: Number of bytes in token */
103793  int *piStartOffset,                 /* OUT: Starting offset of token */
103794  int *piEndOffset,                   /* OUT: Ending offset of token */
103795  int *piPosition                     /* OUT: Position integer of token */
103796){
103797  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
103798  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
103799  unsigned char *p = (unsigned char *)c->pInput;
103800
103801  while( c->iOffset<c->nBytes ){
103802    int iStartOffset;
103803
103804    /* Scan past delimiter characters */
103805    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
103806      c->iOffset++;
103807    }
103808
103809    /* Count non-delimiter characters. */
103810    iStartOffset = c->iOffset;
103811    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
103812      c->iOffset++;
103813    }
103814
103815    if( c->iOffset>iStartOffset ){
103816      int i, n = c->iOffset-iStartOffset;
103817      if( n>c->nTokenAllocated ){
103818        c->nTokenAllocated = n+20;
103819        c->pToken = sqlite3_realloc(c->pToken, c->nTokenAllocated);
103820        if( c->pToken==NULL ) return SQLITE_NOMEM;
103821      }
103822      for(i=0; i<n; i++){
103823        /* TODO(shess) This needs expansion to handle UTF-8
103824        ** case-insensitivity.
103825        */
103826        unsigned char ch = p[iStartOffset+i];
103827        c->pToken[i] = (char)(ch<0x80 ? tolower(ch) : ch);
103828      }
103829      *ppToken = c->pToken;
103830      *pnBytes = n;
103831      *piStartOffset = iStartOffset;
103832      *piEndOffset = c->iOffset;
103833      *piPosition = c->iToken++;
103834
103835      return SQLITE_OK;
103836    }
103837  }
103838  return SQLITE_DONE;
103839}
103840
103841/*
103842** The set of routines that implement the simple tokenizer
103843*/
103844static const sqlite3_tokenizer_module simpleTokenizerModule = {
103845  0,
103846  simpleCreate,
103847  simpleDestroy,
103848  simpleOpen,
103849  simpleClose,
103850  simpleNext,
103851};
103852
103853/*
103854** Allocate a new simple tokenizer.  Return a pointer to the new
103855** tokenizer in *ppModule
103856*/
103857SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
103858  sqlite3_tokenizer_module const**ppModule
103859){
103860  *ppModule = &simpleTokenizerModule;
103861}
103862
103863#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
103864
103865/************** End of fts3_tokenizer1.c *************************************/
103866/************** Begin file fts3_write.c **************************************/
103867/*
103868** 2009 Oct 23
103869**
103870** The author disclaims copyright to this source code.  In place of
103871** a legal notice, here is a blessing:
103872**
103873**    May you do good and not evil.
103874**    May you find forgiveness for yourself and forgive others.
103875**    May you share freely, never taking more than you give.
103876**
103877******************************************************************************
103878**
103879** This file is part of the SQLite FTS3 extension module. Specifically,
103880** this file contains code to insert, update and delete rows from FTS3
103881** tables. It also contains code to merge FTS3 b-tree segments. Some
103882** of the sub-routines used to merge segments are also used by the query
103883** code in fts3.c.
103884*/
103885
103886#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
103887
103888
103889typedef struct PendingList PendingList;
103890typedef struct SegmentNode SegmentNode;
103891typedef struct SegmentWriter SegmentWriter;
103892
103893/*
103894** Data structure used while accumulating terms in the pending-terms hash
103895** table. The hash table entry maps from term (a string) to a malloc'd
103896** instance of this structure.
103897*/
103898struct PendingList {
103899  int nData;
103900  char *aData;
103901  int nSpace;
103902  sqlite3_int64 iLastDocid;
103903  sqlite3_int64 iLastCol;
103904  sqlite3_int64 iLastPos;
103905};
103906
103907/*
103908** An instance of this structure is used to iterate through the terms on
103909** a contiguous set of segment b-tree leaf nodes. Although the details of
103910** this structure are only manipulated by code in this file, opaque handles
103911** of type Fts3SegReader* are also used by code in fts3.c to iterate through
103912** terms when querying the full-text index. See functions:
103913**
103914**   sqlite3Fts3SegReaderNew()
103915**   sqlite3Fts3SegReaderFree()
103916**   sqlite3Fts3SegReaderIterate()
103917**
103918** Methods used to manipulate Fts3SegReader structures:
103919**
103920**   fts3SegReaderNext()
103921**   fts3SegReaderFirstDocid()
103922**   fts3SegReaderNextDocid()
103923*/
103924struct Fts3SegReader {
103925  int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
103926  sqlite3_int64 iStartBlock;
103927  sqlite3_int64 iEndBlock;
103928  sqlite3_stmt *pStmt;            /* SQL Statement to access leaf nodes */
103929  char *aNode;                    /* Pointer to node data (or NULL) */
103930  int nNode;                      /* Size of buffer at aNode (or 0) */
103931  int nTermAlloc;                 /* Allocated size of zTerm buffer */
103932  Fts3HashElem **ppNextElem;
103933
103934  /* Variables set by fts3SegReaderNext(). These may be read directly
103935  ** by the caller. They are valid from the time SegmentReaderNew() returns
103936  ** until SegmentReaderNext() returns something other than SQLITE_OK
103937  ** (i.e. SQLITE_DONE).
103938  */
103939  int nTerm;                      /* Number of bytes in current term */
103940  char *zTerm;                    /* Pointer to current term */
103941  char *aDoclist;                 /* Pointer to doclist of current entry */
103942  int nDoclist;                   /* Size of doclist in current entry */
103943
103944  /* The following variables are used to iterate through the current doclist */
103945  char *pOffsetList;
103946  sqlite3_int64 iDocid;
103947};
103948
103949#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
103950
103951/*
103952** An instance of this structure is used to create a segment b-tree in the
103953** database. The internal details of this type are only accessed by the
103954** following functions:
103955**
103956**   fts3SegWriterAdd()
103957**   fts3SegWriterFlush()
103958**   fts3SegWriterFree()
103959*/
103960struct SegmentWriter {
103961  SegmentNode *pTree;             /* Pointer to interior tree structure */
103962  sqlite3_int64 iFirst;           /* First slot in %_segments written */
103963  sqlite3_int64 iFree;            /* Next free slot in %_segments */
103964  char *zTerm;                    /* Pointer to previous term buffer */
103965  int nTerm;                      /* Number of bytes in zTerm */
103966  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
103967  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
103968  int nSize;                      /* Size of allocation at aData */
103969  int nData;                      /* Bytes of data in aData */
103970  char *aData;                    /* Pointer to block from malloc() */
103971};
103972
103973/*
103974** Type SegmentNode is used by the following three functions to create
103975** the interior part of the segment b+-tree structures (everything except
103976** the leaf nodes). These functions and type are only ever used by code
103977** within the fts3SegWriterXXX() family of functions described above.
103978**
103979**   fts3NodeAddTerm()
103980**   fts3NodeWrite()
103981**   fts3NodeFree()
103982*/
103983struct SegmentNode {
103984  SegmentNode *pParent;           /* Parent node (or NULL for root node) */
103985  SegmentNode *pRight;            /* Pointer to right-sibling */
103986  SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
103987  int nEntry;                     /* Number of terms written to node so far */
103988  char *zTerm;                    /* Pointer to previous term buffer */
103989  int nTerm;                      /* Number of bytes in zTerm */
103990  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
103991  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
103992  int nData;                      /* Bytes of valid data so far */
103993  char *aData;                    /* Node data */
103994};
103995
103996/*
103997** Valid values for the second argument to fts3SqlStmt().
103998*/
103999#define SQL_DELETE_CONTENT             0
104000#define SQL_IS_EMPTY                   1
104001#define SQL_DELETE_ALL_CONTENT         2
104002#define SQL_DELETE_ALL_SEGMENTS        3
104003#define SQL_DELETE_ALL_SEGDIR          4
104004#define SQL_SELECT_CONTENT_BY_ROWID    5
104005#define SQL_NEXT_SEGMENT_INDEX         6
104006#define SQL_INSERT_SEGMENTS            7
104007#define SQL_NEXT_SEGMENTS_ID           8
104008#define SQL_INSERT_SEGDIR              9
104009#define SQL_SELECT_LEVEL              10
104010#define SQL_SELECT_ALL_LEVEL          11
104011#define SQL_SELECT_LEVEL_COUNT        12
104012#define SQL_SELECT_SEGDIR_COUNT_MAX   13
104013#define SQL_DELETE_SEGDIR_BY_LEVEL    14
104014#define SQL_DELETE_SEGMENTS_RANGE     15
104015#define SQL_CONTENT_INSERT            16
104016#define SQL_GET_BLOCK                 17
104017
104018/*
104019** This function is used to obtain an SQLite prepared statement handle
104020** for the statement identified by the second argument. If successful,
104021** *pp is set to the requested statement handle and SQLITE_OK returned.
104022** Otherwise, an SQLite error code is returned and *pp is set to 0.
104023**
104024** If argument apVal is not NULL, then it must point to an array with
104025** at least as many entries as the requested statement has bound
104026** parameters. The values are bound to the statements parameters before
104027** returning.
104028*/
104029static int fts3SqlStmt(
104030  Fts3Table *p,                   /* Virtual table handle */
104031  int eStmt,                      /* One of the SQL_XXX constants above */
104032  sqlite3_stmt **pp,              /* OUT: Statement handle */
104033  sqlite3_value **apVal           /* Values to bind to statement */
104034){
104035  const char *azSql[] = {
104036/* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
104037/* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
104038/* 2  */  "DELETE FROM %Q.'%q_content'",
104039/* 3  */  "DELETE FROM %Q.'%q_segments'",
104040/* 4  */  "DELETE FROM %Q.'%q_segdir'",
104041/* 5  */  "SELECT * FROM %Q.'%q_content' WHERE rowid=?",
104042/* 6  */  "SELECT coalesce(max(idx)+1, 0) FROM %Q.'%q_segdir' WHERE level=?",
104043/* 7  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
104044/* 8  */  "SELECT coalesce(max(blockid)+1, 1) FROM %Q.'%q_segments'",
104045/* 9  */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
104046
104047          /* Return segments in order from oldest to newest.*/
104048/* 10 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
104049            "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
104050/* 11 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
104051            "FROM %Q.'%q_segdir' ORDER BY level DESC, idx ASC",
104052
104053/* 12 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
104054/* 13 */  "SELECT count(*), max(level) FROM %Q.'%q_segdir'",
104055
104056/* 14 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
104057/* 15 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
104058/* 16 */  "INSERT INTO %Q.'%q_content' VALUES(%z)",
104059/* 17 */  "SELECT block FROM %Q.'%q_segments' WHERE blockid = ?",
104060  };
104061  int rc = SQLITE_OK;
104062  sqlite3_stmt *pStmt;
104063
104064  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
104065  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
104066
104067  pStmt = p->aStmt[eStmt];
104068  if( !pStmt ){
104069    char *zSql;
104070    if( eStmt==SQL_CONTENT_INSERT ){
104071      int i;                      /* Iterator variable */
104072      char *zVarlist;             /* The "?, ?, ..." string */
104073      zVarlist = (char *)sqlite3_malloc(2*p->nColumn+2);
104074      if( !zVarlist ){
104075        *pp = 0;
104076        return SQLITE_NOMEM;
104077      }
104078      zVarlist[0] = '?';
104079      zVarlist[p->nColumn*2+1] = '\0';
104080      for(i=1; i<=p->nColumn; i++){
104081        zVarlist[i*2-1] = ',';
104082        zVarlist[i*2] = '?';
104083      }
104084      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, zVarlist);
104085    }else{
104086      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
104087    }
104088    if( !zSql ){
104089      rc = SQLITE_NOMEM;
104090    }else{
104091      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
104092      sqlite3_free(zSql);
104093      assert( rc==SQLITE_OK || pStmt==0 );
104094      p->aStmt[eStmt] = pStmt;
104095    }
104096  }
104097  if( apVal ){
104098    int i;
104099    int nParam = sqlite3_bind_parameter_count(pStmt);
104100    for(i=0; rc==SQLITE_OK && i<nParam; i++){
104101      rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
104102    }
104103  }
104104  *pp = pStmt;
104105  return rc;
104106}
104107
104108/*
104109** Similar to fts3SqlStmt(). Except, after binding the parameters in
104110** array apVal[] to the SQL statement identified by eStmt, the statement
104111** is executed.
104112**
104113** Returns SQLITE_OK if the statement is successfully executed, or an
104114** SQLite error code otherwise.
104115*/
104116static int fts3SqlExec(Fts3Table *p, int eStmt, sqlite3_value **apVal){
104117  sqlite3_stmt *pStmt;
104118  int rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
104119  if( rc==SQLITE_OK ){
104120    sqlite3_step(pStmt);
104121    rc = sqlite3_reset(pStmt);
104122  }
104123  return rc;
104124}
104125
104126
104127/*
104128** Read a single block from the %_segments table. If the specified block
104129** does not exist, return SQLITE_CORRUPT. If some other error (malloc, IO
104130** etc.) occurs, return the appropriate SQLite error code.
104131**
104132** Otherwise, if successful, set *pzBlock to point to a buffer containing
104133** the block read from the database, and *pnBlock to the size of the read
104134** block in bytes.
104135**
104136** WARNING: The returned buffer is only valid until the next call to
104137** sqlite3Fts3ReadBlock().
104138*/
104139SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
104140  Fts3Table *p,
104141  sqlite3_int64 iBlock,
104142  char const **pzBlock,
104143  int *pnBlock
104144){
104145  sqlite3_stmt *pStmt;
104146  int rc = fts3SqlStmt(p, SQL_GET_BLOCK, &pStmt, 0);
104147  if( rc!=SQLITE_OK ) return rc;
104148  sqlite3_reset(pStmt);
104149
104150  if( pzBlock ){
104151    sqlite3_bind_int64(pStmt, 1, iBlock);
104152    rc = sqlite3_step(pStmt);
104153    if( rc!=SQLITE_ROW ){
104154      return (rc==SQLITE_DONE ? SQLITE_CORRUPT : rc);
104155    }
104156
104157    *pnBlock = sqlite3_column_bytes(pStmt, 0);
104158    *pzBlock = (char *)sqlite3_column_blob(pStmt, 0);
104159    if( sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
104160      return SQLITE_CORRUPT;
104161    }
104162  }
104163  return SQLITE_OK;
104164}
104165
104166/*
104167** Set *ppStmt to a statement handle that may be used to iterate through
104168** all rows in the %_segdir table, from oldest to newest. If successful,
104169** return SQLITE_OK. If an error occurs while preparing the statement,
104170** return an SQLite error code.
104171**
104172** There is only ever one instance of this SQL statement compiled for
104173** each FTS3 table.
104174**
104175** The statement returns the following columns from the %_segdir table:
104176**
104177**   0: idx
104178**   1: start_block
104179**   2: leaves_end_block
104180**   3: end_block
104181**   4: root
104182*/
104183SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table *p, sqlite3_stmt **ppStmt){
104184  return fts3SqlStmt(p, SQL_SELECT_ALL_LEVEL, ppStmt, 0);
104185}
104186
104187
104188/*
104189** Append a single varint to a PendingList buffer. SQLITE_OK is returned
104190** if successful, or an SQLite error code otherwise.
104191**
104192** This function also serves to allocate the PendingList structure itself.
104193** For example, to create a new PendingList structure containing two
104194** varints:
104195**
104196**   PendingList *p = 0;
104197**   fts3PendingListAppendVarint(&p, 1);
104198**   fts3PendingListAppendVarint(&p, 2);
104199*/
104200static int fts3PendingListAppendVarint(
104201  PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
104202  sqlite3_int64 i                 /* Value to append to data */
104203){
104204  PendingList *p = *pp;
104205
104206  /* Allocate or grow the PendingList as required. */
104207  if( !p ){
104208    p = sqlite3_malloc(sizeof(*p) + 100);
104209    if( !p ){
104210      return SQLITE_NOMEM;
104211    }
104212    p->nSpace = 100;
104213    p->aData = (char *)&p[1];
104214    p->nData = 0;
104215  }
104216  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
104217    int nNew = p->nSpace * 2;
104218    p = sqlite3_realloc(p, sizeof(*p) + nNew);
104219    if( !p ){
104220      sqlite3_free(*pp);
104221      *pp = 0;
104222      return SQLITE_NOMEM;
104223    }
104224    p->nSpace = nNew;
104225    p->aData = (char *)&p[1];
104226  }
104227
104228  /* Append the new serialized varint to the end of the list. */
104229  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
104230  p->aData[p->nData] = '\0';
104231  *pp = p;
104232  return SQLITE_OK;
104233}
104234
104235/*
104236** Add a docid/column/position entry to a PendingList structure. Non-zero
104237** is returned if the structure is sqlite3_realloced as part of adding
104238** the entry. Otherwise, zero.
104239**
104240** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
104241** Zero is always returned in this case. Otherwise, if no OOM error occurs,
104242** it is set to SQLITE_OK.
104243*/
104244static int fts3PendingListAppend(
104245  PendingList **pp,               /* IN/OUT: PendingList structure */
104246  sqlite3_int64 iDocid,           /* Docid for entry to add */
104247  sqlite3_int64 iCol,             /* Column for entry to add */
104248  sqlite3_int64 iPos,             /* Position of term for entry to add */
104249  int *pRc                        /* OUT: Return code */
104250){
104251  PendingList *p = *pp;
104252  int rc = SQLITE_OK;
104253
104254  assert( !p || p->iLastDocid<=iDocid );
104255
104256  if( !p || p->iLastDocid!=iDocid ){
104257    sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
104258    if( p ){
104259      assert( p->nData<p->nSpace );
104260      assert( p->aData[p->nData]==0 );
104261      p->nData++;
104262    }
104263    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
104264      goto pendinglistappend_out;
104265    }
104266    p->iLastCol = -1;
104267    p->iLastPos = 0;
104268    p->iLastDocid = iDocid;
104269  }
104270  if( iCol>0 && p->iLastCol!=iCol ){
104271    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
104272     || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
104273    ){
104274      goto pendinglistappend_out;
104275    }
104276    p->iLastCol = iCol;
104277    p->iLastPos = 0;
104278  }
104279  if( iCol>=0 ){
104280    assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
104281    rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
104282    if( rc==SQLITE_OK ){
104283      p->iLastPos = iPos;
104284    }
104285  }
104286
104287 pendinglistappend_out:
104288  *pRc = rc;
104289  if( p!=*pp ){
104290    *pp = p;
104291    return 1;
104292  }
104293  return 0;
104294}
104295
104296/*
104297** Tokenize the nul-terminated string zText and add all tokens to the
104298** pending-terms hash-table. The docid used is that currently stored in
104299** p->iPrevDocid, and the column is specified by argument iCol.
104300**
104301** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
104302*/
104303static int fts3PendingTermsAdd(Fts3Table *p, const char *zText, int iCol){
104304  int rc;
104305  int iStart;
104306  int iEnd;
104307  int iPos;
104308
104309  char const *zToken;
104310  int nToken;
104311
104312  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
104313  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
104314  sqlite3_tokenizer_cursor *pCsr;
104315  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
104316      const char**,int*,int*,int*,int*);
104317
104318  assert( pTokenizer && pModule );
104319
104320  rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
104321  if( rc!=SQLITE_OK ){
104322    return rc;
104323  }
104324  pCsr->pTokenizer = pTokenizer;
104325
104326  xNext = pModule->xNext;
104327  while( SQLITE_OK==rc
104328      && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
104329  ){
104330    PendingList *pList;
104331
104332    /* Positions cannot be negative; we use -1 as a terminator internally.
104333    ** Tokens must have a non-zero length.
104334    */
104335    if( iPos<0 || !zToken || nToken<=0 ){
104336      rc = SQLITE_ERROR;
104337      break;
104338    }
104339
104340    pList = (PendingList *)fts3HashFind(&p->pendingTerms, zToken, nToken);
104341    if( pList ){
104342      p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
104343    }
104344    if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
104345      if( pList==fts3HashInsert(&p->pendingTerms, zToken, nToken, pList) ){
104346        /* Malloc failed while inserting the new entry. This can only
104347        ** happen if there was no previous entry for this token.
104348        */
104349        assert( 0==fts3HashFind(&p->pendingTerms, zToken, nToken) );
104350        sqlite3_free(pList);
104351        rc = SQLITE_NOMEM;
104352      }
104353    }
104354    if( rc==SQLITE_OK ){
104355      p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
104356    }
104357  }
104358
104359  pModule->xClose(pCsr);
104360  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
104361}
104362
104363/*
104364** Calling this function indicates that subsequent calls to
104365** fts3PendingTermsAdd() are to add term/position-list pairs for the
104366** contents of the document with docid iDocid.
104367*/
104368static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
104369  /* TODO(shess) Explore whether partially flushing the buffer on
104370  ** forced-flush would provide better performance.  I suspect that if
104371  ** we ordered the doclists by size and flushed the largest until the
104372  ** buffer was half empty, that would let the less frequent terms
104373  ** generate longer doclists.
104374  */
104375  if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
104376    int rc = sqlite3Fts3PendingTermsFlush(p);
104377    if( rc!=SQLITE_OK ) return rc;
104378  }
104379  p->iPrevDocid = iDocid;
104380  return SQLITE_OK;
104381}
104382
104383SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
104384  Fts3HashElem *pElem;
104385  for(pElem=fts3HashFirst(&p->pendingTerms); pElem; pElem=fts3HashNext(pElem)){
104386    sqlite3_free(fts3HashData(pElem));
104387  }
104388  fts3HashClear(&p->pendingTerms);
104389  p->nPendingData = 0;
104390}
104391
104392/*
104393** This function is called by the xUpdate() method as part of an INSERT
104394** operation. It adds entries for each term in the new record to the
104395** pendingTerms hash table.
104396**
104397** Argument apVal is the same as the similarly named argument passed to
104398** fts3InsertData(). Parameter iDocid is the docid of the new row.
104399*/
104400static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal){
104401  int i;                          /* Iterator variable */
104402  for(i=2; i<p->nColumn+2; i++){
104403    const char *zText = (const char *)sqlite3_value_text(apVal[i]);
104404    if( zText ){
104405      int rc = fts3PendingTermsAdd(p, zText, i-2);
104406      if( rc!=SQLITE_OK ){
104407        return rc;
104408      }
104409    }
104410  }
104411  return SQLITE_OK;
104412}
104413
104414/*
104415** This function is called by the xUpdate() method for an INSERT operation.
104416** The apVal parameter is passed a copy of the apVal argument passed by
104417** SQLite to the xUpdate() method. i.e:
104418**
104419**   apVal[0]                Not used for INSERT.
104420**   apVal[1]                rowid
104421**   apVal[2]                Left-most user-defined column
104422**   ...
104423**   apVal[p->nColumn+1]     Right-most user-defined column
104424**   apVal[p->nColumn+2]     Hidden column with same name as table
104425**   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
104426*/
104427static int fts3InsertData(
104428  Fts3Table *p,                   /* Full-text table */
104429  sqlite3_value **apVal,          /* Array of values to insert */
104430  sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
104431){
104432  int rc;                         /* Return code */
104433  sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
104434
104435  /* Locate the statement handle used to insert data into the %_content
104436  ** table. The SQL for this statement is:
104437  **
104438  **   INSERT INTO %_content VALUES(?, ?, ?, ...)
104439  **
104440  ** The statement features N '?' variables, where N is the number of user
104441  ** defined columns in the FTS3 table, plus one for the docid field.
104442  */
104443  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
104444  if( rc!=SQLITE_OK ){
104445    return rc;
104446  }
104447
104448  /* There is a quirk here. The users INSERT statement may have specified
104449  ** a value for the "rowid" field, for the "docid" field, or for both.
104450  ** Which is a problem, since "rowid" and "docid" are aliases for the
104451  ** same value. For example:
104452  **
104453  **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
104454  **
104455  ** In FTS3, this is an error. It is an error to specify non-NULL values
104456  ** for both docid and some other rowid alias.
104457  */
104458  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
104459    if( SQLITE_NULL==sqlite3_value_type(apVal[0])
104460     && SQLITE_NULL!=sqlite3_value_type(apVal[1])
104461    ){
104462      /* A rowid/docid conflict. */
104463      return SQLITE_ERROR;
104464    }
104465    rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
104466    if( rc!=SQLITE_OK ) return rc;
104467  }
104468
104469  /* Execute the statement to insert the record. Set *piDocid to the
104470  ** new docid value.
104471  */
104472  sqlite3_step(pContentInsert);
104473  rc = sqlite3_reset(pContentInsert);
104474
104475  *piDocid = sqlite3_last_insert_rowid(p->db);
104476  return rc;
104477}
104478
104479
104480
104481/*
104482** Remove all data from the FTS3 table. Clear the hash table containing
104483** pending terms.
104484*/
104485static int fts3DeleteAll(Fts3Table *p){
104486  int rc;                         /* Return code */
104487
104488  /* Discard the contents of the pending-terms hash table. */
104489  sqlite3Fts3PendingTermsClear(p);
104490
104491  /* Delete everything from the %_content, %_segments and %_segdir tables. */
104492  rc = fts3SqlExec(p, SQL_DELETE_ALL_CONTENT, 0);
104493  if( rc==SQLITE_OK ){
104494    rc = fts3SqlExec(p, SQL_DELETE_ALL_SEGMENTS, 0);
104495  }
104496  if( rc==SQLITE_OK ){
104497    rc = fts3SqlExec(p, SQL_DELETE_ALL_SEGDIR, 0);
104498  }
104499  return rc;
104500}
104501
104502/*
104503** The first element in the apVal[] array is assumed to contain the docid
104504** (an integer) of a row about to be deleted. Remove all terms from the
104505** full-text index.
104506*/
104507static int fts3DeleteTerms(Fts3Table *p, sqlite3_value **apVal){
104508  int rc;
104509  sqlite3_stmt *pSelect;
104510
104511  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, apVal);
104512  if( rc==SQLITE_OK ){
104513    if( SQLITE_ROW==sqlite3_step(pSelect) ){
104514      int i;
104515      for(i=1; i<=p->nColumn; i++){
104516        const char *zText = (const char *)sqlite3_column_text(pSelect, i);
104517        rc = fts3PendingTermsAdd(p, zText, -1);
104518        if( rc!=SQLITE_OK ){
104519          sqlite3_reset(pSelect);
104520          return rc;
104521        }
104522      }
104523    }
104524    rc = sqlite3_reset(pSelect);
104525  }else{
104526    sqlite3_reset(pSelect);
104527  }
104528  return rc;
104529}
104530
104531/*
104532** Forward declaration to account for the circular dependency between
104533** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
104534*/
104535static int fts3SegmentMerge(Fts3Table *, int);
104536
104537/*
104538** This function allocates a new level iLevel index in the segdir table.
104539** Usually, indexes are allocated within a level sequentially starting
104540** with 0, so the allocated index is one greater than the value returned
104541** by:
104542**
104543**   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
104544**
104545** However, if there are already FTS3_MERGE_COUNT indexes at the requested
104546** level, they are merged into a single level (iLevel+1) segment and the
104547** allocated index is 0.
104548**
104549** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
104550** returned. Otherwise, an SQLite error code is returned.
104551*/
104552static int fts3AllocateSegdirIdx(Fts3Table *p, int iLevel, int *piIdx){
104553  int rc;                         /* Return Code */
104554  sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
104555  int iNext = 0;                  /* Result of query pNextIdx */
104556
104557  /* Set variable iNext to the next available segdir index at level iLevel. */
104558  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
104559  if( rc==SQLITE_OK ){
104560    sqlite3_bind_int(pNextIdx, 1, iLevel);
104561    if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
104562      iNext = sqlite3_column_int(pNextIdx, 0);
104563    }
104564    rc = sqlite3_reset(pNextIdx);
104565  }
104566
104567  if( rc==SQLITE_OK ){
104568    /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
104569    ** full, merge all segments in level iLevel into a single iLevel+1
104570    ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
104571    ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
104572    */
104573    if( iNext>=FTS3_MERGE_COUNT ){
104574      rc = fts3SegmentMerge(p, iLevel);
104575      *piIdx = 0;
104576    }else{
104577      *piIdx = iNext;
104578    }
104579  }
104580
104581  return rc;
104582}
104583
104584/*
104585** Move the iterator passed as the first argument to the next term in the
104586** segment. If successful, SQLITE_OK is returned. If there is no next term,
104587** SQLITE_DONE. Otherwise, an SQLite error code.
104588*/
104589static int fts3SegReaderNext(Fts3SegReader *pReader){
104590  char *pNext;                    /* Cursor variable */
104591  int nPrefix;                    /* Number of bytes in term prefix */
104592  int nSuffix;                    /* Number of bytes in term suffix */
104593
104594  if( !pReader->aDoclist ){
104595    pNext = pReader->aNode;
104596  }else{
104597    pNext = &pReader->aDoclist[pReader->nDoclist];
104598  }
104599
104600  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
104601    int rc;
104602    if( fts3SegReaderIsPending(pReader) ){
104603      Fts3HashElem *pElem = *(pReader->ppNextElem);
104604      if( pElem==0 ){
104605        pReader->aNode = 0;
104606      }else{
104607        PendingList *pList = (PendingList *)fts3HashData(pElem);
104608        pReader->zTerm = (char *)fts3HashKey(pElem);
104609        pReader->nTerm = fts3HashKeysize(pElem);
104610        pReader->nNode = pReader->nDoclist = pList->nData + 1;
104611        pReader->aNode = pReader->aDoclist = pList->aData;
104612        pReader->ppNextElem++;
104613        assert( pReader->aNode );
104614      }
104615      return SQLITE_OK;
104616    }
104617    if( !pReader->pStmt ){
104618      pReader->aNode = 0;
104619      return SQLITE_OK;
104620    }
104621    rc = sqlite3_step(pReader->pStmt);
104622    if( rc!=SQLITE_ROW ){
104623      pReader->aNode = 0;
104624      return (rc==SQLITE_DONE ? SQLITE_OK : rc);
104625    }
104626    pReader->nNode = sqlite3_column_bytes(pReader->pStmt, 0);
104627    pReader->aNode = (char *)sqlite3_column_blob(pReader->pStmt, 0);
104628    pNext = pReader->aNode;
104629  }
104630
104631  pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
104632  pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
104633
104634  if( nPrefix+nSuffix>pReader->nTermAlloc ){
104635    int nNew = (nPrefix+nSuffix)*2;
104636    char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
104637    if( !zNew ){
104638      return SQLITE_NOMEM;
104639    }
104640    pReader->zTerm = zNew;
104641    pReader->nTermAlloc = nNew;
104642  }
104643  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
104644  pReader->nTerm = nPrefix+nSuffix;
104645  pNext += nSuffix;
104646  pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
104647  assert( pNext<&pReader->aNode[pReader->nNode] );
104648  pReader->aDoclist = pNext;
104649  pReader->pOffsetList = 0;
104650  return SQLITE_OK;
104651}
104652
104653/*
104654** Set the SegReader to point to the first docid in the doclist associated
104655** with the current term.
104656*/
104657static void fts3SegReaderFirstDocid(Fts3SegReader *pReader){
104658  int n;
104659  assert( pReader->aDoclist );
104660  assert( !pReader->pOffsetList );
104661  n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
104662  pReader->pOffsetList = &pReader->aDoclist[n];
104663}
104664
104665/*
104666** Advance the SegReader to point to the next docid in the doclist
104667** associated with the current term.
104668**
104669** If arguments ppOffsetList and pnOffsetList are not NULL, then
104670** *ppOffsetList is set to point to the first column-offset list
104671** in the doclist entry (i.e. immediately past the docid varint).
104672** *pnOffsetList is set to the length of the set of column-offset
104673** lists, not including the nul-terminator byte. For example:
104674*/
104675static void fts3SegReaderNextDocid(
104676  Fts3SegReader *pReader,
104677  char **ppOffsetList,
104678  int *pnOffsetList
104679){
104680  char *p = pReader->pOffsetList;
104681  char c = 0;
104682
104683  /* Pointer p currently points at the first byte of an offset list. The
104684  ** following two lines advance it to point one byte past the end of
104685  ** the same offset list.
104686  */
104687  while( *p | c ) c = *p++ & 0x80;
104688  p++;
104689
104690  /* If required, populate the output variables with a pointer to and the
104691  ** size of the previous offset-list.
104692  */
104693  if( ppOffsetList ){
104694    *ppOffsetList = pReader->pOffsetList;
104695    *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
104696  }
104697
104698  /* If there are no more entries in the doclist, set pOffsetList to
104699  ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
104700  ** Fts3SegReader.pOffsetList to point to the next offset list before
104701  ** returning.
104702  */
104703  if( p>=&pReader->aDoclist[pReader->nDoclist] ){
104704    pReader->pOffsetList = 0;
104705  }else{
104706    sqlite3_int64 iDelta;
104707    pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
104708    pReader->iDocid += iDelta;
104709  }
104710}
104711
104712/*
104713** Free all allocations associated with the iterator passed as the
104714** second argument.
104715*/
104716SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *p, Fts3SegReader *pReader){
104717  if( pReader ){
104718    if( pReader->pStmt ){
104719      /* Move the leaf-range SELECT statement to the aLeavesStmt[] array,
104720      ** so that it can be reused when required by another query.
104721      */
104722      assert( p->nLeavesStmt<p->nLeavesTotal );
104723      sqlite3_reset(pReader->pStmt);
104724      p->aLeavesStmt[p->nLeavesStmt++] = pReader->pStmt;
104725    }
104726    if( !fts3SegReaderIsPending(pReader) ){
104727      sqlite3_free(pReader->zTerm);
104728    }
104729    sqlite3_free(pReader);
104730  }
104731}
104732
104733/*
104734** Allocate a new SegReader object.
104735*/
104736SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
104737  Fts3Table *p,                   /* Virtual table handle */
104738  int iAge,                       /* Segment "age". */
104739  sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
104740  sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
104741  sqlite3_int64 iEndBlock,        /* Final block of segment */
104742  const char *zRoot,              /* Buffer containing root node */
104743  int nRoot,                      /* Size of buffer containing root node */
104744  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
104745){
104746  int rc = SQLITE_OK;             /* Return code */
104747  Fts3SegReader *pReader;         /* Newly allocated SegReader object */
104748  int nExtra = 0;                 /* Bytes to allocate segment root node */
104749
104750  if( iStartLeaf==0 ){
104751    nExtra = nRoot;
104752  }
104753
104754  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
104755  if( !pReader ){
104756    return SQLITE_NOMEM;
104757  }
104758  memset(pReader, 0, sizeof(Fts3SegReader));
104759  pReader->iStartBlock = iStartLeaf;
104760  pReader->iIdx = iAge;
104761  pReader->iEndBlock = iEndBlock;
104762
104763  if( nExtra ){
104764    /* The entire segment is stored in the root node. */
104765    pReader->aNode = (char *)&pReader[1];
104766    pReader->nNode = nRoot;
104767    memcpy(pReader->aNode, zRoot, nRoot);
104768  }else{
104769    /* If the text of the SQL statement to iterate through a contiguous
104770    ** set of entries in the %_segments table has not yet been composed,
104771    ** compose it now.
104772    */
104773    if( !p->zSelectLeaves ){
104774      p->zSelectLeaves = sqlite3_mprintf(
104775          "SELECT block FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ? "
104776          "ORDER BY blockid", p->zDb, p->zName
104777      );
104778      if( !p->zSelectLeaves ){
104779        rc = SQLITE_NOMEM;
104780        goto finished;
104781      }
104782    }
104783
104784    /* If there are no free statements in the aLeavesStmt[] array, prepare
104785    ** a new statement now. Otherwise, reuse a prepared statement from
104786    ** aLeavesStmt[].
104787    */
104788    if( p->nLeavesStmt==0 ){
104789      if( p->nLeavesTotal==p->nLeavesAlloc ){
104790        int nNew = p->nLeavesAlloc + 16;
104791        sqlite3_stmt **aNew = (sqlite3_stmt **)sqlite3_realloc(
104792            p->aLeavesStmt, nNew*sizeof(sqlite3_stmt *)
104793        );
104794        if( !aNew ){
104795          rc = SQLITE_NOMEM;
104796          goto finished;
104797        }
104798        p->nLeavesAlloc = nNew;
104799        p->aLeavesStmt = aNew;
104800      }
104801      rc = sqlite3_prepare_v2(p->db, p->zSelectLeaves, -1, &pReader->pStmt, 0);
104802      if( rc!=SQLITE_OK ){
104803        goto finished;
104804      }
104805      p->nLeavesTotal++;
104806    }else{
104807      pReader->pStmt = p->aLeavesStmt[--p->nLeavesStmt];
104808    }
104809
104810    /* Bind the start and end leaf blockids to the prepared SQL statement. */
104811    sqlite3_bind_int64(pReader->pStmt, 1, iStartLeaf);
104812    sqlite3_bind_int64(pReader->pStmt, 2, iEndLeaf);
104813  }
104814  rc = fts3SegReaderNext(pReader);
104815
104816 finished:
104817  if( rc==SQLITE_OK ){
104818    *ppReader = pReader;
104819  }else{
104820    sqlite3Fts3SegReaderFree(p, pReader);
104821  }
104822  return rc;
104823}
104824
104825/*
104826** This is a comparison function used as a qsort() callback when sorting
104827** an array of pending terms by term. This occurs as part of flushing
104828** the contents of the pending-terms hash table to the database.
104829*/
104830static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
104831  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
104832  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
104833  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
104834  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
104835
104836  int n = (n1<n2 ? n1 : n2);
104837  int c = memcmp(z1, z2, n);
104838  if( c==0 ){
104839    c = n1 - n2;
104840  }
104841  return c;
104842}
104843
104844/*
104845** This function is used to allocate an Fts3SegReader that iterates through
104846** a subset of the terms stored in the Fts3Table.pendingTerms array.
104847*/
104848SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
104849  Fts3Table *p,                   /* Virtual table handle */
104850  const char *zTerm,              /* Term to search for */
104851  int nTerm,                      /* Size of buffer zTerm */
104852  int isPrefix,                   /* True for a term-prefix query */
104853  Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
104854){
104855  Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
104856  Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
104857  int nElem = 0;                  /* Size of array at aElem */
104858  int rc = SQLITE_OK;             /* Return Code */
104859
104860  if( isPrefix ){
104861    int nAlloc = 0;               /* Size of allocated array at aElem */
104862    Fts3HashElem *pE = 0;         /* Iterator variable */
104863
104864    for(pE=fts3HashFirst(&p->pendingTerms); pE; pE=fts3HashNext(pE)){
104865      char *zKey = (char *)fts3HashKey(pE);
104866      int nKey = fts3HashKeysize(pE);
104867      if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
104868        if( nElem==nAlloc ){
104869          Fts3HashElem **aElem2;
104870          nAlloc += 16;
104871          aElem2 = (Fts3HashElem **)sqlite3_realloc(
104872              aElem, nAlloc*sizeof(Fts3HashElem *)
104873          );
104874          if( !aElem2 ){
104875            rc = SQLITE_NOMEM;
104876            nElem = 0;
104877            break;
104878          }
104879          aElem = aElem2;
104880        }
104881        aElem[nElem++] = pE;
104882      }
104883    }
104884
104885    /* If more than one term matches the prefix, sort the Fts3HashElem
104886    ** objects in term order using qsort(). This uses the same comparison
104887    ** callback as is used when flushing terms to disk.
104888    */
104889    if( nElem>1 ){
104890      qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
104891    }
104892
104893  }else{
104894    Fts3HashElem *pE = fts3HashFindElem(&p->pendingTerms, zTerm, nTerm);
104895    if( pE ){
104896      aElem = &pE;
104897      nElem = 1;
104898    }
104899  }
104900
104901  if( nElem>0 ){
104902    int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
104903    pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
104904    if( !pReader ){
104905      rc = SQLITE_NOMEM;
104906    }else{
104907      memset(pReader, 0, nByte);
104908      pReader->iIdx = 0x7FFFFFFF;
104909      pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
104910      memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
104911      fts3SegReaderNext(pReader);
104912    }
104913  }
104914
104915  if( isPrefix ){
104916    sqlite3_free(aElem);
104917  }
104918  *ppReader = pReader;
104919  return rc;
104920}
104921
104922
104923/*
104924** The second argument to this function is expected to be a statement of
104925** the form:
104926**
104927**   SELECT
104928**     idx,                  -- col 0
104929**     start_block,          -- col 1
104930**     leaves_end_block,     -- col 2
104931**     end_block,            -- col 3
104932**     root                  -- col 4
104933**   FROM %_segdir ...
104934**
104935** This function allocates and initializes a Fts3SegReader structure to
104936** iterate through the terms stored in the segment identified by the
104937** current row that pStmt is pointing to.
104938**
104939** If successful, the Fts3SegReader is left pointing to the first term
104940** in the segment and SQLITE_OK is returned. Otherwise, an SQLite error
104941** code is returned.
104942*/
104943static int fts3SegReaderNew(
104944  Fts3Table *p,                   /* Virtual table handle */
104945  sqlite3_stmt *pStmt,            /* See above */
104946  int iAge,                       /* Segment "age". */
104947  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
104948){
104949  return sqlite3Fts3SegReaderNew(p, iAge,
104950      sqlite3_column_int64(pStmt, 1),
104951      sqlite3_column_int64(pStmt, 2),
104952      sqlite3_column_int64(pStmt, 3),
104953      sqlite3_column_blob(pStmt, 4),
104954      sqlite3_column_bytes(pStmt, 4),
104955      ppReader
104956  );
104957}
104958
104959/*
104960** Compare the entries pointed to by two Fts3SegReader structures.
104961** Comparison is as follows:
104962**
104963**   1) EOF is greater than not EOF.
104964**
104965**   2) The current terms (if any) are compared using memcmp(). If one
104966**      term is a prefix of another, the longer term is considered the
104967**      larger.
104968**
104969**   3) By segment age. An older segment is considered larger.
104970*/
104971static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
104972  int rc;
104973  if( pLhs->aNode && pRhs->aNode ){
104974    int rc2 = pLhs->nTerm - pRhs->nTerm;
104975    if( rc2<0 ){
104976      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
104977    }else{
104978      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
104979    }
104980    if( rc==0 ){
104981      rc = rc2;
104982    }
104983  }else{
104984    rc = (pLhs->aNode==0) - (pRhs->aNode==0);
104985  }
104986  if( rc==0 ){
104987    rc = pRhs->iIdx - pLhs->iIdx;
104988  }
104989  assert( rc!=0 );
104990  return rc;
104991}
104992
104993/*
104994** A different comparison function for SegReader structures. In this
104995** version, it is assumed that each SegReader points to an entry in
104996** a doclist for identical terms. Comparison is made as follows:
104997**
104998**   1) EOF (end of doclist in this case) is greater than not EOF.
104999**
105000**   2) By current docid.
105001**
105002**   3) By segment age. An older segment is considered larger.
105003*/
105004static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
105005  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
105006  if( rc==0 ){
105007    if( pLhs->iDocid==pRhs->iDocid ){
105008      rc = pRhs->iIdx - pLhs->iIdx;
105009    }else{
105010      rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
105011    }
105012  }
105013  assert( pLhs->aNode && pRhs->aNode );
105014  return rc;
105015}
105016
105017/*
105018** Compare the term that the Fts3SegReader object passed as the first argument
105019** points to with the term specified by arguments zTerm and nTerm.
105020**
105021** If the pSeg iterator is already at EOF, return 0. Otherwise, return
105022** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
105023** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
105024*/
105025static int fts3SegReaderTermCmp(
105026  Fts3SegReader *pSeg,            /* Segment reader object */
105027  const char *zTerm,              /* Term to compare to */
105028  int nTerm                       /* Size of term zTerm in bytes */
105029){
105030  int res = 0;
105031  if( pSeg->aNode ){
105032    if( pSeg->nTerm>nTerm ){
105033      res = memcmp(pSeg->zTerm, zTerm, nTerm);
105034    }else{
105035      res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
105036    }
105037    if( res==0 ){
105038      res = pSeg->nTerm-nTerm;
105039    }
105040  }
105041  return res;
105042}
105043
105044/*
105045** Argument apSegment is an array of nSegment elements. It is known that
105046** the final (nSegment-nSuspect) members are already in sorted order
105047** (according to the comparison function provided). This function shuffles
105048** the array around until all entries are in sorted order.
105049*/
105050static void fts3SegReaderSort(
105051  Fts3SegReader **apSegment,                     /* Array to sort entries of */
105052  int nSegment,                                  /* Size of apSegment array */
105053  int nSuspect,                                  /* Unsorted entry count */
105054  int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
105055){
105056  int i;                          /* Iterator variable */
105057
105058  assert( nSuspect<=nSegment );
105059
105060  if( nSuspect==nSegment ) nSuspect--;
105061  for(i=nSuspect-1; i>=0; i--){
105062    int j;
105063    for(j=i; j<(nSegment-1); j++){
105064      Fts3SegReader *pTmp;
105065      if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
105066      pTmp = apSegment[j+1];
105067      apSegment[j+1] = apSegment[j];
105068      apSegment[j] = pTmp;
105069    }
105070  }
105071
105072#ifndef NDEBUG
105073  /* Check that the list really is sorted now. */
105074  for(i=0; i<(nSuspect-1); i++){
105075    assert( xCmp(apSegment[i], apSegment[i+1])<0 );
105076  }
105077#endif
105078}
105079
105080/*
105081** Insert a record into the %_segments table.
105082*/
105083static int fts3WriteSegment(
105084  Fts3Table *p,                   /* Virtual table handle */
105085  sqlite3_int64 iBlock,           /* Block id for new block */
105086  char *z,                        /* Pointer to buffer containing block data */
105087  int n                           /* Size of buffer z in bytes */
105088){
105089  sqlite3_stmt *pStmt;
105090  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
105091  if( rc==SQLITE_OK ){
105092    sqlite3_bind_int64(pStmt, 1, iBlock);
105093    sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
105094    sqlite3_step(pStmt);
105095    rc = sqlite3_reset(pStmt);
105096  }
105097  return rc;
105098}
105099
105100/*
105101** Insert a record into the %_segdir table.
105102*/
105103static int fts3WriteSegdir(
105104  Fts3Table *p,                   /* Virtual table handle */
105105  int iLevel,                     /* Value for "level" field */
105106  int iIdx,                       /* Value for "idx" field */
105107  sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
105108  sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
105109  sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
105110  char *zRoot,                    /* Blob value for "root" field */
105111  int nRoot                       /* Number of bytes in buffer zRoot */
105112){
105113  sqlite3_stmt *pStmt;
105114  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
105115  if( rc==SQLITE_OK ){
105116    sqlite3_bind_int(pStmt, 1, iLevel);
105117    sqlite3_bind_int(pStmt, 2, iIdx);
105118    sqlite3_bind_int64(pStmt, 3, iStartBlock);
105119    sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
105120    sqlite3_bind_int64(pStmt, 5, iEndBlock);
105121    sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
105122    sqlite3_step(pStmt);
105123    rc = sqlite3_reset(pStmt);
105124  }
105125  return rc;
105126}
105127
105128/*
105129** Return the size of the common prefix (if any) shared by zPrev and
105130** zNext, in bytes. For example,
105131**
105132**   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
105133**   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
105134**   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
105135*/
105136static int fts3PrefixCompress(
105137  const char *zPrev,              /* Buffer containing previous term */
105138  int nPrev,                      /* Size of buffer zPrev in bytes */
105139  const char *zNext,              /* Buffer containing next term */
105140  int nNext                       /* Size of buffer zNext in bytes */
105141){
105142  int n;
105143  UNUSED_PARAMETER(nNext);
105144  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
105145  return n;
105146}
105147
105148/*
105149** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
105150** (according to memcmp) than the previous term.
105151*/
105152static int fts3NodeAddTerm(
105153  Fts3Table *p,               /* Virtual table handle */
105154  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
105155  int isCopyTerm,                 /* True if zTerm/nTerm is transient */
105156  const char *zTerm,              /* Pointer to buffer containing term */
105157  int nTerm                       /* Size of term in bytes */
105158){
105159  SegmentNode *pTree = *ppTree;
105160  int rc;
105161  SegmentNode *pNew;
105162
105163  /* First try to append the term to the current node. Return early if
105164  ** this is possible.
105165  */
105166  if( pTree ){
105167    int nData = pTree->nData;     /* Current size of node in bytes */
105168    int nReq = nData;             /* Required space after adding zTerm */
105169    int nPrefix;                  /* Number of bytes of prefix compression */
105170    int nSuffix;                  /* Suffix length */
105171
105172    nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
105173    nSuffix = nTerm-nPrefix;
105174
105175    nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
105176    if( nReq<=p->nNodeSize || !pTree->zTerm ){
105177
105178      if( nReq>p->nNodeSize ){
105179        /* An unusual case: this is the first term to be added to the node
105180        ** and the static node buffer (p->nNodeSize bytes) is not large
105181        ** enough. Use a separately malloced buffer instead This wastes
105182        ** p->nNodeSize bytes, but since this scenario only comes about when
105183        ** the database contain two terms that share a prefix of almost 2KB,
105184        ** this is not expected to be a serious problem.
105185        */
105186        assert( pTree->aData==(char *)&pTree[1] );
105187        pTree->aData = (char *)sqlite3_malloc(nReq);
105188        if( !pTree->aData ){
105189          return SQLITE_NOMEM;
105190        }
105191      }
105192
105193      if( pTree->zTerm ){
105194        /* There is no prefix-length field for first term in a node */
105195        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
105196      }
105197
105198      nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
105199      memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
105200      pTree->nData = nData + nSuffix;
105201      pTree->nEntry++;
105202
105203      if( isCopyTerm ){
105204        if( pTree->nMalloc<nTerm ){
105205          char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
105206          if( !zNew ){
105207            return SQLITE_NOMEM;
105208          }
105209          pTree->nMalloc = nTerm*2;
105210          pTree->zMalloc = zNew;
105211        }
105212        pTree->zTerm = pTree->zMalloc;
105213        memcpy(pTree->zTerm, zTerm, nTerm);
105214        pTree->nTerm = nTerm;
105215      }else{
105216        pTree->zTerm = (char *)zTerm;
105217        pTree->nTerm = nTerm;
105218      }
105219      return SQLITE_OK;
105220    }
105221  }
105222
105223  /* If control flows to here, it was not possible to append zTerm to the
105224  ** current node. Create a new node (a right-sibling of the current node).
105225  ** If this is the first node in the tree, the term is added to it.
105226  **
105227  ** Otherwise, the term is not added to the new node, it is left empty for
105228  ** now. Instead, the term is inserted into the parent of pTree. If pTree
105229  ** has no parent, one is created here.
105230  */
105231  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
105232  if( !pNew ){
105233    return SQLITE_NOMEM;
105234  }
105235  memset(pNew, 0, sizeof(SegmentNode));
105236  pNew->nData = 1 + FTS3_VARINT_MAX;
105237  pNew->aData = (char *)&pNew[1];
105238
105239  if( pTree ){
105240    SegmentNode *pParent = pTree->pParent;
105241    rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
105242    if( pTree->pParent==0 ){
105243      pTree->pParent = pParent;
105244    }
105245    pTree->pRight = pNew;
105246    pNew->pLeftmost = pTree->pLeftmost;
105247    pNew->pParent = pParent;
105248    pNew->zMalloc = pTree->zMalloc;
105249    pNew->nMalloc = pTree->nMalloc;
105250    pTree->zMalloc = 0;
105251  }else{
105252    pNew->pLeftmost = pNew;
105253    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
105254  }
105255
105256  *ppTree = pNew;
105257  return rc;
105258}
105259
105260/*
105261** Helper function for fts3NodeWrite().
105262*/
105263static int fts3TreeFinishNode(
105264  SegmentNode *pTree,
105265  int iHeight,
105266  sqlite3_int64 iLeftChild
105267){
105268  int nStart;
105269  assert( iHeight>=1 && iHeight<128 );
105270  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
105271  pTree->aData[nStart] = (char)iHeight;
105272  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
105273  return nStart;
105274}
105275
105276/*
105277** Write the buffer for the segment node pTree and all of its peers to the
105278** database. Then call this function recursively to write the parent of
105279** pTree and its peers to the database.
105280**
105281** Except, if pTree is a root node, do not write it to the database. Instead,
105282** set output variables *paRoot and *pnRoot to contain the root node.
105283**
105284** If successful, SQLITE_OK is returned and output variable *piLast is
105285** set to the largest blockid written to the database (or zero if no
105286** blocks were written to the db). Otherwise, an SQLite error code is
105287** returned.
105288*/
105289static int fts3NodeWrite(
105290  Fts3Table *p,                   /* Virtual table handle */
105291  SegmentNode *pTree,             /* SegmentNode handle */
105292  int iHeight,                    /* Height of this node in tree */
105293  sqlite3_int64 iLeaf,            /* Block id of first leaf node */
105294  sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
105295  sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
105296  char **paRoot,                  /* OUT: Data for root node */
105297  int *pnRoot                     /* OUT: Size of root node in bytes */
105298){
105299  int rc = SQLITE_OK;
105300
105301  if( !pTree->pParent ){
105302    /* Root node of the tree. */
105303    int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
105304    *piLast = iFree-1;
105305    *pnRoot = pTree->nData - nStart;
105306    *paRoot = &pTree->aData[nStart];
105307  }else{
105308    SegmentNode *pIter;
105309    sqlite3_int64 iNextFree = iFree;
105310    sqlite3_int64 iNextLeaf = iLeaf;
105311    for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
105312      int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
105313      int nWrite = pIter->nData - nStart;
105314
105315      rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
105316      iNextFree++;
105317      iNextLeaf += (pIter->nEntry+1);
105318    }
105319    if( rc==SQLITE_OK ){
105320      assert( iNextLeaf==iFree );
105321      rc = fts3NodeWrite(
105322          p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
105323      );
105324    }
105325  }
105326
105327  return rc;
105328}
105329
105330/*
105331** Free all memory allocations associated with the tree pTree.
105332*/
105333static void fts3NodeFree(SegmentNode *pTree){
105334  if( pTree ){
105335    SegmentNode *p = pTree->pLeftmost;
105336    fts3NodeFree(p->pParent);
105337    while( p ){
105338      SegmentNode *pRight = p->pRight;
105339      if( p->aData!=(char *)&p[1] ){
105340        sqlite3_free(p->aData);
105341      }
105342      assert( pRight==0 || p->zMalloc==0 );
105343      sqlite3_free(p->zMalloc);
105344      sqlite3_free(p);
105345      p = pRight;
105346    }
105347  }
105348}
105349
105350/*
105351** Add a term to the segment being constructed by the SegmentWriter object
105352** *ppWriter. When adding the first term to a segment, *ppWriter should
105353** be passed NULL. This function will allocate a new SegmentWriter object
105354** and return it via the input/output variable *ppWriter in this case.
105355**
105356** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
105357*/
105358static int fts3SegWriterAdd(
105359  Fts3Table *p,                   /* Virtual table handle */
105360  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
105361  int isCopyTerm,                 /* True if buffer zTerm must be copied */
105362  const char *zTerm,              /* Pointer to buffer containing term */
105363  int nTerm,                      /* Size of term in bytes */
105364  const char *aDoclist,           /* Pointer to buffer containing doclist */
105365  int nDoclist                    /* Size of doclist in bytes */
105366){
105367  int nPrefix;                    /* Size of term prefix in bytes */
105368  int nSuffix;                    /* Size of term suffix in bytes */
105369  int nReq;                       /* Number of bytes required on leaf page */
105370  int nData;
105371  SegmentWriter *pWriter = *ppWriter;
105372
105373  if( !pWriter ){
105374    int rc;
105375    sqlite3_stmt *pStmt;
105376
105377    /* Allocate the SegmentWriter structure */
105378    pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
105379    if( !pWriter ) return SQLITE_NOMEM;
105380    memset(pWriter, 0, sizeof(SegmentWriter));
105381    *ppWriter = pWriter;
105382
105383    /* Allocate a buffer in which to accumulate data */
105384    pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
105385    if( !pWriter->aData ) return SQLITE_NOMEM;
105386    pWriter->nSize = p->nNodeSize;
105387
105388    /* Find the next free blockid in the %_segments table */
105389    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
105390    if( rc!=SQLITE_OK ) return rc;
105391    if( SQLITE_ROW==sqlite3_step(pStmt) ){
105392      pWriter->iFree = sqlite3_column_int64(pStmt, 0);
105393      pWriter->iFirst = pWriter->iFree;
105394    }
105395    rc = sqlite3_reset(pStmt);
105396    if( rc!=SQLITE_OK ) return rc;
105397  }
105398  nData = pWriter->nData;
105399
105400  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
105401  nSuffix = nTerm-nPrefix;
105402
105403  /* Figure out how many bytes are required by this new entry */
105404  nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
105405    sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
105406    nSuffix +                               /* Term suffix */
105407    sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
105408    nDoclist;                               /* Doclist data */
105409
105410  if( nData>0 && nData+nReq>p->nNodeSize ){
105411    int rc;
105412
105413    /* The current leaf node is full. Write it out to the database. */
105414    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
105415    if( rc!=SQLITE_OK ) return rc;
105416
105417    /* Add the current term to the interior node tree. The term added to
105418    ** the interior tree must:
105419    **
105420    **   a) be greater than the largest term on the leaf node just written
105421    **      to the database (still available in pWriter->zTerm), and
105422    **
105423    **   b) be less than or equal to the term about to be added to the new
105424    **      leaf node (zTerm/nTerm).
105425    **
105426    ** In other words, it must be the prefix of zTerm 1 byte longer than
105427    ** the common prefix (if any) of zTerm and pWriter->zTerm.
105428    */
105429    assert( nPrefix<nTerm );
105430    rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
105431    if( rc!=SQLITE_OK ) return rc;
105432
105433    nData = 0;
105434    pWriter->nTerm = 0;
105435
105436    nPrefix = 0;
105437    nSuffix = nTerm;
105438    nReq = 1 +                              /* varint containing prefix size */
105439      sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
105440      nTerm +                               /* Term suffix */
105441      sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
105442      nDoclist;                             /* Doclist data */
105443  }
105444
105445  /* If the buffer currently allocated is too small for this entry, realloc
105446  ** the buffer to make it large enough.
105447  */
105448  if( nReq>pWriter->nSize ){
105449    char *aNew = sqlite3_realloc(pWriter->aData, nReq);
105450    if( !aNew ) return SQLITE_NOMEM;
105451    pWriter->aData = aNew;
105452    pWriter->nSize = nReq;
105453  }
105454  assert( nData+nReq<=pWriter->nSize );
105455
105456  /* Append the prefix-compressed term and doclist to the buffer. */
105457  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
105458  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
105459  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
105460  nData += nSuffix;
105461  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
105462  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
105463  pWriter->nData = nData + nDoclist;
105464
105465  /* Save the current term so that it can be used to prefix-compress the next.
105466  ** If the isCopyTerm parameter is true, then the buffer pointed to by
105467  ** zTerm is transient, so take a copy of the term data. Otherwise, just
105468  ** store a copy of the pointer.
105469  */
105470  if( isCopyTerm ){
105471    if( nTerm>pWriter->nMalloc ){
105472      char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
105473      if( !zNew ){
105474        return SQLITE_NOMEM;
105475      }
105476      pWriter->nMalloc = nTerm*2;
105477      pWriter->zMalloc = zNew;
105478      pWriter->zTerm = zNew;
105479    }
105480    assert( pWriter->zTerm==pWriter->zMalloc );
105481    memcpy(pWriter->zTerm, zTerm, nTerm);
105482  }else{
105483    pWriter->zTerm = (char *)zTerm;
105484  }
105485  pWriter->nTerm = nTerm;
105486
105487  return SQLITE_OK;
105488}
105489
105490/*
105491** Flush all data associated with the SegmentWriter object pWriter to the
105492** database. This function must be called after all terms have been added
105493** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
105494** returned. Otherwise, an SQLite error code.
105495*/
105496static int fts3SegWriterFlush(
105497  Fts3Table *p,                   /* Virtual table handle */
105498  SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
105499  int iLevel,                     /* Value for 'level' column of %_segdir */
105500  int iIdx                        /* Value for 'idx' column of %_segdir */
105501){
105502  int rc;                         /* Return code */
105503  if( pWriter->pTree ){
105504    sqlite3_int64 iLast = 0;      /* Largest block id written to database */
105505    sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
105506    char *zRoot = NULL;           /* Pointer to buffer containing root node */
105507    int nRoot = 0;                /* Size of buffer zRoot */
105508
105509    iLastLeaf = pWriter->iFree;
105510    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
105511    if( rc==SQLITE_OK ){
105512      rc = fts3NodeWrite(p, pWriter->pTree, 1,
105513          pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
105514    }
105515    if( rc==SQLITE_OK ){
105516      rc = fts3WriteSegdir(
105517          p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
105518    }
105519  }else{
105520    /* The entire tree fits on the root node. Write it to the segdir table. */
105521    rc = fts3WriteSegdir(
105522        p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
105523  }
105524  return rc;
105525}
105526
105527/*
105528** Release all memory held by the SegmentWriter object passed as the
105529** first argument.
105530*/
105531static void fts3SegWriterFree(SegmentWriter *pWriter){
105532  if( pWriter ){
105533    sqlite3_free(pWriter->aData);
105534    sqlite3_free(pWriter->zMalloc);
105535    fts3NodeFree(pWriter->pTree);
105536    sqlite3_free(pWriter);
105537  }
105538}
105539
105540/*
105541** The first value in the apVal[] array is assumed to contain an integer.
105542** This function tests if there exist any documents with docid values that
105543** are different from that integer. i.e. if deleting the document with docid
105544** apVal[0] would mean the FTS3 table were empty.
105545**
105546** If successful, *pisEmpty is set to true if the table is empty except for
105547** document apVal[0], or false otherwise, and SQLITE_OK is returned. If an
105548** error occurs, an SQLite error code is returned.
105549*/
105550static int fts3IsEmpty(Fts3Table *p, sqlite3_value **apVal, int *pisEmpty){
105551  sqlite3_stmt *pStmt;
105552  int rc;
105553  rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, apVal);
105554  if( rc==SQLITE_OK ){
105555    if( SQLITE_ROW==sqlite3_step(pStmt) ){
105556      *pisEmpty = sqlite3_column_int(pStmt, 0);
105557    }
105558    rc = sqlite3_reset(pStmt);
105559  }
105560  return rc;
105561}
105562
105563/*
105564** Set *pnSegment to the number of segments of level iLevel in the database.
105565**
105566** Return SQLITE_OK if successful, or an SQLite error code if not.
105567*/
105568static int fts3SegmentCount(Fts3Table *p, int iLevel, int *pnSegment){
105569  sqlite3_stmt *pStmt;
105570  int rc;
105571
105572  assert( iLevel>=0 );
105573  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_COUNT, &pStmt, 0);
105574  if( rc!=SQLITE_OK ) return rc;
105575  sqlite3_bind_int(pStmt, 1, iLevel);
105576  if( SQLITE_ROW==sqlite3_step(pStmt) ){
105577    *pnSegment = sqlite3_column_int(pStmt, 0);
105578  }
105579  return sqlite3_reset(pStmt);
105580}
105581
105582/*
105583** Set *pnSegment to the total number of segments in the database. Set
105584** *pnMax to the largest segment level in the database (segment levels
105585** are stored in the 'level' column of the %_segdir table).
105586**
105587** Return SQLITE_OK if successful, or an SQLite error code if not.
105588*/
105589static int fts3SegmentCountMax(Fts3Table *p, int *pnSegment, int *pnMax){
105590  sqlite3_stmt *pStmt;
105591  int rc;
105592
105593  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_COUNT_MAX, &pStmt, 0);
105594  if( rc!=SQLITE_OK ) return rc;
105595  if( SQLITE_ROW==sqlite3_step(pStmt) ){
105596    *pnSegment = sqlite3_column_int(pStmt, 0);
105597    *pnMax = sqlite3_column_int(pStmt, 1);
105598  }
105599  return sqlite3_reset(pStmt);
105600}
105601
105602/*
105603** This function is used after merging multiple segments into a single large
105604** segment to delete the old, now redundant, segment b-trees. Specifically,
105605** it:
105606**
105607**   1) Deletes all %_segments entries for the segments associated with
105608**      each of the SegReader objects in the array passed as the third
105609**      argument, and
105610**
105611**   2) deletes all %_segdir entries with level iLevel, or all %_segdir
105612**      entries regardless of level if (iLevel<0).
105613**
105614** SQLITE_OK is returned if successful, otherwise an SQLite error code.
105615*/
105616static int fts3DeleteSegdir(
105617  Fts3Table *p,                   /* Virtual table handle */
105618  int iLevel,                     /* Level of %_segdir entries to delete */
105619  Fts3SegReader **apSegment,      /* Array of SegReader objects */
105620  int nReader                     /* Size of array apSegment */
105621){
105622  int rc;                         /* Return Code */
105623  int i;                          /* Iterator variable */
105624  sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
105625
105626  rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
105627  for(i=0; rc==SQLITE_OK && i<nReader; i++){
105628    Fts3SegReader *pSegment = apSegment[i];
105629    if( pSegment->iStartBlock ){
105630      sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
105631      sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
105632      sqlite3_step(pDelete);
105633      rc = sqlite3_reset(pDelete);
105634    }
105635  }
105636  if( rc!=SQLITE_OK ){
105637    return rc;
105638  }
105639
105640  if( iLevel>=0 ){
105641    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_BY_LEVEL, &pDelete, 0);
105642    if( rc==SQLITE_OK ){
105643      sqlite3_bind_int(pDelete, 1, iLevel);
105644      sqlite3_step(pDelete);
105645      rc = sqlite3_reset(pDelete);
105646    }
105647  }else{
105648    rc = fts3SqlExec(p, SQL_DELETE_ALL_SEGDIR, 0);
105649  }
105650
105651  return rc;
105652}
105653
105654/*
105655** When this function is called, buffer *ppList (size *pnList bytes) contains
105656** a position list that may (or may not) feature multiple columns. This
105657** function adjusts the pointer *ppList and the length *pnList so that they
105658** identify the subset of the position list that corresponds to column iCol.
105659**
105660** If there are no entries in the input position list for column iCol, then
105661** *pnList is set to zero before returning.
105662*/
105663static void fts3ColumnFilter(
105664  int iCol,                       /* Column to filter on */
105665  char **ppList,                  /* IN/OUT: Pointer to position list */
105666  int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
105667){
105668  char *pList = *ppList;
105669  int nList = *pnList;
105670  char *pEnd = &pList[nList];
105671  int iCurrent = 0;
105672  char *p = pList;
105673
105674  assert( iCol>=0 );
105675  while( 1 ){
105676    char c = 0;
105677    while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
105678
105679    if( iCol==iCurrent ){
105680      nList = (int)(p - pList);
105681      break;
105682    }
105683
105684    nList -= (int)(p - pList);
105685    pList = p;
105686    if( nList==0 ){
105687      break;
105688    }
105689    p = &pList[1];
105690    p += sqlite3Fts3GetVarint32(p, &iCurrent);
105691  }
105692
105693  *ppList = pList;
105694  *pnList = nList;
105695}
105696
105697/*
105698** sqlite3Fts3SegReaderIterate() callback used when merging multiple
105699** segments to create a single, larger segment.
105700*/
105701static int fts3MergeCallback(
105702  Fts3Table *p,                   /* FTS3 Virtual table handle */
105703  void *pContext,                 /* Pointer to SegmentWriter* to write with */
105704  char *zTerm,                    /* Term to write to the db */
105705  int nTerm,                      /* Number of bytes in zTerm */
105706  char *aDoclist,                 /* Doclist associated with zTerm */
105707  int nDoclist                    /* Number of bytes in doclist */
105708){
105709  SegmentWriter **ppW = (SegmentWriter **)pContext;
105710  return fts3SegWriterAdd(p, ppW, 1, zTerm, nTerm, aDoclist, nDoclist);
105711}
105712
105713/*
105714** sqlite3Fts3SegReaderIterate() callback used when flushing the contents
105715** of the pending-terms hash table to the database.
105716*/
105717static int fts3FlushCallback(
105718  Fts3Table *p,                   /* FTS3 Virtual table handle */
105719  void *pContext,                 /* Pointer to SegmentWriter* to write with */
105720  char *zTerm,                    /* Term to write to the db */
105721  int nTerm,                      /* Number of bytes in zTerm */
105722  char *aDoclist,                 /* Doclist associated with zTerm */
105723  int nDoclist                    /* Number of bytes in doclist */
105724){
105725  SegmentWriter **ppW = (SegmentWriter **)pContext;
105726  return fts3SegWriterAdd(p, ppW, 0, zTerm, nTerm, aDoclist, nDoclist);
105727}
105728
105729/*
105730** This function is used to iterate through a contiguous set of terms
105731** stored in the full-text index. It merges data contained in one or
105732** more segments to support this.
105733**
105734** The second argument is passed an array of pointers to SegReader objects
105735** allocated with sqlite3Fts3SegReaderNew(). This function merges the range
105736** of terms selected by each SegReader. If a single term is present in
105737** more than one segment, the associated doclists are merged. For each
105738** term and (possibly merged) doclist in the merged range, the callback
105739** function xFunc is invoked with its arguments set as follows.
105740**
105741**   arg 0: Copy of 'p' parameter passed to this function
105742**   arg 1: Copy of 'pContext' parameter passed to this function
105743**   arg 2: Pointer to buffer containing term
105744**   arg 3: Size of arg 2 buffer in bytes
105745**   arg 4: Pointer to buffer containing doclist
105746**   arg 5: Size of arg 2 buffer in bytes
105747**
105748** The 4th argument to this function is a pointer to a structure of type
105749** Fts3SegFilter, defined in fts3Int.h. The contents of this structure
105750** further restrict the range of terms that callbacks are made for and
105751** modify the behaviour of this function. See comments above structure
105752** definition for details.
105753*/
105754SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
105755  Fts3Table *p,                   /* Virtual table handle */
105756  Fts3SegReader **apSegment,      /* Array of Fts3SegReader objects */
105757  int nSegment,                   /* Size of apSegment array */
105758  Fts3SegFilter *pFilter,         /* Restrictions on range of iteration */
105759  int (*xFunc)(Fts3Table *, void *, char *, int, char *, int),  /* Callback */
105760  void *pContext                  /* Callback context (2nd argument) */
105761){
105762  int i;                          /* Iterator variable */
105763  char *aBuffer = 0;              /* Buffer to merge doclists in */
105764  int nAlloc = 0;                 /* Allocated size of aBuffer buffer */
105765  int rc = SQLITE_OK;             /* Return code */
105766
105767  int isIgnoreEmpty =  (pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
105768  int isRequirePos =   (pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
105769  int isColFilter =    (pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
105770  int isPrefix =       (pFilter->flags & FTS3_SEGMENT_PREFIX);
105771
105772  /* If there are zero segments, this function is a no-op. This scenario
105773  ** comes about only when reading from an empty database.
105774  */
105775  if( nSegment==0 ) goto finished;
105776
105777  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
105778  ** for, then advance each segment iterator until it points to a term of
105779  ** equal or greater value than the specified term. This prevents many
105780  ** unnecessary merge/sort operations for the case where single segment
105781  ** b-tree leaf nodes contain more than one term.
105782  */
105783  if( pFilter->zTerm ){
105784    int nTerm = pFilter->nTerm;
105785    const char *zTerm = pFilter->zTerm;
105786    for(i=0; i<nSegment; i++){
105787      Fts3SegReader *pSeg = apSegment[i];
105788      while( fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 ){
105789        rc = fts3SegReaderNext(pSeg);
105790        if( rc!=SQLITE_OK ) goto finished; }
105791    }
105792  }
105793
105794  fts3SegReaderSort(apSegment, nSegment, nSegment, fts3SegReaderCmp);
105795  while( apSegment[0]->aNode ){
105796    int nTerm = apSegment[0]->nTerm;
105797    char *zTerm = apSegment[0]->zTerm;
105798    int nMerge = 1;
105799
105800    /* If this is a prefix-search, and if the term that apSegment[0] points
105801    ** to does not share a suffix with pFilter->zTerm/nTerm, then all
105802    ** required callbacks have been made. In this case exit early.
105803    **
105804    ** Similarly, if this is a search for an exact match, and the first term
105805    ** of segment apSegment[0] is not a match, exit early.
105806    */
105807    if( pFilter->zTerm ){
105808      if( nTerm<pFilter->nTerm
105809       || (!isPrefix && nTerm>pFilter->nTerm)
105810       || memcmp(zTerm, pFilter->zTerm, pFilter->nTerm)
105811    ){
105812        goto finished;
105813      }
105814    }
105815
105816    while( nMerge<nSegment
105817        && apSegment[nMerge]->aNode
105818        && apSegment[nMerge]->nTerm==nTerm
105819        && 0==memcmp(zTerm, apSegment[nMerge]->zTerm, nTerm)
105820    ){
105821      nMerge++;
105822    }
105823
105824    assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
105825    if( nMerge==1 && !isIgnoreEmpty ){
105826      Fts3SegReader *p0 = apSegment[0];
105827      rc = xFunc(p, pContext, zTerm, nTerm, p0->aDoclist, p0->nDoclist);
105828      if( rc!=SQLITE_OK ) goto finished;
105829    }else{
105830      int nDoclist = 0;           /* Size of doclist */
105831      sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
105832
105833      /* The current term of the first nMerge entries in the array
105834      ** of Fts3SegReader objects is the same. The doclists must be merged
105835      ** and a single term added to the new segment.
105836      */
105837      for(i=0; i<nMerge; i++){
105838        fts3SegReaderFirstDocid(apSegment[i]);
105839      }
105840      fts3SegReaderSort(apSegment, nMerge, nMerge, fts3SegReaderDoclistCmp);
105841      while( apSegment[0]->pOffsetList ){
105842        int j;                    /* Number of segments that share a docid */
105843        char *pList;
105844        int nList;
105845        int nByte;
105846        sqlite3_int64 iDocid = apSegment[0]->iDocid;
105847        fts3SegReaderNextDocid(apSegment[0], &pList, &nList);
105848        j = 1;
105849        while( j<nMerge
105850            && apSegment[j]->pOffsetList
105851            && apSegment[j]->iDocid==iDocid
105852        ){
105853          fts3SegReaderNextDocid(apSegment[j], 0, 0);
105854          j++;
105855        }
105856
105857        if( isColFilter ){
105858          fts3ColumnFilter(pFilter->iCol, &pList, &nList);
105859        }
105860
105861        if( !isIgnoreEmpty || nList>0 ){
105862          nByte = sqlite3Fts3VarintLen(iDocid-iPrev) + (isRequirePos?nList+1:0);
105863          if( nDoclist+nByte>nAlloc ){
105864            char *aNew;
105865            nAlloc = nDoclist+nByte*2;
105866            aNew = sqlite3_realloc(aBuffer, nAlloc);
105867            if( !aNew ){
105868              rc = SQLITE_NOMEM;
105869              goto finished;
105870            }
105871            aBuffer = aNew;
105872          }
105873          nDoclist += sqlite3Fts3PutVarint(&aBuffer[nDoclist], iDocid-iPrev);
105874          iPrev = iDocid;
105875          if( isRequirePos ){
105876            memcpy(&aBuffer[nDoclist], pList, nList);
105877            nDoclist += nList;
105878            aBuffer[nDoclist++] = '\0';
105879          }
105880        }
105881
105882        fts3SegReaderSort(apSegment, nMerge, j, fts3SegReaderDoclistCmp);
105883      }
105884
105885      if( nDoclist>0 ){
105886        rc = xFunc(p, pContext, zTerm, nTerm, aBuffer, nDoclist);
105887        if( rc!=SQLITE_OK ) goto finished;
105888      }
105889    }
105890
105891    /* If there is a term specified to filter on, and this is not a prefix
105892    ** search, return now. The callback that corresponds to the required
105893    ** term (if such a term exists in the index) has already been made.
105894    */
105895    if( pFilter->zTerm && !isPrefix ){
105896      goto finished;
105897    }
105898
105899    for(i=0; i<nMerge; i++){
105900      rc = fts3SegReaderNext(apSegment[i]);
105901      if( rc!=SQLITE_OK ) goto finished;
105902    }
105903    fts3SegReaderSort(apSegment, nSegment, nMerge, fts3SegReaderCmp);
105904  }
105905
105906 finished:
105907  sqlite3_free(aBuffer);
105908  return rc;
105909}
105910
105911/*
105912** Merge all level iLevel segments in the database into a single
105913** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
105914** single segment with a level equal to the numerically largest level
105915** currently present in the database.
105916**
105917** If this function is called with iLevel<0, but there is only one
105918** segment in the database, SQLITE_DONE is returned immediately.
105919** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
105920** an SQLite error code is returned.
105921*/
105922static int fts3SegmentMerge(Fts3Table *p, int iLevel){
105923  int i;                          /* Iterator variable */
105924  int rc;                         /* Return code */
105925  int iIdx;                       /* Index of new segment */
105926  int iNewLevel;                  /* Level to create new segment at */
105927  sqlite3_stmt *pStmt = 0;
105928  SegmentWriter *pWriter = 0;
105929  int nSegment = 0;               /* Number of segments being merged */
105930  Fts3SegReader **apSegment = 0;  /* Array of Segment iterators */
105931  Fts3SegReader *pPending = 0;    /* Iterator for pending-terms */
105932  Fts3SegFilter filter;           /* Segment term filter condition */
105933
105934  if( iLevel<0 ){
105935    /* This call is to merge all segments in the database to a single
105936    ** segment. The level of the new segment is equal to the the numerically
105937    ** greatest segment level currently present in the database. The index
105938    ** of the new segment is always 0.
105939    */
105940    iIdx = 0;
105941    rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pPending);
105942    if( rc!=SQLITE_OK ) goto finished;
105943    rc = fts3SegmentCountMax(p, &nSegment, &iNewLevel);
105944    if( rc!=SQLITE_OK ) goto finished;
105945    nSegment += (pPending!=0);
105946    if( nSegment<=1 ){
105947      return SQLITE_DONE;
105948    }
105949  }else{
105950    /* This call is to merge all segments at level iLevel. Find the next
105951    ** available segment index at level iLevel+1. The call to
105952    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
105953    ** a single iLevel+2 segment if necessary.
105954    */
105955    iNewLevel = iLevel+1;
105956    rc = fts3AllocateSegdirIdx(p, iNewLevel, &iIdx);
105957    if( rc!=SQLITE_OK ) goto finished;
105958    rc = fts3SegmentCount(p, iLevel, &nSegment);
105959    if( rc!=SQLITE_OK ) goto finished;
105960  }
105961  assert( nSegment>0 );
105962  assert( iNewLevel>=0 );
105963
105964  /* Allocate space for an array of pointers to segment iterators. */
105965  apSegment = (Fts3SegReader**)sqlite3_malloc(sizeof(Fts3SegReader *)*nSegment);
105966  if( !apSegment ){
105967    rc = SQLITE_NOMEM;
105968    goto finished;
105969  }
105970  memset(apSegment, 0, sizeof(Fts3SegReader *)*nSegment);
105971
105972  /* Allocate a Fts3SegReader structure for each segment being merged. A
105973  ** Fts3SegReader stores the state data required to iterate through all
105974  ** entries on all leaves of a single segment.
105975  */
105976  assert( SQL_SELECT_LEVEL+1==SQL_SELECT_ALL_LEVEL);
105977  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL+(iLevel<0), &pStmt, 0);
105978  if( rc!=SQLITE_OK ) goto finished;
105979  sqlite3_bind_int(pStmt, 1, iLevel);
105980  for(i=0; SQLITE_ROW==(sqlite3_step(pStmt)); i++){
105981    rc = fts3SegReaderNew(p, pStmt, i, &apSegment[i]);
105982    if( rc!=SQLITE_OK ){
105983      goto finished;
105984    }
105985  }
105986  rc = sqlite3_reset(pStmt);
105987  if( pPending ){
105988    apSegment[i] = pPending;
105989    pPending = 0;
105990  }
105991  pStmt = 0;
105992  if( rc!=SQLITE_OK ) goto finished;
105993
105994  memset(&filter, 0, sizeof(Fts3SegFilter));
105995  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
105996  filter.flags |= (iLevel<0 ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
105997  rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment,
105998      &filter, fts3MergeCallback, (void *)&pWriter
105999  );
106000  if( rc!=SQLITE_OK ) goto finished;
106001
106002  rc = fts3DeleteSegdir(p, iLevel, apSegment, nSegment);
106003  if( rc==SQLITE_OK ){
106004    rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
106005  }
106006
106007 finished:
106008  fts3SegWriterFree(pWriter);
106009  if( apSegment ){
106010    for(i=0; i<nSegment; i++){
106011      sqlite3Fts3SegReaderFree(p, apSegment[i]);
106012    }
106013    sqlite3_free(apSegment);
106014  }
106015  sqlite3Fts3SegReaderFree(p, pPending);
106016  sqlite3_reset(pStmt);
106017  return rc;
106018}
106019
106020
106021/*
106022** Flush the contents of pendingTerms to a level 0 segment.
106023*/
106024SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
106025  int rc;                         /* Return Code */
106026  int idx;                        /* Index of new segment created */
106027  SegmentWriter *pWriter = 0;     /* Used to write the segment */
106028  Fts3SegReader *pReader = 0;     /* Used to iterate through the hash table */
106029
106030  /* Allocate a SegReader object to iterate through the contents of the
106031  ** pending-terms table. If an error occurs, or if there are no terms
106032  ** in the pending-terms table, return immediately.
106033  */
106034  rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pReader);
106035  if( rc!=SQLITE_OK || pReader==0 ){
106036    return rc;
106037  }
106038
106039  /* Determine the next index at level 0. If level 0 is already full, this
106040  ** call may merge all existing level 0 segments into a single level 1
106041  ** segment.
106042  */
106043  rc = fts3AllocateSegdirIdx(p, 0, &idx);
106044
106045  /* If no errors have occured, iterate through the contents of the
106046  ** pending-terms hash table using the Fts3SegReader iterator. The callback
106047  ** writes each term (along with its doclist) to the database via the
106048  ** SegmentWriter handle pWriter.
106049  */
106050  if( rc==SQLITE_OK ){
106051    void *c = (void *)&pWriter;   /* SegReaderIterate() callback context */
106052    Fts3SegFilter f;              /* SegReaderIterate() parameters */
106053
106054    memset(&f, 0, sizeof(Fts3SegFilter));
106055    f.flags = FTS3_SEGMENT_REQUIRE_POS;
106056    rc = sqlite3Fts3SegReaderIterate(p, &pReader, 1, &f, fts3FlushCallback, c);
106057  }
106058  assert( pWriter || rc!=SQLITE_OK );
106059
106060  /* If no errors have occured, flush the SegmentWriter object to the
106061  ** database. Then delete the SegmentWriter and Fts3SegReader objects
106062  ** allocated by this function.
106063  */
106064  if( rc==SQLITE_OK ){
106065    rc = fts3SegWriterFlush(p, pWriter, 0, idx);
106066  }
106067  fts3SegWriterFree(pWriter);
106068  sqlite3Fts3SegReaderFree(p, pReader);
106069
106070  if( rc==SQLITE_OK ){
106071    sqlite3Fts3PendingTermsClear(p);
106072  }
106073  return rc;
106074}
106075
106076/*
106077** Handle a 'special' INSERT of the form:
106078**
106079**   "INSERT INTO tbl(tbl) VALUES(<expr>)"
106080**
106081** Argument pVal contains the result of <expr>. Currently the only
106082** meaningful value to insert is the text 'optimize'.
106083*/
106084static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
106085  int rc;                         /* Return Code */
106086  const char *zVal = (const char *)sqlite3_value_text(pVal);
106087  int nVal = sqlite3_value_bytes(pVal);
106088
106089  if( !zVal ){
106090    return SQLITE_NOMEM;
106091  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
106092    rc = fts3SegmentMerge(p, -1);
106093    if( rc==SQLITE_DONE ){
106094      rc = SQLITE_OK;
106095    }else{
106096      sqlite3Fts3PendingTermsClear(p);
106097    }
106098#ifdef SQLITE_TEST
106099  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
106100    p->nNodeSize = atoi(&zVal[9]);
106101    rc = SQLITE_OK;
106102  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
106103    p->nMaxPendingData = atoi(&zVal[11]);
106104    rc = SQLITE_OK;
106105#endif
106106  }else{
106107    rc = SQLITE_ERROR;
106108  }
106109
106110  return rc;
106111}
106112
106113/*
106114** This function does the work for the xUpdate method of FTS3 virtual
106115** tables.
106116*/
106117SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
106118  sqlite3_vtab *pVtab,            /* FTS3 vtab object */
106119  int nArg,                       /* Size of argument array */
106120  sqlite3_value **apVal,          /* Array of arguments */
106121  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
106122){
106123  Fts3Table *p = (Fts3Table *)pVtab;
106124  int rc = SQLITE_OK;             /* Return Code */
106125  int isRemove = 0;               /* True for an UPDATE or DELETE */
106126  sqlite3_int64 iRemove = 0;      /* Rowid removed by UPDATE or DELETE */
106127
106128
106129  /* If this is a DELETE or UPDATE operation, remove the old record. */
106130  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
106131    int isEmpty;
106132    rc = fts3IsEmpty(p, apVal, &isEmpty);
106133    if( rc==SQLITE_OK ){
106134      if( isEmpty ){
106135        /* Deleting this row means the whole table is empty. In this case
106136        ** delete the contents of all three tables and throw away any
106137        ** data in the pendingTerms hash table.
106138        */
106139        rc = fts3DeleteAll(p);
106140      }else{
106141        isRemove = 1;
106142        iRemove = sqlite3_value_int64(apVal[0]);
106143        rc = fts3PendingTermsDocid(p, iRemove);
106144        if( rc==SQLITE_OK ){
106145          rc = fts3DeleteTerms(p, apVal);
106146          if( rc==SQLITE_OK ){
106147            rc = fts3SqlExec(p, SQL_DELETE_CONTENT, apVal);
106148          }
106149        }
106150      }
106151    }
106152  }else if( sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){
106153    return fts3SpecialInsert(p, apVal[p->nColumn+2]);
106154  }
106155
106156  /* If this is an INSERT or UPDATE operation, insert the new record. */
106157  if( nArg>1 && rc==SQLITE_OK ){
106158    rc = fts3InsertData(p, apVal, pRowid);
106159    if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
106160      rc = fts3PendingTermsDocid(p, *pRowid);
106161    }
106162    if( rc==SQLITE_OK ){
106163      rc = fts3InsertTerms(p, apVal);
106164    }
106165  }
106166
106167  return rc;
106168}
106169
106170/*
106171** Flush any data in the pending-terms hash table to disk. If successful,
106172** merge all segments in the database (including the new segment, if
106173** there was any data to flush) into a single segment.
106174*/
106175SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
106176  int rc;
106177  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
106178  if( rc==SQLITE_OK ){
106179    rc = fts3SegmentMerge(p, -1);
106180    if( rc==SQLITE_OK ){
106181      rc = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
106182      if( rc==SQLITE_OK ){
106183        sqlite3Fts3PendingTermsClear(p);
106184      }
106185    }else{
106186      sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
106187      sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
106188    }
106189  }
106190  return rc;
106191}
106192
106193#endif
106194
106195/************** End of fts3_write.c ******************************************/
106196/************** Begin file fts3_snippet.c ************************************/
106197/*
106198** 2009 Oct 23
106199**
106200** The author disclaims copyright to this source code.  In place of
106201** a legal notice, here is a blessing:
106202**
106203**    May you do good and not evil.
106204**    May you find forgiveness for yourself and forgive others.
106205**    May you share freely, never taking more than you give.
106206**
106207******************************************************************************
106208*/
106209
106210#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
106211
106212
106213typedef struct Snippet Snippet;
106214
106215/*
106216** An instance of the following structure keeps track of generated
106217** matching-word offset information and snippets.
106218*/
106219struct Snippet {
106220  int nMatch;                     /* Total number of matches */
106221  int nAlloc;                     /* Space allocated for aMatch[] */
106222  struct snippetMatch {  /* One entry for each matching term */
106223    char snStatus;       /* Status flag for use while constructing snippets */
106224    short int nByte;     /* Number of bytes in the term */
106225    short int iCol;      /* The column that contains the match */
106226    short int iTerm;     /* The index in Query.pTerms[] of the matching term */
106227    int iToken;          /* The index of the matching document token */
106228    int iStart;          /* The offset to the first character of the term */
106229  } *aMatch;                      /* Points to space obtained from malloc */
106230  char *zOffset;                  /* Text rendering of aMatch[] */
106231  int nOffset;                    /* strlen(zOffset) */
106232  char *zSnippet;                 /* Snippet text */
106233  int nSnippet;                   /* strlen(zSnippet) */
106234};
106235
106236
106237/* It is not safe to call isspace(), tolower(), or isalnum() on
106238** hi-bit-set characters.  This is the same solution used in the
106239** tokenizer.
106240*/
106241static int fts3snippetIsspace(char c){
106242  return (c&0x80)==0 ? isspace(c) : 0;
106243}
106244
106245
106246/*
106247** A StringBuffer object holds a zero-terminated string that grows
106248** arbitrarily by appending.  Space to hold the string is obtained
106249** from sqlite3_malloc().  After any memory allocation failure,
106250** StringBuffer.z is set to NULL and no further allocation is attempted.
106251*/
106252typedef struct StringBuffer {
106253  char *z;         /* Text of the string.  Space from malloc. */
106254  int nUsed;       /* Number bytes of z[] used, not counting \000 terminator */
106255  int nAlloc;      /* Bytes allocated for z[] */
106256} StringBuffer;
106257
106258
106259/*
106260** Initialize a new StringBuffer.
106261*/
106262static void fts3SnippetSbInit(StringBuffer *p){
106263  p->nAlloc = 100;
106264  p->nUsed = 0;
106265  p->z = sqlite3_malloc( p->nAlloc );
106266}
106267
106268/*
106269** Append text to the string buffer.
106270*/
106271static void fts3SnippetAppend(StringBuffer *p, const char *zNew, int nNew){
106272  if( p->z==0 ) return;
106273  if( nNew<0 ) nNew = (int)strlen(zNew);
106274  if( p->nUsed + nNew >= p->nAlloc ){
106275    int nAlloc;
106276    char *zNew;
106277
106278    nAlloc = p->nUsed + nNew + p->nAlloc;
106279    zNew = sqlite3_realloc(p->z, nAlloc);
106280    if( zNew==0 ){
106281      sqlite3_free(p->z);
106282      p->z = 0;
106283      return;
106284    }
106285    p->z = zNew;
106286    p->nAlloc = nAlloc;
106287  }
106288  memcpy(&p->z[p->nUsed], zNew, nNew);
106289  p->nUsed += nNew;
106290  p->z[p->nUsed] = 0;
106291}
106292
106293/* If the StringBuffer ends in something other than white space, add a
106294** single space character to the end.
106295*/
106296static void fts3SnippetAppendWhiteSpace(StringBuffer *p){
106297  if( p->z && p->nUsed && !fts3snippetIsspace(p->z[p->nUsed-1]) ){
106298    fts3SnippetAppend(p, " ", 1);
106299  }
106300}
106301
106302/* Remove white space from the end of the StringBuffer */
106303static void fts3SnippetTrimWhiteSpace(StringBuffer *p){
106304  if( p->z ){
106305    while( p->nUsed && fts3snippetIsspace(p->z[p->nUsed-1]) ){
106306      p->nUsed--;
106307    }
106308    p->z[p->nUsed] = 0;
106309  }
106310}
106311
106312/*
106313** Release all memory associated with the Snippet structure passed as
106314** an argument.
106315*/
106316static void fts3SnippetFree(Snippet *p){
106317  if( p ){
106318    sqlite3_free(p->aMatch);
106319    sqlite3_free(p->zOffset);
106320    sqlite3_free(p->zSnippet);
106321    sqlite3_free(p);
106322  }
106323}
106324
106325/*
106326** Append a single entry to the p->aMatch[] log.
106327*/
106328static int snippetAppendMatch(
106329  Snippet *p,               /* Append the entry to this snippet */
106330  int iCol, int iTerm,      /* The column and query term */
106331  int iToken,               /* Matching token in document */
106332  int iStart, int nByte     /* Offset and size of the match */
106333){
106334  int i;
106335  struct snippetMatch *pMatch;
106336  if( p->nMatch+1>=p->nAlloc ){
106337    struct snippetMatch *pNew;
106338    p->nAlloc = p->nAlloc*2 + 10;
106339    pNew = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
106340    if( pNew==0 ){
106341      p->aMatch = 0;
106342      p->nMatch = 0;
106343      p->nAlloc = 0;
106344      return SQLITE_NOMEM;
106345    }
106346    p->aMatch = pNew;
106347  }
106348  i = p->nMatch++;
106349  pMatch = &p->aMatch[i];
106350  pMatch->iCol = (short)iCol;
106351  pMatch->iTerm = (short)iTerm;
106352  pMatch->iToken = iToken;
106353  pMatch->iStart = iStart;
106354  pMatch->nByte = (short)nByte;
106355  return SQLITE_OK;
106356}
106357
106358/*
106359** Sizing information for the circular buffer used in snippetOffsetsOfColumn()
106360*/
106361#define FTS3_ROTOR_SZ   (32)
106362#define FTS3_ROTOR_MASK (FTS3_ROTOR_SZ-1)
106363
106364/*
106365** Function to iterate through the tokens of a compiled expression.
106366**
106367** Except, skip all tokens on the right-hand side of a NOT operator.
106368** This function is used to find tokens as part of snippet and offset
106369** generation and we do nt want snippets and offsets to report matches
106370** for tokens on the RHS of a NOT.
106371*/
106372static int fts3NextExprToken(Fts3Expr **ppExpr, int *piToken){
106373  Fts3Expr *p = *ppExpr;
106374  int iToken = *piToken;
106375  if( iToken<0 ){
106376    /* In this case the expression p is the root of an expression tree.
106377    ** Move to the first token in the expression tree.
106378    */
106379    while( p->pLeft ){
106380      p = p->pLeft;
106381    }
106382    iToken = 0;
106383  }else{
106384    assert(p && p->eType==FTSQUERY_PHRASE );
106385    if( iToken<(p->pPhrase->nToken-1) ){
106386      iToken++;
106387    }else{
106388      iToken = 0;
106389      while( p->pParent && p->pParent->pLeft!=p ){
106390        assert( p->pParent->pRight==p );
106391        p = p->pParent;
106392      }
106393      p = p->pParent;
106394      if( p ){
106395        assert( p->pRight!=0 );
106396        p = p->pRight;
106397        while( p->pLeft ){
106398          p = p->pLeft;
106399        }
106400      }
106401    }
106402  }
106403
106404  *ppExpr = p;
106405  *piToken = iToken;
106406  return p?1:0;
106407}
106408
106409/*
106410** Return TRUE if the expression node pExpr is located beneath the
106411** RHS of a NOT operator.
106412*/
106413static int fts3ExprBeneathNot(Fts3Expr *p){
106414  Fts3Expr *pParent;
106415  while( p ){
106416    pParent = p->pParent;
106417    if( pParent && pParent->eType==FTSQUERY_NOT && pParent->pRight==p ){
106418      return 1;
106419    }
106420    p = pParent;
106421  }
106422  return 0;
106423}
106424
106425/*
106426** Add entries to pSnippet->aMatch[] for every match that occurs against
106427** document zDoc[0..nDoc-1] which is stored in column iColumn.
106428*/
106429static int snippetOffsetsOfColumn(
106430  Fts3Cursor *pCur,         /* The fulltest search cursor */
106431  Snippet *pSnippet,             /* The Snippet object to be filled in */
106432  int iColumn,                   /* Index of fulltext table column */
106433  const char *zDoc,              /* Text of the fulltext table column */
106434  int nDoc                       /* Length of zDoc in bytes */
106435){
106436  const sqlite3_tokenizer_module *pTModule;  /* The tokenizer module */
106437  sqlite3_tokenizer *pTokenizer;             /* The specific tokenizer */
106438  sqlite3_tokenizer_cursor *pTCursor;        /* Tokenizer cursor */
106439  Fts3Table *pVtab;                /* The full text index */
106440  int nColumn;                         /* Number of columns in the index */
106441  int i, j;                            /* Loop counters */
106442  int rc;                              /* Return code */
106443  unsigned int match, prevMatch;       /* Phrase search bitmasks */
106444  const char *zToken;                  /* Next token from the tokenizer */
106445  int nToken;                          /* Size of zToken */
106446  int iBegin, iEnd, iPos;              /* Offsets of beginning and end */
106447
106448  /* The following variables keep a circular buffer of the last
106449  ** few tokens */
106450  unsigned int iRotor = 0;             /* Index of current token */
106451  int iRotorBegin[FTS3_ROTOR_SZ];      /* Beginning offset of token */
106452  int iRotorLen[FTS3_ROTOR_SZ];        /* Length of token */
106453
106454  pVtab =  (Fts3Table *)pCur->base.pVtab;
106455  nColumn = pVtab->nColumn;
106456  pTokenizer = pVtab->pTokenizer;
106457  pTModule = pTokenizer->pModule;
106458  rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
106459  if( rc ) return rc;
106460  pTCursor->pTokenizer = pTokenizer;
106461
106462  prevMatch = 0;
106463  while( (rc = pTModule->xNext(pTCursor, &zToken, &nToken,
106464                               &iBegin, &iEnd, &iPos))==SQLITE_OK ){
106465    Fts3Expr *pIter = pCur->pExpr;
106466    int iIter = -1;
106467    iRotorBegin[iRotor&FTS3_ROTOR_MASK] = iBegin;
106468    iRotorLen[iRotor&FTS3_ROTOR_MASK] = iEnd-iBegin;
106469    match = 0;
106470    for(i=0; i<(FTS3_ROTOR_SZ-1) && fts3NextExprToken(&pIter, &iIter); i++){
106471      int nPhrase;                    /* Number of tokens in current phrase */
106472      struct PhraseToken *pToken;     /* Current token */
106473      int iCol;                       /* Column index */
106474
106475      if( fts3ExprBeneathNot(pIter) ) continue;
106476      nPhrase = pIter->pPhrase->nToken;
106477      pToken = &pIter->pPhrase->aToken[iIter];
106478      iCol = pIter->pPhrase->iColumn;
106479      if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
106480      if( pToken->n>nToken ) continue;
106481      if( !pToken->isPrefix && pToken->n<nToken ) continue;
106482      assert( pToken->n<=nToken );
106483      if( memcmp(pToken->z, zToken, pToken->n) ) continue;
106484      if( iIter>0 && (prevMatch & (1<<i))==0 ) continue;
106485      match |= 1<<i;
106486      if( i==(FTS3_ROTOR_SZ-2) || nPhrase==iIter+1 ){
106487        for(j=nPhrase-1; j>=0; j--){
106488          int k = (iRotor-j) & FTS3_ROTOR_MASK;
106489          rc = snippetAppendMatch(pSnippet, iColumn, i-j, iPos-j,
106490                                  iRotorBegin[k], iRotorLen[k]);
106491          if( rc ) goto end_offsets_of_column;
106492        }
106493      }
106494    }
106495    prevMatch = match<<1;
106496    iRotor++;
106497  }
106498end_offsets_of_column:
106499  pTModule->xClose(pTCursor);
106500  return rc==SQLITE_DONE ? SQLITE_OK : rc;
106501}
106502
106503/*
106504** Remove entries from the pSnippet structure to account for the NEAR
106505** operator. When this is called, pSnippet contains the list of token
106506** offsets produced by treating all NEAR operators as AND operators.
106507** This function removes any entries that should not be present after
106508** accounting for the NEAR restriction. For example, if the queried
106509** document is:
106510**
106511**     "A B C D E A"
106512**
106513** and the query is:
106514**
106515**     A NEAR/0 E
106516**
106517** then when this function is called the Snippet contains token offsets
106518** 0, 4 and 5. This function removes the "0" entry (because the first A
106519** is not near enough to an E).
106520**
106521** When this function is called, the value pointed to by parameter piLeft is
106522** the integer id of the left-most token in the expression tree headed by
106523** pExpr. This function increments *piLeft by the total number of tokens
106524** in the expression tree headed by pExpr.
106525**
106526** Return 1 if any trimming occurs.  Return 0 if no trimming is required.
106527*/
106528static int trimSnippetOffsets(
106529  Fts3Expr *pExpr,      /* The search expression */
106530  Snippet *pSnippet,    /* The set of snippet offsets to be trimmed */
106531  int *piLeft           /* Index of left-most token in pExpr */
106532){
106533  if( pExpr ){
106534    if( trimSnippetOffsets(pExpr->pLeft, pSnippet, piLeft) ){
106535      return 1;
106536    }
106537
106538    switch( pExpr->eType ){
106539      case FTSQUERY_PHRASE:
106540        *piLeft += pExpr->pPhrase->nToken;
106541        break;
106542      case FTSQUERY_NEAR: {
106543        /* The right-hand-side of a NEAR operator is always a phrase. The
106544        ** left-hand-side is either a phrase or an expression tree that is
106545        ** itself headed by a NEAR operator. The following initializations
106546        ** set local variable iLeft to the token number of the left-most
106547        ** token in the right-hand phrase, and iRight to the right most
106548        ** token in the same phrase. For example, if we had:
106549        **
106550        **     <col> MATCH '"abc def" NEAR/2 "ghi jkl"'
106551        **
106552        ** then iLeft will be set to 2 (token number of ghi) and nToken will
106553        ** be set to 4.
106554        */
106555        Fts3Expr *pLeft = pExpr->pLeft;
106556        Fts3Expr *pRight = pExpr->pRight;
106557        int iLeft = *piLeft;
106558        int nNear = pExpr->nNear;
106559        int nToken = pRight->pPhrase->nToken;
106560        int jj, ii;
106561        if( pLeft->eType==FTSQUERY_NEAR ){
106562          pLeft = pLeft->pRight;
106563        }
106564        assert( pRight->eType==FTSQUERY_PHRASE );
106565        assert( pLeft->eType==FTSQUERY_PHRASE );
106566        nToken += pLeft->pPhrase->nToken;
106567
106568        for(ii=0; ii<pSnippet->nMatch; ii++){
106569          struct snippetMatch *p = &pSnippet->aMatch[ii];
106570          if( p->iTerm==iLeft ){
106571            int isOk = 0;
106572            /* Snippet ii is an occurence of query term iLeft in the document.
106573            ** It occurs at position (p->iToken) of the document. We now
106574            ** search for an instance of token (iLeft-1) somewhere in the
106575            ** range (p->iToken - nNear)...(p->iToken + nNear + nToken) within
106576            ** the set of snippetMatch structures. If one is found, proceed.
106577            ** If one cannot be found, then remove snippets ii..(ii+N-1)
106578            ** from the matching snippets, where N is the number of tokens
106579            ** in phrase pRight->pPhrase.
106580            */
106581            for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
106582              struct snippetMatch *p2 = &pSnippet->aMatch[jj];
106583              if( p2->iTerm==(iLeft-1) ){
106584                if( p2->iToken>=(p->iToken-nNear-1)
106585                 && p2->iToken<(p->iToken+nNear+nToken)
106586                ){
106587                  isOk = 1;
106588                }
106589              }
106590            }
106591            if( !isOk ){
106592              int kk;
106593              for(kk=0; kk<pRight->pPhrase->nToken; kk++){
106594                pSnippet->aMatch[kk+ii].iTerm = -2;
106595              }
106596              return 1;
106597            }
106598          }
106599          if( p->iTerm==(iLeft-1) ){
106600            int isOk = 0;
106601            for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
106602              struct snippetMatch *p2 = &pSnippet->aMatch[jj];
106603              if( p2->iTerm==iLeft ){
106604                if( p2->iToken<=(p->iToken+nNear+1)
106605                 && p2->iToken>(p->iToken-nNear-nToken)
106606                ){
106607                  isOk = 1;
106608                }
106609              }
106610            }
106611            if( !isOk ){
106612              int kk;
106613              for(kk=0; kk<pLeft->pPhrase->nToken; kk++){
106614                pSnippet->aMatch[ii-kk].iTerm = -2;
106615              }
106616              return 1;
106617            }
106618          }
106619        }
106620        break;
106621      }
106622    }
106623
106624    if( trimSnippetOffsets(pExpr->pRight, pSnippet, piLeft) ){
106625      return 1;
106626    }
106627  }
106628  return 0;
106629}
106630
106631/*
106632** Compute all offsets for the current row of the query.
106633** If the offsets have already been computed, this routine is a no-op.
106634*/
106635static int snippetAllOffsets(Fts3Cursor *pCsr, Snippet **ppSnippet){
106636  Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;  /* The FTS3 virtual table */
106637  int nColumn;           /* Number of columns.  Docid does count */
106638  int iColumn;           /* Index of of a column */
106639  int i;                 /* Loop index */
106640  int iFirst;            /* First column to search */
106641  int iLast;             /* Last coumn to search */
106642  int iTerm = 0;
106643  Snippet *pSnippet;
106644  int rc = SQLITE_OK;
106645
106646  if( pCsr->pExpr==0 ){
106647    return SQLITE_OK;
106648  }
106649
106650  pSnippet = (Snippet *)sqlite3_malloc(sizeof(Snippet));
106651  *ppSnippet = pSnippet;
106652  if( !pSnippet ){
106653    return SQLITE_NOMEM;
106654  }
106655  memset(pSnippet, 0, sizeof(Snippet));
106656
106657  nColumn = p->nColumn;
106658  iColumn = (pCsr->eSearch - 2);
106659  if( iColumn<0 || iColumn>=nColumn ){
106660    /* Look for matches over all columns of the full-text index */
106661    iFirst = 0;
106662    iLast = nColumn-1;
106663  }else{
106664    /* Look for matches in the iColumn-th column of the index only */
106665    iFirst = iColumn;
106666    iLast = iColumn;
106667  }
106668  for(i=iFirst; rc==SQLITE_OK && i<=iLast; i++){
106669    const char *zDoc;
106670    int nDoc;
106671    zDoc = (const char*)sqlite3_column_text(pCsr->pStmt, i+1);
106672    nDoc = sqlite3_column_bytes(pCsr->pStmt, i+1);
106673    if( zDoc==0 && sqlite3_column_type(pCsr->pStmt, i+1)!=SQLITE_NULL ){
106674      rc = SQLITE_NOMEM;
106675    }else{
106676      rc = snippetOffsetsOfColumn(pCsr, pSnippet, i, zDoc, nDoc);
106677    }
106678  }
106679
106680  while( trimSnippetOffsets(pCsr->pExpr, pSnippet, &iTerm) ){
106681    iTerm = 0;
106682  }
106683
106684  return rc;
106685}
106686
106687/*
106688** Convert the information in the aMatch[] array of the snippet
106689** into the string zOffset[0..nOffset-1]. This string is used as
106690** the return of the SQL offsets() function.
106691*/
106692static void snippetOffsetText(Snippet *p){
106693  int i;
106694  int cnt = 0;
106695  StringBuffer sb;
106696  char zBuf[200];
106697  if( p->zOffset ) return;
106698  fts3SnippetSbInit(&sb);
106699  for(i=0; i<p->nMatch; i++){
106700    struct snippetMatch *pMatch = &p->aMatch[i];
106701    if( pMatch->iTerm>=0 ){
106702      /* If snippetMatch.iTerm is less than 0, then the match was
106703      ** discarded as part of processing the NEAR operator (see the
106704      ** trimSnippetOffsetsForNear() function for details). Ignore
106705      ** it in this case
106706      */
106707      zBuf[0] = ' ';
106708      sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d",
106709          pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte);
106710      fts3SnippetAppend(&sb, zBuf, -1);
106711      cnt++;
106712    }
106713  }
106714  p->zOffset = sb.z;
106715  p->nOffset = sb.z ? sb.nUsed : 0;
106716}
106717
106718/*
106719** zDoc[0..nDoc-1] is phrase of text.  aMatch[0..nMatch-1] are a set
106720** of matching words some of which might be in zDoc.  zDoc is column
106721** number iCol.
106722**
106723** iBreak is suggested spot in zDoc where we could begin or end an
106724** excerpt.  Return a value similar to iBreak but possibly adjusted
106725** to be a little left or right so that the break point is better.
106726*/
106727static int wordBoundary(
106728  int iBreak,                   /* The suggested break point */
106729  const char *zDoc,             /* Document text */
106730  int nDoc,                     /* Number of bytes in zDoc[] */
106731  struct snippetMatch *aMatch,  /* Matching words */
106732  int nMatch,                   /* Number of entries in aMatch[] */
106733  int iCol                      /* The column number for zDoc[] */
106734){
106735  int i;
106736  if( iBreak<=10 ){
106737    return 0;
106738  }
106739  if( iBreak>=nDoc-10 ){
106740    return nDoc;
106741  }
106742  for(i=0; ALWAYS(i<nMatch) && aMatch[i].iCol<iCol; i++){}
106743  while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
106744  if( i<nMatch ){
106745    if( aMatch[i].iStart<iBreak+10 ){
106746      return aMatch[i].iStart;
106747    }
106748    if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
106749      return aMatch[i-1].iStart;
106750    }
106751  }
106752  for(i=1; i<=10; i++){
106753    if( fts3snippetIsspace(zDoc[iBreak-i]) ){
106754      return iBreak - i + 1;
106755    }
106756    if( fts3snippetIsspace(zDoc[iBreak+i]) ){
106757      return iBreak + i + 1;
106758    }
106759  }
106760  return iBreak;
106761}
106762
106763
106764
106765/*
106766** Allowed values for Snippet.aMatch[].snStatus
106767*/
106768#define SNIPPET_IGNORE  0   /* It is ok to omit this match from the snippet */
106769#define SNIPPET_DESIRED 1   /* We want to include this match in the snippet */
106770
106771/*
106772** Generate the text of a snippet.
106773*/
106774static void snippetText(
106775  Fts3Cursor *pCursor,   /* The cursor we need the snippet for */
106776  Snippet *pSnippet,
106777  const char *zStartMark,     /* Markup to appear before each match */
106778  const char *zEndMark,       /* Markup to appear after each match */
106779  const char *zEllipsis       /* Ellipsis mark */
106780){
106781  int i, j;
106782  struct snippetMatch *aMatch;
106783  int nMatch;
106784  int nDesired;
106785  StringBuffer sb;
106786  int tailCol;
106787  int tailOffset;
106788  int iCol;
106789  int nDoc;
106790  const char *zDoc;
106791  int iStart, iEnd;
106792  int tailEllipsis = 0;
106793  int iMatch;
106794
106795
106796  sqlite3_free(pSnippet->zSnippet);
106797  pSnippet->zSnippet = 0;
106798  aMatch = pSnippet->aMatch;
106799  nMatch = pSnippet->nMatch;
106800  fts3SnippetSbInit(&sb);
106801
106802  for(i=0; i<nMatch; i++){
106803    aMatch[i].snStatus = SNIPPET_IGNORE;
106804  }
106805  nDesired = 0;
106806  for(i=0; i<FTS3_ROTOR_SZ; i++){
106807    for(j=0; j<nMatch; j++){
106808      if( aMatch[j].iTerm==i ){
106809        aMatch[j].snStatus = SNIPPET_DESIRED;
106810        nDesired++;
106811        break;
106812      }
106813    }
106814  }
106815
106816  iMatch = 0;
106817  tailCol = -1;
106818  tailOffset = 0;
106819  for(i=0; i<nMatch && nDesired>0; i++){
106820    if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
106821    nDesired--;
106822    iCol = aMatch[i].iCol;
106823    zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
106824    nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
106825    iStart = aMatch[i].iStart - 40;
106826    iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
106827    if( iStart<=10 ){
106828      iStart = 0;
106829    }
106830    if( iCol==tailCol && iStart<=tailOffset+20 ){
106831      iStart = tailOffset;
106832    }
106833    if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
106834      fts3SnippetTrimWhiteSpace(&sb);
106835      fts3SnippetAppendWhiteSpace(&sb);
106836      fts3SnippetAppend(&sb, zEllipsis, -1);
106837      fts3SnippetAppendWhiteSpace(&sb);
106838    }
106839    iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
106840    iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
106841    if( iEnd>=nDoc-10 ){
106842      iEnd = nDoc;
106843      tailEllipsis = 0;
106844    }else{
106845      tailEllipsis = 1;
106846    }
106847    while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
106848    while( iStart<iEnd ){
106849      while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
106850             && aMatch[iMatch].iCol<=iCol ){
106851        iMatch++;
106852      }
106853      if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
106854             && aMatch[iMatch].iCol==iCol ){
106855        fts3SnippetAppend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
106856        iStart = aMatch[iMatch].iStart;
106857        fts3SnippetAppend(&sb, zStartMark, -1);
106858        fts3SnippetAppend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
106859        fts3SnippetAppend(&sb, zEndMark, -1);
106860        iStart += aMatch[iMatch].nByte;
106861        for(j=iMatch+1; j<nMatch; j++){
106862          if( aMatch[j].iTerm==aMatch[iMatch].iTerm
106863              && aMatch[j].snStatus==SNIPPET_DESIRED ){
106864            nDesired--;
106865            aMatch[j].snStatus = SNIPPET_IGNORE;
106866          }
106867        }
106868      }else{
106869        fts3SnippetAppend(&sb, &zDoc[iStart], iEnd - iStart);
106870        iStart = iEnd;
106871      }
106872    }
106873    tailCol = iCol;
106874    tailOffset = iEnd;
106875  }
106876  fts3SnippetTrimWhiteSpace(&sb);
106877  if( tailEllipsis ){
106878    fts3SnippetAppendWhiteSpace(&sb);
106879    fts3SnippetAppend(&sb, zEllipsis, -1);
106880  }
106881  pSnippet->zSnippet = sb.z;
106882  pSnippet->nSnippet = sb.z ? sb.nUsed : 0;
106883}
106884
106885SQLITE_PRIVATE void sqlite3Fts3Offsets(
106886  sqlite3_context *pCtx,          /* SQLite function call context */
106887  Fts3Cursor *pCsr                /* Cursor object */
106888){
106889  Snippet *p;                     /* Snippet structure */
106890  int rc = snippetAllOffsets(pCsr, &p);
106891  if( rc==SQLITE_OK ){
106892    snippetOffsetText(p);
106893    if( p->zOffset ){
106894      sqlite3_result_text(pCtx, p->zOffset, p->nOffset, SQLITE_TRANSIENT);
106895    }else{
106896      sqlite3_result_error_nomem(pCtx);
106897    }
106898  }else{
106899    sqlite3_result_error_nomem(pCtx);
106900  }
106901  fts3SnippetFree(p);
106902}
106903
106904SQLITE_PRIVATE void sqlite3Fts3Snippet(
106905  sqlite3_context *pCtx,          /* SQLite function call context */
106906  Fts3Cursor *pCsr,               /* Cursor object */
106907  const char *zStart,             /* Snippet start text - "<b>" */
106908  const char *zEnd,               /* Snippet end text - "</b>" */
106909  const char *zEllipsis           /* Snippet ellipsis text - "<b>...</b>" */
106910){
106911  Snippet *p;                     /* Snippet structure */
106912  int rc = snippetAllOffsets(pCsr, &p);
106913  if( rc==SQLITE_OK ){
106914    snippetText(pCsr, p, zStart, zEnd, zEllipsis);
106915    if( p->zSnippet ){
106916      sqlite3_result_text(pCtx, p->zSnippet, p->nSnippet, SQLITE_TRANSIENT);
106917    }else{
106918      sqlite3_result_error_nomem(pCtx);
106919    }
106920  }else{
106921    sqlite3_result_error_nomem(pCtx);
106922  }
106923  fts3SnippetFree(p);
106924}
106925
106926/*************************************************************************
106927** Below this point is the alternative, experimental snippet() implementation.
106928*/
106929
106930#define SNIPPET_BUFFER_CHUNK  64
106931#define SNIPPET_BUFFER_SIZE   SNIPPET_BUFFER_CHUNK*4
106932#define SNIPPET_BUFFER_MASK   (SNIPPET_BUFFER_SIZE-1)
106933
106934static void fts3GetDeltaPosition(char **pp, int *piPos){
106935  int iVal;
106936  *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
106937  *piPos += (iVal-2);
106938}
106939
106940/*
106941** Iterate through all phrase nodes in an FTS3 query, except those that
106942** are part of a sub-tree that is the right-hand-side of a NOT operator.
106943** For each phrase node found, the supplied callback function is invoked.
106944**
106945** If the callback function returns anything other than SQLITE_OK,
106946** the iteration is abandoned and the error code returned immediately.
106947** Otherwise, SQLITE_OK is returned after a callback has been made for
106948** all eligible phrase nodes.
106949*/
106950static int fts3ExprIterate(
106951  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
106952  int (*x)(Fts3Expr *, void *),   /* Callback function to invoke for phrases */
106953  void *pCtx                      /* Second argument to pass to callback */
106954){
106955  int rc;
106956  int eType = pExpr->eType;
106957  if( eType==FTSQUERY_NOT ){
106958    rc = SQLITE_OK;
106959  }else if( eType!=FTSQUERY_PHRASE ){
106960    assert( pExpr->pLeft && pExpr->pRight );
106961    rc = fts3ExprIterate(pExpr->pLeft, x, pCtx);
106962    if( rc==SQLITE_OK ){
106963      rc = fts3ExprIterate(pExpr->pRight, x, pCtx);
106964    }
106965  }else{
106966    rc = x(pExpr, pCtx);
106967  }
106968  return rc;
106969}
106970
106971typedef struct LoadDoclistCtx LoadDoclistCtx;
106972struct LoadDoclistCtx {
106973  Fts3Table *pTab;                /* FTS3 Table */
106974  int nPhrase;                    /* Number of phrases so far */
106975};
106976
106977static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, void *ctx){
106978  int rc = SQLITE_OK;
106979  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
106980  p->nPhrase++;
106981  if( pExpr->isLoaded==0 ){
106982    rc = sqlite3Fts3ExprLoadDoclist(p->pTab, pExpr);
106983    pExpr->isLoaded = 1;
106984    if( rc==SQLITE_OK && pExpr->aDoclist ){
106985      pExpr->pCurrent = pExpr->aDoclist;
106986      pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent,&pExpr->iCurrent);
106987    }
106988  }
106989  return rc;
106990}
106991
106992static int fts3ExprLoadDoclists(Fts3Cursor *pCsr, int *pnPhrase){
106993  int rc;
106994  LoadDoclistCtx sCtx = {0, 0};
106995  sCtx.pTab = (Fts3Table *)pCsr->base.pVtab;
106996  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
106997  *pnPhrase = sCtx.nPhrase;
106998  return rc;
106999}
107000
107001/*
107002** Each call to this function populates a chunk of a snippet-buffer
107003** SNIPPET_BUFFER_CHUNK bytes in size.
107004**
107005** Return true if the end of the data has been reached (and all subsequent
107006** calls to fts3LoadSnippetBuffer() with the same arguments will be no-ops),
107007** or false otherwise.
107008*/
107009static int fts3LoadSnippetBuffer(
107010  int iPos,                       /* Document token offset to load data for */
107011  u8 *aBuffer,                    /* Circular snippet buffer to populate */
107012  int nList,                      /* Number of position lists in appList */
107013  char **apList,                  /* IN/OUT: nList position list pointers */
107014  int *aiPrev                     /* IN/OUT: Previous positions read */
107015){
107016  int i;
107017  int nFin = 0;
107018
107019  assert( (iPos&(SNIPPET_BUFFER_CHUNK-1))==0 );
107020
107021  memset(&aBuffer[iPos&SNIPPET_BUFFER_MASK], 0, SNIPPET_BUFFER_CHUNK);
107022
107023  for(i=0; i<nList; i++){
107024    int iPrev = aiPrev[i];
107025    char *pList = apList[i];
107026
107027    if( !pList ){
107028      nFin++;
107029      continue;
107030    }
107031
107032    while( iPrev<(iPos+SNIPPET_BUFFER_CHUNK) ){
107033      if( iPrev>=iPos ){
107034        aBuffer[iPrev&SNIPPET_BUFFER_MASK] = (u8)(i+1);
107035      }
107036      if( 0==((*pList)&0xFE) ){
107037        nFin++;
107038        break;
107039      }
107040      fts3GetDeltaPosition(&pList, &iPrev);
107041    }
107042
107043    aiPrev[i] = iPrev;
107044    apList[i] = pList;
107045  }
107046
107047  return (nFin==nList);
107048}
107049
107050typedef struct SnippetCtx SnippetCtx;
107051struct SnippetCtx {
107052  Fts3Cursor *pCsr;
107053  int iCol;
107054  int iPhrase;
107055  int *aiPrev;
107056  int *anToken;
107057  char **apList;
107058};
107059
107060static int fts3SnippetFindPositions(Fts3Expr *pExpr, void *ctx){
107061  SnippetCtx *p = (SnippetCtx *)ctx;
107062  int iPhrase = p->iPhrase++;
107063  char *pCsr;
107064
107065  p->anToken[iPhrase] = pExpr->pPhrase->nToken;
107066  pCsr = sqlite3Fts3FindPositions(pExpr, p->pCsr->iPrevId, p->iCol);
107067
107068  if( pCsr ){
107069    int iVal;
107070    pCsr += sqlite3Fts3GetVarint32(pCsr, &iVal);
107071    p->apList[iPhrase] = pCsr;
107072    p->aiPrev[iPhrase] = iVal-2;
107073  }
107074  return SQLITE_OK;
107075}
107076
107077static void fts3SnippetCnt(
107078  int iIdx,
107079  int nSnippet,
107080  int *anCnt,
107081  u8 *aBuffer,
107082  int *anToken,
107083  u64 *pHlmask
107084){
107085  int iSub =  (iIdx-1)&SNIPPET_BUFFER_MASK;
107086  int iAdd =  (iIdx+nSnippet-1)&SNIPPET_BUFFER_MASK;
107087  int iSub2 = (iIdx+(nSnippet/3)-1)&SNIPPET_BUFFER_MASK;
107088  int iAdd2 = (iIdx+(nSnippet*2/3)-1)&SNIPPET_BUFFER_MASK;
107089
107090  u64 h = *pHlmask;
107091
107092  anCnt[ aBuffer[iSub]  ]--;
107093  anCnt[ aBuffer[iSub2] ]--;
107094  anCnt[ aBuffer[iAdd]  ]++;
107095  anCnt[ aBuffer[iAdd2] ]++;
107096
107097  h = h >> 1;
107098  if( aBuffer[iAdd] ){
107099    int j;
107100    for(j=anToken[aBuffer[iAdd]-1]; j>=1; j--){
107101      h |= (u64)1 << (nSnippet-j);
107102    }
107103  }
107104  *pHlmask = h;
107105}
107106
107107static int fts3SnippetScore(int n, int *anCnt){
107108  int j;
107109  int iScore = 0;
107110  for(j=1; j<=n; j++){
107111    int nCnt = anCnt[j];
107112    iScore += nCnt + (nCnt ? 1000 : 0);
107113  }
107114  return iScore;
107115}
107116
107117static int fts3BestSnippet(
107118  int nSnippet,                   /* Desired snippet length */
107119  Fts3Cursor *pCsr,               /* Cursor to create snippet for */
107120  int iCol,                       /* Index of column to create snippet from */
107121  int *piPos,                     /* OUT: Starting token for best snippet */
107122  u64 *pHlmask                    /* OUT: Highlight mask for best snippet */
107123){
107124  int rc;                         /* Return Code */
107125  u8 aBuffer[SNIPPET_BUFFER_SIZE];/* Circular snippet buffer */
107126  int *aiPrev;                    /* Used by fts3LoadSnippetBuffer() */
107127  int *anToken;                   /* Number of tokens in each phrase */
107128  char **apList;                  /* Array of position lists */
107129  int *anCnt;                     /* Running totals of phrase occurences */
107130  int nList;
107131
107132  int i;
107133
107134  u64 hlmask = 0;                 /* Current mask of highlighted terms */
107135  u64 besthlmask = 0;             /* Mask of highlighted terms for iBestPos */
107136  int iBestPos = 0;               /* Starting position of 'best' snippet */
107137  int iBestScore = 0;             /* Score of best snippet higher->better */
107138  SnippetCtx sCtx;
107139
107140  /* Iterate through the phrases in the expression to count them. The same
107141  ** callback makes sure the doclists are loaded for each phrase.
107142  */
107143  rc = fts3ExprLoadDoclists(pCsr, &nList);
107144  if( rc!=SQLITE_OK ){
107145    return rc;
107146  }
107147
107148  /* Now that it is known how many phrases there are, allocate and zero
107149  ** the required arrays using malloc().
107150  */
107151  apList = sqlite3_malloc(
107152      sizeof(u8*)*nList +         /* apList */
107153      sizeof(int)*(nList) +       /* anToken */
107154      sizeof(int)*nList +         /* aiPrev */
107155      sizeof(int)*(nList+1)       /* anCnt */
107156  );
107157  if( !apList ){
107158    return SQLITE_NOMEM;
107159  }
107160  memset(apList, 0, sizeof(u8*)*nList+sizeof(int)*nList+sizeof(int)*nList);
107161  anToken = (int *)&apList[nList];
107162  aiPrev = &anToken[nList];
107163  anCnt = &aiPrev[nList];
107164
107165  /* Initialize the contents of the aiPrev and aiList arrays. */
107166  sCtx.pCsr = pCsr;
107167  sCtx.iCol = iCol;
107168  sCtx.apList = apList;
107169  sCtx.aiPrev = aiPrev;
107170  sCtx.anToken = anToken;
107171  sCtx.iPhrase = 0;
107172  (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sCtx);
107173
107174  /* Load the first two chunks of data into the buffer. */
107175  memset(aBuffer, 0, SNIPPET_BUFFER_SIZE);
107176  fts3LoadSnippetBuffer(0, aBuffer, nList, apList, aiPrev);
107177  fts3LoadSnippetBuffer(SNIPPET_BUFFER_CHUNK, aBuffer, nList, apList, aiPrev);
107178
107179  /* Set the initial contents of the highlight-mask and anCnt[] array. */
107180  for(i=1-nSnippet; i<=0; i++){
107181    fts3SnippetCnt(i, nSnippet, anCnt, aBuffer, anToken, &hlmask);
107182  }
107183  iBestScore = fts3SnippetScore(nList, anCnt);
107184  besthlmask = hlmask;
107185  iBestPos = 0;
107186
107187  for(i=1; 1; i++){
107188    int iScore;
107189
107190    if( 0==(i&(SNIPPET_BUFFER_CHUNK-1)) ){
107191      int iLoad = i + SNIPPET_BUFFER_CHUNK;
107192      if( fts3LoadSnippetBuffer(iLoad, aBuffer, nList, apList, aiPrev) ) break;
107193    }
107194
107195    /* Figure out how highly a snippet starting at token offset i scores
107196    ** according to fts3SnippetScore(). If it is higher than any previously
107197    ** considered position, save the current position, score and hlmask as
107198    ** the best snippet candidate found so far.
107199    */
107200    fts3SnippetCnt(i, nSnippet, anCnt, aBuffer, anToken, &hlmask);
107201    iScore = fts3SnippetScore(nList, anCnt);
107202    if( iScore>iBestScore ){
107203      iBestPos = i;
107204      iBestScore = iScore;
107205      besthlmask = hlmask;
107206    }
107207  }
107208
107209  sqlite3_free(apList);
107210  *piPos = iBestPos;
107211  *pHlmask = besthlmask;
107212  return SQLITE_OK;
107213}
107214
107215typedef struct StrBuffer StrBuffer;
107216struct StrBuffer {
107217  char *z;
107218  int n;
107219  int nAlloc;
107220};
107221
107222static int fts3StringAppend(
107223  StrBuffer *pStr,
107224  const char *zAppend,
107225  int nAppend
107226){
107227  if( nAppend<0 ){
107228    nAppend = (int)strlen(zAppend);
107229  }
107230
107231  if( pStr->n+nAppend+1>=pStr->nAlloc ){
107232    int nAlloc = pStr->nAlloc+nAppend+100;
107233    char *zNew = sqlite3_realloc(pStr->z, nAlloc);
107234    if( !zNew ){
107235      return SQLITE_NOMEM;
107236    }
107237    pStr->z = zNew;
107238    pStr->nAlloc = nAlloc;
107239  }
107240
107241  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
107242  pStr->n += nAppend;
107243  pStr->z[pStr->n] = '\0';
107244
107245  return SQLITE_OK;
107246}
107247
107248static int fts3SnippetText(
107249  Fts3Cursor *pCsr,               /* FTS3 Cursor */
107250  const char *zDoc,               /* Document to extract snippet from */
107251  int nDoc,                       /* Size of zDoc in bytes */
107252  int nSnippet,                   /* Number of tokens in extracted snippet */
107253  int iPos,                       /* Index of first document token in snippet */
107254  u64 hlmask,                     /* Bitmask of terms to highlight in snippet */
107255  const char *zOpen,              /* String inserted before highlighted term */
107256  const char *zClose,             /* String inserted after highlighted term */
107257  const char *zEllipsis,
107258  char **pzSnippet                /* OUT: Snippet text */
107259){
107260  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
107261  int rc;                         /* Return code */
107262  int iCurrent = 0;
107263  int iStart = 0;
107264  int iEnd;
107265
107266  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
107267  sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
107268  const char *ZDUMMY;             /* Dummy arguments used with tokenizer */
107269  int DUMMY1, DUMMY2, DUMMY3;     /* Dummy arguments used with tokenizer */
107270
107271  StrBuffer res = {0, 0, 0};   /* Result string */
107272
107273  /* Open a token cursor on the document. Read all tokens up to and
107274  ** including token iPos (the first token of the snippet). Set variable
107275  ** iStart to the byte offset in zDoc of the start of token iPos.
107276  */
107277  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
107278  rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
107279  while( rc==SQLITE_OK && iCurrent<iPos ){
107280    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iStart, &DUMMY2, &iCurrent);
107281  }
107282  iEnd = iStart;
107283
107284  if( rc==SQLITE_OK && iStart>0 ){
107285    rc = fts3StringAppend(&res, zEllipsis, -1);
107286  }
107287
107288  while( rc==SQLITE_OK ){
107289    int iBegin;
107290    int iFin;
107291    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
107292
107293    if( rc==SQLITE_OK ){
107294      if( iCurrent>=(iPos+nSnippet) ){
107295        rc = SQLITE_DONE;
107296      }else{
107297        iEnd = iFin;
107298        if( hlmask & ((u64)1 << (iCurrent-iPos)) ){
107299          if( fts3StringAppend(&res, &zDoc[iStart], iBegin-iStart)
107300           || fts3StringAppend(&res, zOpen, -1)
107301           || fts3StringAppend(&res, &zDoc[iBegin], iEnd-iBegin)
107302           || fts3StringAppend(&res, zClose, -1)
107303          ){
107304            rc = SQLITE_NOMEM;
107305          }
107306          iStart = iEnd;
107307        }
107308      }
107309    }
107310  }
107311  assert( rc!=SQLITE_OK );
107312  if( rc==SQLITE_DONE ){
107313    rc = fts3StringAppend(&res, &zDoc[iStart], iEnd-iStart);
107314    if( rc==SQLITE_OK ){
107315      rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
107316      if( rc==SQLITE_OK ){
107317        rc = fts3StringAppend(&res, zEllipsis, -1);
107318      }else if( rc==SQLITE_DONE ){
107319        rc = fts3StringAppend(&res, &zDoc[iEnd], -1);
107320      }
107321    }
107322  }
107323
107324  pMod->xClose(pC);
107325  if( rc!=SQLITE_OK ){
107326    sqlite3_free(res.z);
107327  }else{
107328    *pzSnippet = res.z;
107329  }
107330  return rc;
107331}
107332
107333
107334/*
107335** An instance of this structure is used to collect the 'global' part of
107336** the matchinfo statistics. The 'global' part consists of the following:
107337**
107338**   1. The number of phrases in the query (nPhrase).
107339**
107340**   2. The number of columns in the FTS3 table (nCol).
107341**
107342**   3. A matrix of (nPhrase*nCol) integers containing the sum of the
107343**      number of hits for each phrase in each column across all rows
107344**      of the table.
107345**
107346** The total size of the global matchinfo array, assuming the number of
107347** columns is N and the number of phrases is P is:
107348**
107349**   2 + P*(N+1)
107350**
107351** The number of hits for the 3rd phrase in the second column is found
107352** using the expression:
107353**
107354**   aGlobal[2 + P*(1+2) + 1]
107355*/
107356typedef struct MatchInfo MatchInfo;
107357struct MatchInfo {
107358  Fts3Table *pTab;                /* FTS3 Table */
107359  Fts3Cursor *pCursor;            /* FTS3 Cursor */
107360  int iPhrase;                    /* Number of phrases so far */
107361  int nCol;                       /* Number of columns in table */
107362  u32 *aGlobal;                   /* Pre-allocated buffer */
107363};
107364
107365/*
107366** This function is used to count the entries in a column-list (delta-encoded
107367** list of term offsets within a single column of a single row).
107368*/
107369static int fts3ColumnlistCount(char **ppCollist){
107370  char *pEnd = *ppCollist;
107371  char c = 0;
107372  int nEntry = 0;
107373
107374  /* A column-list is terminated by either a 0x01 or 0x00. */
107375  while( 0xFE & (*pEnd | c) ){
107376    c = *pEnd++ & 0x80;
107377    if( !c ) nEntry++;
107378  }
107379
107380  *ppCollist = pEnd;
107381  return nEntry;
107382}
107383
107384static void fts3LoadColumnlistCounts(char **pp, u32 *aOut){
107385  char *pCsr = *pp;
107386  while( *pCsr ){
107387    sqlite3_int64 iCol = 0;
107388    if( *pCsr==0x01 ){
107389      pCsr++;
107390      pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
107391    }
107392    aOut[iCol] += fts3ColumnlistCount(&pCsr);
107393  }
107394  pCsr++;
107395  *pp = pCsr;
107396}
107397
107398/*
107399** fts3ExprIterate() callback used to collect the "global" matchinfo stats
107400** for a single query.
107401*/
107402static int fts3ExprGlobalMatchinfoCb(
107403  Fts3Expr *pExpr,                /* Phrase expression node */
107404  void *pCtx                      /* Pointer to MatchInfo structure */
107405){
107406  MatchInfo *p = (MatchInfo *)pCtx;
107407  char *pCsr;
107408  char *pEnd;
107409  const int iStart = 2 + p->nCol*p->iPhrase;
107410
107411  assert( pExpr->isLoaded );
107412
107413  /* Fill in the global hit count matrix row for this phrase. */
107414  pCsr = pExpr->aDoclist;
107415  pEnd = &pExpr->aDoclist[pExpr->nDoclist];
107416  while( pCsr<pEnd ){
107417    while( *pCsr++ & 0x80 );
107418    fts3LoadColumnlistCounts(&pCsr, &p->aGlobal[iStart]);
107419  }
107420
107421  p->iPhrase++;
107422  return SQLITE_OK;
107423}
107424
107425static int fts3ExprLocalMatchinfoCb(
107426  Fts3Expr *pExpr,                /* Phrase expression node */
107427  void *pCtx                      /* Pointer to MatchInfo structure */
107428){
107429  MatchInfo *p = (MatchInfo *)pCtx;
107430  int iPhrase = p->iPhrase++;
107431
107432  if( pExpr->aDoclist ){
107433    char *pCsr;
107434    int iOffset = 2 + p->nCol*(p->aGlobal[0]+iPhrase);
107435
107436    memset(&p->aGlobal[iOffset], 0, p->nCol*sizeof(u32));
107437    pCsr = sqlite3Fts3FindPositions(pExpr, p->pCursor->iPrevId, -1);
107438    if( pCsr ) fts3LoadColumnlistCounts(&pCsr, &p->aGlobal[iOffset]);
107439  }
107440
107441  return SQLITE_OK;
107442}
107443
107444/*
107445** Populate pCsr->aMatchinfo[] with data for the current row. The 'matchinfo'
107446** data is an array of 32-bit unsigned integers (C type u32).
107447*/
107448static int fts3GetMatchinfo(Fts3Cursor *pCsr){
107449  MatchInfo g;
107450  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
107451  if( pCsr->aMatchinfo==0 ){
107452    int rc;
107453    int nPhrase;
107454    int nMatchinfo;
107455
107456    g.pTab = pTab;
107457    g.nCol = pTab->nColumn;
107458    g.iPhrase = 0;
107459    rc = fts3ExprLoadDoclists(pCsr, &nPhrase);
107460    if( rc!=SQLITE_OK ){
107461      return rc;
107462    }
107463
107464    nMatchinfo = 2 + 2*g.nCol*nPhrase;
107465
107466    g.iPhrase = 0;
107467    g.aGlobal = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo);
107468    if( !g.aGlobal ){
107469      return SQLITE_NOMEM;
107470    }
107471    memset(g.aGlobal, 0, sizeof(u32)*nMatchinfo);
107472
107473    g.aGlobal[0] = nPhrase;
107474    g.aGlobal[1] = g.nCol;
107475    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprGlobalMatchinfoCb, (void *)&g);
107476
107477    pCsr->aMatchinfo = g.aGlobal;
107478  }
107479
107480  g.pTab = pTab;
107481  g.pCursor = pCsr;
107482  g.nCol = pTab->nColumn;
107483  g.iPhrase = 0;
107484  g.aGlobal = pCsr->aMatchinfo;
107485
107486  if( pCsr->isMatchinfoOk ){
107487    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLocalMatchinfoCb, (void *)&g);
107488    pCsr->isMatchinfoOk = 0;
107489  }
107490
107491  return SQLITE_OK;
107492}
107493
107494SQLITE_PRIVATE void sqlite3Fts3Snippet2(
107495  sqlite3_context *pCtx,          /* SQLite function call context */
107496  Fts3Cursor *pCsr,               /* Cursor object */
107497  const char *zStart,             /* Snippet start text - "<b>" */
107498  const char *zEnd,               /* Snippet end text - "</b>" */
107499  const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
107500  int iCol,                       /* Extract snippet from this column */
107501  int nToken                      /* Approximate number of tokens in snippet */
107502){
107503  int rc;
107504  int iPos = 0;
107505  u64 hlmask = 0;
107506  char *z = 0;
107507  int nDoc;
107508  const char *zDoc;
107509
107510  rc = fts3BestSnippet(nToken, pCsr, iCol, &iPos, &hlmask);
107511
107512  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
107513  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
107514
107515  if( rc==SQLITE_OK ){
107516    rc = fts3SnippetText(
107517        pCsr, zDoc, nDoc, nToken, iPos, hlmask, zStart, zEnd, zEllipsis, &z);
107518  }
107519  if( rc!=SQLITE_OK ){
107520    sqlite3_result_error_code(pCtx, rc);
107521  }else{
107522    sqlite3_result_text(pCtx, z, -1, sqlite3_free);
107523  }
107524}
107525
107526SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *pContext, Fts3Cursor *pCsr){
107527  int rc = fts3GetMatchinfo(pCsr);
107528  if( rc!=SQLITE_OK ){
107529    sqlite3_result_error_code(pContext, rc);
107530  }else{
107531    int n = sizeof(u32)*(2+pCsr->aMatchinfo[0]*pCsr->aMatchinfo[1]*2);
107532    sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
107533  }
107534}
107535
107536#endif
107537
107538/************** End of fts3_snippet.c ****************************************/
107539/************** Begin file rtree.c *******************************************/
107540/*
107541** 2001 September 15
107542**
107543** The author disclaims copyright to this source code.  In place of
107544** a legal notice, here is a blessing:
107545**
107546**    May you do good and not evil.
107547**    May you find forgiveness for yourself and forgive others.
107548**    May you share freely, never taking more than you give.
107549**
107550*************************************************************************
107551** This file contains code for implementations of the r-tree and r*-tree
107552** algorithms packaged as an SQLite virtual table module.
107553*/
107554
107555#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
107556
107557/*
107558** This file contains an implementation of a couple of different variants
107559** of the r-tree algorithm. See the README file for further details. The
107560** same data-structure is used for all, but the algorithms for insert and
107561** delete operations vary. The variants used are selected at compile time
107562** by defining the following symbols:
107563*/
107564
107565/* Either, both or none of the following may be set to activate
107566** r*tree variant algorithms.
107567*/
107568#define VARIANT_RSTARTREE_CHOOSESUBTREE 0
107569#define VARIANT_RSTARTREE_REINSERT      1
107570
107571/*
107572** Exactly one of the following must be set to 1.
107573*/
107574#define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
107575#define VARIANT_GUTTMAN_LINEAR_SPLIT    0
107576#define VARIANT_RSTARTREE_SPLIT         1
107577
107578#define VARIANT_GUTTMAN_SPLIT \
107579        (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
107580
107581#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
107582  #define PickNext QuadraticPickNext
107583  #define PickSeeds QuadraticPickSeeds
107584  #define AssignCells splitNodeGuttman
107585#endif
107586#if VARIANT_GUTTMAN_LINEAR_SPLIT
107587  #define PickNext LinearPickNext
107588  #define PickSeeds LinearPickSeeds
107589  #define AssignCells splitNodeGuttman
107590#endif
107591#if VARIANT_RSTARTREE_SPLIT
107592  #define AssignCells splitNodeStartree
107593#endif
107594
107595
107596#ifndef SQLITE_CORE
107597  SQLITE_EXTENSION_INIT1
107598#else
107599#endif
107600
107601
107602#ifndef SQLITE_AMALGAMATION
107603typedef sqlite3_int64 i64;
107604typedef unsigned char u8;
107605typedef unsigned int u32;
107606#endif
107607
107608typedef struct Rtree Rtree;
107609typedef struct RtreeCursor RtreeCursor;
107610typedef struct RtreeNode RtreeNode;
107611typedef struct RtreeCell RtreeCell;
107612typedef struct RtreeConstraint RtreeConstraint;
107613typedef union RtreeCoord RtreeCoord;
107614
107615/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
107616#define RTREE_MAX_DIMENSIONS 5
107617
107618/* Size of hash table Rtree.aHash. This hash table is not expected to
107619** ever contain very many entries, so a fixed number of buckets is
107620** used.
107621*/
107622#define HASHSIZE 128
107623
107624/*
107625** An rtree virtual-table object.
107626*/
107627struct Rtree {
107628  sqlite3_vtab base;
107629  sqlite3 *db;                /* Host database connection */
107630  int iNodeSize;              /* Size in bytes of each node in the node table */
107631  int nDim;                   /* Number of dimensions */
107632  int nBytesPerCell;          /* Bytes consumed per cell */
107633  int iDepth;                 /* Current depth of the r-tree structure */
107634  char *zDb;                  /* Name of database containing r-tree table */
107635  char *zName;                /* Name of r-tree table */
107636  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
107637  int nBusy;                  /* Current number of users of this structure */
107638
107639  /* List of nodes removed during a CondenseTree operation. List is
107640  ** linked together via the pointer normally used for hash chains -
107641  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
107642  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
107643  */
107644  RtreeNode *pDeleted;
107645  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
107646
107647  /* Statements to read/write/delete a record from xxx_node */
107648  sqlite3_stmt *pReadNode;
107649  sqlite3_stmt *pWriteNode;
107650  sqlite3_stmt *pDeleteNode;
107651
107652  /* Statements to read/write/delete a record from xxx_rowid */
107653  sqlite3_stmt *pReadRowid;
107654  sqlite3_stmt *pWriteRowid;
107655  sqlite3_stmt *pDeleteRowid;
107656
107657  /* Statements to read/write/delete a record from xxx_parent */
107658  sqlite3_stmt *pReadParent;
107659  sqlite3_stmt *pWriteParent;
107660  sqlite3_stmt *pDeleteParent;
107661
107662  int eCoordType;
107663};
107664
107665/* Possible values for eCoordType: */
107666#define RTREE_COORD_REAL32 0
107667#define RTREE_COORD_INT32  1
107668
107669/*
107670** The minimum number of cells allowed for a node is a third of the
107671** maximum. In Gutman's notation:
107672**
107673**     m = M/3
107674**
107675** If an R*-tree "Reinsert" operation is required, the same number of
107676** cells are removed from the overfull node and reinserted into the tree.
107677*/
107678#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
107679#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
107680#define RTREE_MAXCELLS 51
107681
107682/*
107683** An rtree cursor object.
107684*/
107685struct RtreeCursor {
107686  sqlite3_vtab_cursor base;
107687  RtreeNode *pNode;                 /* Node cursor is currently pointing at */
107688  int iCell;                        /* Index of current cell in pNode */
107689  int iStrategy;                    /* Copy of idxNum search parameter */
107690  int nConstraint;                  /* Number of entries in aConstraint */
107691  RtreeConstraint *aConstraint;     /* Search constraints. */
107692};
107693
107694union RtreeCoord {
107695  float f;
107696  int i;
107697};
107698
107699/*
107700** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
107701** formatted as a double. This macro assumes that local variable pRtree points
107702** to the Rtree structure associated with the RtreeCoord.
107703*/
107704#define DCOORD(coord) (                           \
107705  (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
107706    ((double)coord.f) :                           \
107707    ((double)coord.i)                             \
107708)
107709
107710/*
107711** A search constraint.
107712*/
107713struct RtreeConstraint {
107714  int iCoord;                       /* Index of constrained coordinate */
107715  int op;                           /* Constraining operation */
107716  double rValue;                    /* Constraint value. */
107717};
107718
107719/* Possible values for RtreeConstraint.op */
107720#define RTREE_EQ 0x41
107721#define RTREE_LE 0x42
107722#define RTREE_LT 0x43
107723#define RTREE_GE 0x44
107724#define RTREE_GT 0x45
107725
107726/*
107727** An rtree structure node.
107728**
107729** Data format (RtreeNode.zData):
107730**
107731**   1. If the node is the root node (node 1), then the first 2 bytes
107732**      of the node contain the tree depth as a big-endian integer.
107733**      For non-root nodes, the first 2 bytes are left unused.
107734**
107735**   2. The next 2 bytes contain the number of entries currently
107736**      stored in the node.
107737**
107738**   3. The remainder of the node contains the node entries. Each entry
107739**      consists of a single 8-byte integer followed by an even number
107740**      of 4-byte coordinates. For leaf nodes the integer is the rowid
107741**      of a record. For internal nodes it is the node number of a
107742**      child page.
107743*/
107744struct RtreeNode {
107745  RtreeNode *pParent;               /* Parent node */
107746  i64 iNode;
107747  int nRef;
107748  int isDirty;
107749  u8 *zData;
107750  RtreeNode *pNext;                 /* Next node in this hash chain */
107751};
107752#define NCELL(pNode) readInt16(&(pNode)->zData[2])
107753
107754/*
107755** Structure to store a deserialized rtree record.
107756*/
107757struct RtreeCell {
107758  i64 iRowid;
107759  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
107760};
107761
107762#ifndef MAX
107763# define MAX(x,y) ((x) < (y) ? (y) : (x))
107764#endif
107765#ifndef MIN
107766# define MIN(x,y) ((x) > (y) ? (y) : (x))
107767#endif
107768
107769/*
107770** Functions to deserialize a 16 bit integer, 32 bit real number and
107771** 64 bit integer. The deserialized value is returned.
107772*/
107773static int readInt16(u8 *p){
107774  return (p[0]<<8) + p[1];
107775}
107776static void readCoord(u8 *p, RtreeCoord *pCoord){
107777  u32 i = (
107778    (((u32)p[0]) << 24) +
107779    (((u32)p[1]) << 16) +
107780    (((u32)p[2]) <<  8) +
107781    (((u32)p[3]) <<  0)
107782  );
107783  *(u32 *)pCoord = i;
107784}
107785static i64 readInt64(u8 *p){
107786  return (
107787    (((i64)p[0]) << 56) +
107788    (((i64)p[1]) << 48) +
107789    (((i64)p[2]) << 40) +
107790    (((i64)p[3]) << 32) +
107791    (((i64)p[4]) << 24) +
107792    (((i64)p[5]) << 16) +
107793    (((i64)p[6]) <<  8) +
107794    (((i64)p[7]) <<  0)
107795  );
107796}
107797
107798/*
107799** Functions to serialize a 16 bit integer, 32 bit real number and
107800** 64 bit integer. The value returned is the number of bytes written
107801** to the argument buffer (always 2, 4 and 8 respectively).
107802*/
107803static int writeInt16(u8 *p, int i){
107804  p[0] = (i>> 8)&0xFF;
107805  p[1] = (i>> 0)&0xFF;
107806  return 2;
107807}
107808static int writeCoord(u8 *p, RtreeCoord *pCoord){
107809  u32 i;
107810  assert( sizeof(RtreeCoord)==4 );
107811  assert( sizeof(u32)==4 );
107812  i = *(u32 *)pCoord;
107813  p[0] = (i>>24)&0xFF;
107814  p[1] = (i>>16)&0xFF;
107815  p[2] = (i>> 8)&0xFF;
107816  p[3] = (i>> 0)&0xFF;
107817  return 4;
107818}
107819static int writeInt64(u8 *p, i64 i){
107820  p[0] = (i>>56)&0xFF;
107821  p[1] = (i>>48)&0xFF;
107822  p[2] = (i>>40)&0xFF;
107823  p[3] = (i>>32)&0xFF;
107824  p[4] = (i>>24)&0xFF;
107825  p[5] = (i>>16)&0xFF;
107826  p[6] = (i>> 8)&0xFF;
107827  p[7] = (i>> 0)&0xFF;
107828  return 8;
107829}
107830
107831/*
107832** Increment the reference count of node p.
107833*/
107834static void nodeReference(RtreeNode *p){
107835  if( p ){
107836    p->nRef++;
107837  }
107838}
107839
107840/*
107841** Clear the content of node p (set all bytes to 0x00).
107842*/
107843static void nodeZero(Rtree *pRtree, RtreeNode *p){
107844  if( p ){
107845    memset(&p->zData[2], 0, pRtree->iNodeSize-2);
107846    p->isDirty = 1;
107847  }
107848}
107849
107850/*
107851** Given a node number iNode, return the corresponding key to use
107852** in the Rtree.aHash table.
107853*/
107854static int nodeHash(i64 iNode){
107855  return (
107856    (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
107857    (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
107858  ) % HASHSIZE;
107859}
107860
107861/*
107862** Search the node hash table for node iNode. If found, return a pointer
107863** to it. Otherwise, return 0.
107864*/
107865static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
107866  RtreeNode *p;
107867  assert( iNode!=0 );
107868  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
107869  return p;
107870}
107871
107872/*
107873** Add node pNode to the node hash table.
107874*/
107875static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
107876  if( pNode ){
107877    int iHash;
107878    assert( pNode->pNext==0 );
107879    iHash = nodeHash(pNode->iNode);
107880    pNode->pNext = pRtree->aHash[iHash];
107881    pRtree->aHash[iHash] = pNode;
107882  }
107883}
107884
107885/*
107886** Remove node pNode from the node hash table.
107887*/
107888static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
107889  RtreeNode **pp;
107890  if( pNode->iNode!=0 ){
107891    pp = &pRtree->aHash[nodeHash(pNode->iNode)];
107892    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
107893    *pp = pNode->pNext;
107894    pNode->pNext = 0;
107895  }
107896}
107897
107898/*
107899** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
107900** indicating that node has not yet been assigned a node number. It is
107901** assigned a node number when nodeWrite() is called to write the
107902** node contents out to the database.
107903*/
107904static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){
107905  RtreeNode *pNode;
107906  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
107907  if( pNode ){
107908    memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0));
107909    pNode->zData = (u8 *)&pNode[1];
107910    pNode->nRef = 1;
107911    pNode->pParent = pParent;
107912    pNode->isDirty = 1;
107913    nodeReference(pParent);
107914  }
107915  return pNode;
107916}
107917
107918/*
107919** Obtain a reference to an r-tree node.
107920*/
107921static int
107922nodeAcquire(
107923  Rtree *pRtree,             /* R-tree structure */
107924  i64 iNode,                 /* Node number to load */
107925  RtreeNode *pParent,        /* Either the parent node or NULL */
107926  RtreeNode **ppNode         /* OUT: Acquired node */
107927){
107928  int rc;
107929  RtreeNode *pNode;
107930
107931  /* Check if the requested node is already in the hash table. If so,
107932  ** increase its reference count and return it.
107933  */
107934  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
107935    assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
107936    if( pParent && !pNode->pParent ){
107937      nodeReference(pParent);
107938      pNode->pParent = pParent;
107939    }
107940    pNode->nRef++;
107941    *ppNode = pNode;
107942    return SQLITE_OK;
107943  }
107944
107945  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
107946  if( !pNode ){
107947    *ppNode = 0;
107948    return SQLITE_NOMEM;
107949  }
107950  pNode->pParent = pParent;
107951  pNode->zData = (u8 *)&pNode[1];
107952  pNode->nRef = 1;
107953  pNode->iNode = iNode;
107954  pNode->isDirty = 0;
107955  pNode->pNext = 0;
107956
107957  sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
107958  rc = sqlite3_step(pRtree->pReadNode);
107959  if( rc==SQLITE_ROW ){
107960    const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
107961    memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
107962    nodeReference(pParent);
107963  }else{
107964    sqlite3_free(pNode);
107965    pNode = 0;
107966  }
107967
107968  *ppNode = pNode;
107969  rc = sqlite3_reset(pRtree->pReadNode);
107970
107971  if( rc==SQLITE_OK && iNode==1 ){
107972    pRtree->iDepth = readInt16(pNode->zData);
107973  }
107974
107975  assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) );
107976  nodeHashInsert(pRtree, pNode);
107977
107978  return rc;
107979}
107980
107981/*
107982** Overwrite cell iCell of node pNode with the contents of pCell.
107983*/
107984static void nodeOverwriteCell(
107985  Rtree *pRtree,
107986  RtreeNode *pNode,
107987  RtreeCell *pCell,
107988  int iCell
107989){
107990  int ii;
107991  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
107992  p += writeInt64(p, pCell->iRowid);
107993  for(ii=0; ii<(pRtree->nDim*2); ii++){
107994    p += writeCoord(p, &pCell->aCoord[ii]);
107995  }
107996  pNode->isDirty = 1;
107997}
107998
107999/*
108000** Remove cell the cell with index iCell from node pNode.
108001*/
108002static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
108003  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
108004  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
108005  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
108006  memmove(pDst, pSrc, nByte);
108007  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
108008  pNode->isDirty = 1;
108009}
108010
108011/*
108012** Insert the contents of cell pCell into node pNode. If the insert
108013** is successful, return SQLITE_OK.
108014**
108015** If there is not enough free space in pNode, return SQLITE_FULL.
108016*/
108017static int
108018nodeInsertCell(
108019  Rtree *pRtree,
108020  RtreeNode *pNode,
108021  RtreeCell *pCell
108022){
108023  int nCell;                    /* Current number of cells in pNode */
108024  int nMaxCell;                 /* Maximum number of cells for pNode */
108025
108026  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
108027  nCell = NCELL(pNode);
108028
108029  assert(nCell<=nMaxCell);
108030
108031  if( nCell<nMaxCell ){
108032    nodeOverwriteCell(pRtree, pNode, pCell, nCell);
108033    writeInt16(&pNode->zData[2], nCell+1);
108034    pNode->isDirty = 1;
108035  }
108036
108037  return (nCell==nMaxCell);
108038}
108039
108040/*
108041** If the node is dirty, write it out to the database.
108042*/
108043static int
108044nodeWrite(Rtree *pRtree, RtreeNode *pNode){
108045  int rc = SQLITE_OK;
108046  if( pNode->isDirty ){
108047    sqlite3_stmt *p = pRtree->pWriteNode;
108048    if( pNode->iNode ){
108049      sqlite3_bind_int64(p, 1, pNode->iNode);
108050    }else{
108051      sqlite3_bind_null(p, 1);
108052    }
108053    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
108054    sqlite3_step(p);
108055    pNode->isDirty = 0;
108056    rc = sqlite3_reset(p);
108057    if( pNode->iNode==0 && rc==SQLITE_OK ){
108058      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
108059      nodeHashInsert(pRtree, pNode);
108060    }
108061  }
108062  return rc;
108063}
108064
108065/*
108066** Release a reference to a node. If the node is dirty and the reference
108067** count drops to zero, the node data is written to the database.
108068*/
108069static int
108070nodeRelease(Rtree *pRtree, RtreeNode *pNode){
108071  int rc = SQLITE_OK;
108072  if( pNode ){
108073    assert( pNode->nRef>0 );
108074    pNode->nRef--;
108075    if( pNode->nRef==0 ){
108076      if( pNode->iNode==1 ){
108077        pRtree->iDepth = -1;
108078      }
108079      if( pNode->pParent ){
108080        rc = nodeRelease(pRtree, pNode->pParent);
108081      }
108082      if( rc==SQLITE_OK ){
108083        rc = nodeWrite(pRtree, pNode);
108084      }
108085      nodeHashDelete(pRtree, pNode);
108086      sqlite3_free(pNode);
108087    }
108088  }
108089  return rc;
108090}
108091
108092/*
108093** Return the 64-bit integer value associated with cell iCell of
108094** node pNode. If pNode is a leaf node, this is a rowid. If it is
108095** an internal node, then the 64-bit integer is a child page number.
108096*/
108097static i64 nodeGetRowid(
108098  Rtree *pRtree,
108099  RtreeNode *pNode,
108100  int iCell
108101){
108102  assert( iCell<NCELL(pNode) );
108103  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
108104}
108105
108106/*
108107** Return coordinate iCoord from cell iCell in node pNode.
108108*/
108109static void nodeGetCoord(
108110  Rtree *pRtree,
108111  RtreeNode *pNode,
108112  int iCell,
108113  int iCoord,
108114  RtreeCoord *pCoord           /* Space to write result to */
108115){
108116  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
108117}
108118
108119/*
108120** Deserialize cell iCell of node pNode. Populate the structure pointed
108121** to by pCell with the results.
108122*/
108123static void nodeGetCell(
108124  Rtree *pRtree,
108125  RtreeNode *pNode,
108126  int iCell,
108127  RtreeCell *pCell
108128){
108129  int ii;
108130  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
108131  for(ii=0; ii<pRtree->nDim*2; ii++){
108132    nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
108133  }
108134}
108135
108136
108137/* Forward declaration for the function that does the work of
108138** the virtual table module xCreate() and xConnect() methods.
108139*/
108140static int rtreeInit(
108141  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
108142);
108143
108144/*
108145** Rtree virtual table module xCreate method.
108146*/
108147static int rtreeCreate(
108148  sqlite3 *db,
108149  void *pAux,
108150  int argc, const char *const*argv,
108151  sqlite3_vtab **ppVtab,
108152  char **pzErr
108153){
108154  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
108155}
108156
108157/*
108158** Rtree virtual table module xConnect method.
108159*/
108160static int rtreeConnect(
108161  sqlite3 *db,
108162  void *pAux,
108163  int argc, const char *const*argv,
108164  sqlite3_vtab **ppVtab,
108165  char **pzErr
108166){
108167  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
108168}
108169
108170/*
108171** Increment the r-tree reference count.
108172*/
108173static void rtreeReference(Rtree *pRtree){
108174  pRtree->nBusy++;
108175}
108176
108177/*
108178** Decrement the r-tree reference count. When the reference count reaches
108179** zero the structure is deleted.
108180*/
108181static void rtreeRelease(Rtree *pRtree){
108182  pRtree->nBusy--;
108183  if( pRtree->nBusy==0 ){
108184    sqlite3_finalize(pRtree->pReadNode);
108185    sqlite3_finalize(pRtree->pWriteNode);
108186    sqlite3_finalize(pRtree->pDeleteNode);
108187    sqlite3_finalize(pRtree->pReadRowid);
108188    sqlite3_finalize(pRtree->pWriteRowid);
108189    sqlite3_finalize(pRtree->pDeleteRowid);
108190    sqlite3_finalize(pRtree->pReadParent);
108191    sqlite3_finalize(pRtree->pWriteParent);
108192    sqlite3_finalize(pRtree->pDeleteParent);
108193    sqlite3_free(pRtree);
108194  }
108195}
108196
108197/*
108198** Rtree virtual table module xDisconnect method.
108199*/
108200static int rtreeDisconnect(sqlite3_vtab *pVtab){
108201  rtreeRelease((Rtree *)pVtab);
108202  return SQLITE_OK;
108203}
108204
108205/*
108206** Rtree virtual table module xDestroy method.
108207*/
108208static int rtreeDestroy(sqlite3_vtab *pVtab){
108209  Rtree *pRtree = (Rtree *)pVtab;
108210  int rc;
108211  char *zCreate = sqlite3_mprintf(
108212    "DROP TABLE '%q'.'%q_node';"
108213    "DROP TABLE '%q'.'%q_rowid';"
108214    "DROP TABLE '%q'.'%q_parent';",
108215    pRtree->zDb, pRtree->zName,
108216    pRtree->zDb, pRtree->zName,
108217    pRtree->zDb, pRtree->zName
108218  );
108219  if( !zCreate ){
108220    rc = SQLITE_NOMEM;
108221  }else{
108222    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
108223    sqlite3_free(zCreate);
108224  }
108225  if( rc==SQLITE_OK ){
108226    rtreeRelease(pRtree);
108227  }
108228
108229  return rc;
108230}
108231
108232/*
108233** Rtree virtual table module xOpen method.
108234*/
108235static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
108236  int rc = SQLITE_NOMEM;
108237  RtreeCursor *pCsr;
108238
108239  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
108240  if( pCsr ){
108241    memset(pCsr, 0, sizeof(RtreeCursor));
108242    pCsr->base.pVtab = pVTab;
108243    rc = SQLITE_OK;
108244  }
108245  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
108246
108247  return rc;
108248}
108249
108250/*
108251** Rtree virtual table module xClose method.
108252*/
108253static int rtreeClose(sqlite3_vtab_cursor *cur){
108254  Rtree *pRtree = (Rtree *)(cur->pVtab);
108255  int rc;
108256  RtreeCursor *pCsr = (RtreeCursor *)cur;
108257  sqlite3_free(pCsr->aConstraint);
108258  rc = nodeRelease(pRtree, pCsr->pNode);
108259  sqlite3_free(pCsr);
108260  return rc;
108261}
108262
108263/*
108264** Rtree virtual table module xEof method.
108265**
108266** Return non-zero if the cursor does not currently point to a valid
108267** record (i.e if the scan has finished), or zero otherwise.
108268*/
108269static int rtreeEof(sqlite3_vtab_cursor *cur){
108270  RtreeCursor *pCsr = (RtreeCursor *)cur;
108271  return (pCsr->pNode==0);
108272}
108273
108274/*
108275** Cursor pCursor currently points to a cell in a non-leaf page.
108276** Return true if the sub-tree headed by the cell is filtered
108277** (excluded) by the constraints in the pCursor->aConstraint[]
108278** array, or false otherwise.
108279*/
108280static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){
108281  RtreeCell cell;
108282  int ii;
108283  int bRes = 0;
108284
108285  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
108286  for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
108287    RtreeConstraint *p = &pCursor->aConstraint[ii];
108288    double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
108289    double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
108290
108291    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
108292        || p->op==RTREE_GT || p->op==RTREE_EQ
108293    );
108294
108295    switch( p->op ){
108296      case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break;
108297      case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break;
108298      case RTREE_EQ:
108299        bRes = (p->rValue>cell_max || p->rValue<cell_min);
108300        break;
108301    }
108302  }
108303
108304  return bRes;
108305}
108306
108307/*
108308** Return true if the cell that cursor pCursor currently points to
108309** would be filtered (excluded) by the constraints in the
108310** pCursor->aConstraint[] array, or false otherwise.
108311**
108312** This function assumes that the cell is part of a leaf node.
108313*/
108314static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){
108315  RtreeCell cell;
108316  int ii;
108317
108318  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
108319  for(ii=0; ii<pCursor->nConstraint; ii++){
108320    RtreeConstraint *p = &pCursor->aConstraint[ii];
108321    double coord = DCOORD(cell.aCoord[p->iCoord]);
108322    int res;
108323    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
108324        || p->op==RTREE_GT || p->op==RTREE_EQ
108325    );
108326    switch( p->op ){
108327      case RTREE_LE: res = (coord<=p->rValue); break;
108328      case RTREE_LT: res = (coord<p->rValue);  break;
108329      case RTREE_GE: res = (coord>=p->rValue); break;
108330      case RTREE_GT: res = (coord>p->rValue);  break;
108331      case RTREE_EQ: res = (coord==p->rValue); break;
108332    }
108333
108334    if( !res ) return 1;
108335  }
108336
108337  return 0;
108338}
108339
108340/*
108341** Cursor pCursor currently points at a node that heads a sub-tree of
108342** height iHeight (if iHeight==0, then the node is a leaf). Descend
108343** to point to the left-most cell of the sub-tree that matches the
108344** configured constraints.
108345*/
108346static int descendToCell(
108347  Rtree *pRtree,
108348  RtreeCursor *pCursor,
108349  int iHeight,
108350  int *pEof                 /* OUT: Set to true if cannot descend */
108351){
108352  int isEof;
108353  int rc;
108354  int ii;
108355  RtreeNode *pChild;
108356  sqlite3_int64 iRowid;
108357
108358  RtreeNode *pSavedNode = pCursor->pNode;
108359  int iSavedCell = pCursor->iCell;
108360
108361  assert( iHeight>=0 );
108362
108363  if( iHeight==0 ){
108364    isEof = testRtreeEntry(pRtree, pCursor);
108365  }else{
108366    isEof = testRtreeCell(pRtree, pCursor);
108367  }
108368  if( isEof || iHeight==0 ){
108369    *pEof = isEof;
108370    return SQLITE_OK;
108371  }
108372
108373  iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
108374  rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
108375  if( rc!=SQLITE_OK ){
108376    return rc;
108377  }
108378
108379  nodeRelease(pRtree, pCursor->pNode);
108380  pCursor->pNode = pChild;
108381  isEof = 1;
108382  for(ii=0; isEof && ii<NCELL(pChild); ii++){
108383    pCursor->iCell = ii;
108384    rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
108385    if( rc!=SQLITE_OK ){
108386      return rc;
108387    }
108388  }
108389
108390  if( isEof ){
108391    assert( pCursor->pNode==pChild );
108392    nodeReference(pSavedNode);
108393    nodeRelease(pRtree, pChild);
108394    pCursor->pNode = pSavedNode;
108395    pCursor->iCell = iSavedCell;
108396  }
108397
108398  *pEof = isEof;
108399  return SQLITE_OK;
108400}
108401
108402/*
108403** One of the cells in node pNode is guaranteed to have a 64-bit
108404** integer value equal to iRowid. Return the index of this cell.
108405*/
108406static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){
108407  int ii;
108408  for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){
108409    assert( ii<(NCELL(pNode)-1) );
108410  }
108411  return ii;
108412}
108413
108414/*
108415** Return the index of the cell containing a pointer to node pNode
108416** in its parent. If pNode is the root node, return -1.
108417*/
108418static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){
108419  RtreeNode *pParent = pNode->pParent;
108420  if( pParent ){
108421    return nodeRowidIndex(pRtree, pParent, pNode->iNode);
108422  }
108423  return -1;
108424}
108425
108426/*
108427** Rtree virtual table module xNext method.
108428*/
108429static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
108430  Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
108431  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
108432  int rc = SQLITE_OK;
108433
108434  if( pCsr->iStrategy==1 ){
108435    /* This "scan" is a direct lookup by rowid. There is no next entry. */
108436    nodeRelease(pRtree, pCsr->pNode);
108437    pCsr->pNode = 0;
108438  }
108439
108440  else if( pCsr->pNode ){
108441    /* Move to the next entry that matches the configured constraints. */
108442    int iHeight = 0;
108443    while( pCsr->pNode ){
108444      RtreeNode *pNode = pCsr->pNode;
108445      int nCell = NCELL(pNode);
108446      for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
108447        int isEof;
108448        rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
108449        if( rc!=SQLITE_OK || !isEof ){
108450          return rc;
108451        }
108452      }
108453      pCsr->pNode = pNode->pParent;
108454      pCsr->iCell = nodeParentIndex(pRtree, pNode);
108455      nodeReference(pCsr->pNode);
108456      nodeRelease(pRtree, pNode);
108457      iHeight++;
108458    }
108459  }
108460
108461  return rc;
108462}
108463
108464/*
108465** Rtree virtual table module xRowid method.
108466*/
108467static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
108468  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
108469  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
108470
108471  assert(pCsr->pNode);
108472  *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
108473
108474  return SQLITE_OK;
108475}
108476
108477/*
108478** Rtree virtual table module xColumn method.
108479*/
108480static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
108481  Rtree *pRtree = (Rtree *)cur->pVtab;
108482  RtreeCursor *pCsr = (RtreeCursor *)cur;
108483
108484  if( i==0 ){
108485    i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
108486    sqlite3_result_int64(ctx, iRowid);
108487  }else{
108488    RtreeCoord c;
108489    nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
108490    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
108491      sqlite3_result_double(ctx, c.f);
108492    }else{
108493      assert( pRtree->eCoordType==RTREE_COORD_INT32 );
108494      sqlite3_result_int(ctx, c.i);
108495    }
108496  }
108497
108498  return SQLITE_OK;
108499}
108500
108501/*
108502** Use nodeAcquire() to obtain the leaf node containing the record with
108503** rowid iRowid. If successful, set *ppLeaf to point to the node and
108504** return SQLITE_OK. If there is no such record in the table, set
108505** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
108506** to zero and return an SQLite error code.
108507*/
108508static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
108509  int rc;
108510  *ppLeaf = 0;
108511  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
108512  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
108513    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
108514    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
108515    sqlite3_reset(pRtree->pReadRowid);
108516  }else{
108517    rc = sqlite3_reset(pRtree->pReadRowid);
108518  }
108519  return rc;
108520}
108521
108522
108523/*
108524** Rtree virtual table module xFilter method.
108525*/
108526static int rtreeFilter(
108527  sqlite3_vtab_cursor *pVtabCursor,
108528  int idxNum, const char *idxStr,
108529  int argc, sqlite3_value **argv
108530){
108531  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
108532  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
108533
108534  RtreeNode *pRoot = 0;
108535  int ii;
108536  int rc = SQLITE_OK;
108537
108538  rtreeReference(pRtree);
108539
108540  sqlite3_free(pCsr->aConstraint);
108541  pCsr->aConstraint = 0;
108542  pCsr->iStrategy = idxNum;
108543
108544  if( idxNum==1 ){
108545    /* Special case - lookup by rowid. */
108546    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
108547    i64 iRowid = sqlite3_value_int64(argv[0]);
108548    rc = findLeafNode(pRtree, iRowid, &pLeaf);
108549    pCsr->pNode = pLeaf;
108550    if( pLeaf && rc==SQLITE_OK ){
108551      pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid);
108552    }
108553  }else{
108554    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
108555    ** with the configured constraints.
108556    */
108557    if( argc>0 ){
108558      pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
108559      pCsr->nConstraint = argc;
108560      if( !pCsr->aConstraint ){
108561        rc = SQLITE_NOMEM;
108562      }else{
108563        assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
108564        for(ii=0; ii<argc; ii++){
108565          RtreeConstraint *p = &pCsr->aConstraint[ii];
108566          p->op = idxStr[ii*2];
108567          p->iCoord = idxStr[ii*2+1]-'a';
108568          p->rValue = sqlite3_value_double(argv[ii]);
108569        }
108570      }
108571    }
108572
108573    if( rc==SQLITE_OK ){
108574      pCsr->pNode = 0;
108575      rc = nodeAcquire(pRtree, 1, 0, &pRoot);
108576    }
108577    if( rc==SQLITE_OK ){
108578      int isEof = 1;
108579      int nCell = NCELL(pRoot);
108580      pCsr->pNode = pRoot;
108581      for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
108582        assert( pCsr->pNode==pRoot );
108583        rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
108584        if( !isEof ){
108585          break;
108586        }
108587      }
108588      if( rc==SQLITE_OK && isEof ){
108589        assert( pCsr->pNode==pRoot );
108590        nodeRelease(pRtree, pRoot);
108591        pCsr->pNode = 0;
108592      }
108593      assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
108594    }
108595  }
108596
108597  rtreeRelease(pRtree);
108598  return rc;
108599}
108600
108601/*
108602** Rtree virtual table module xBestIndex method. There are three
108603** table scan strategies to choose from (in order from most to
108604** least desirable):
108605**
108606**   idxNum     idxStr        Strategy
108607**   ------------------------------------------------
108608**     1        Unused        Direct lookup by rowid.
108609**     2        See below     R-tree query.
108610**     3        Unused        Full table scan.
108611**   ------------------------------------------------
108612**
108613** If strategy 1 or 3 is used, then idxStr is not meaningful. If strategy
108614** 2 is used, idxStr is formatted to contain 2 bytes for each
108615** constraint used. The first two bytes of idxStr correspond to
108616** the constraint in sqlite3_index_info.aConstraintUsage[] with
108617** (argvIndex==1) etc.
108618**
108619** The first of each pair of bytes in idxStr identifies the constraint
108620** operator as follows:
108621**
108622**   Operator    Byte Value
108623**   ----------------------
108624**      =        0x41 ('A')
108625**     <=        0x42 ('B')
108626**      <        0x43 ('C')
108627**     >=        0x44 ('D')
108628**      >        0x45 ('E')
108629**   ----------------------
108630**
108631** The second of each pair of bytes identifies the coordinate column
108632** to which the constraint applies. The leftmost coordinate column
108633** is 'a', the second from the left 'b' etc.
108634*/
108635static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
108636  int rc = SQLITE_OK;
108637  int ii, cCol;
108638
108639  int iIdx = 0;
108640  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
108641  memset(zIdxStr, 0, sizeof(zIdxStr));
108642
108643  assert( pIdxInfo->idxStr==0 );
108644  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
108645    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
108646
108647    if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
108648      /* We have an equality constraint on the rowid. Use strategy 1. */
108649      int jj;
108650      for(jj=0; jj<ii; jj++){
108651        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
108652        pIdxInfo->aConstraintUsage[jj].omit = 0;
108653      }
108654      pIdxInfo->idxNum = 1;
108655      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
108656      pIdxInfo->aConstraintUsage[jj].omit = 1;
108657
108658      /* This strategy involves a two rowid lookups on an B-Tree structures
108659      ** and then a linear search of an R-Tree node. This should be
108660      ** considered almost as quick as a direct rowid lookup (for which
108661      ** sqlite uses an internal cost of 0.0).
108662      */
108663      pIdxInfo->estimatedCost = 10.0;
108664      return SQLITE_OK;
108665    }
108666
108667    if( p->usable && p->iColumn>0 ){
108668      u8 op = 0;
108669      switch( p->op ){
108670        case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
108671        case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
108672        case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
108673        case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
108674        case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
108675      }
108676      if( op ){
108677        /* Make sure this particular constraint has not been used before.
108678        ** If it has been used before, ignore it.
108679        **
108680        ** A <= or < can be used if there is a prior >= or >.
108681        ** A >= or > can be used if there is a prior < or <=.
108682        ** A <= or < is disqualified if there is a prior <=, <, or ==.
108683        ** A >= or > is disqualified if there is a prior >=, >, or ==.
108684        ** A == is disqualifed if there is any prior constraint.
108685        */
108686        int j, opmsk;
108687        static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
108688        assert( compatible[RTREE_EQ & 7]==0 );
108689        assert( compatible[RTREE_LT & 7]==1 );
108690        assert( compatible[RTREE_LE & 7]==1 );
108691        assert( compatible[RTREE_GT & 7]==2 );
108692        assert( compatible[RTREE_GE & 7]==2 );
108693        cCol = p->iColumn - 1 + 'a';
108694        opmsk = compatible[op & 7];
108695        for(j=0; j<iIdx; j+=2){
108696          if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
108697            op = 0;
108698            break;
108699          }
108700        }
108701      }
108702      if( op ){
108703        assert( iIdx<sizeof(zIdxStr)-1 );
108704        zIdxStr[iIdx++] = op;
108705        zIdxStr[iIdx++] = cCol;
108706        pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
108707        pIdxInfo->aConstraintUsage[ii].omit = 1;
108708      }
108709    }
108710  }
108711
108712  pIdxInfo->idxNum = 2;
108713  pIdxInfo->needToFreeIdxStr = 1;
108714  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
108715    return SQLITE_NOMEM;
108716  }
108717  assert( iIdx>=0 );
108718  pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
108719  return rc;
108720}
108721
108722/*
108723** Return the N-dimensional volumn of the cell stored in *p.
108724*/
108725static float cellArea(Rtree *pRtree, RtreeCell *p){
108726  float area = 1.0;
108727  int ii;
108728  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108729    area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
108730  }
108731  return area;
108732}
108733
108734/*
108735** Return the margin length of cell p. The margin length is the sum
108736** of the objects size in each dimension.
108737*/
108738static float cellMargin(Rtree *pRtree, RtreeCell *p){
108739  float margin = 0.0;
108740  int ii;
108741  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108742    margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
108743  }
108744  return margin;
108745}
108746
108747/*
108748** Store the union of cells p1 and p2 in p1.
108749*/
108750static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
108751  int ii;
108752  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
108753    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108754      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
108755      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
108756    }
108757  }else{
108758    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108759      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
108760      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
108761    }
108762  }
108763}
108764
108765/*
108766** Return true if the area covered by p2 is a subset of the area covered
108767** by p1. False otherwise.
108768*/
108769static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
108770  int ii;
108771  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
108772  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108773    RtreeCoord *a1 = &p1->aCoord[ii];
108774    RtreeCoord *a2 = &p2->aCoord[ii];
108775    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
108776     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
108777    ){
108778      return 0;
108779    }
108780  }
108781  return 1;
108782}
108783
108784/*
108785** Return the amount cell p would grow by if it were unioned with pCell.
108786*/
108787static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
108788  float area;
108789  RtreeCell cell;
108790  memcpy(&cell, p, sizeof(RtreeCell));
108791  area = cellArea(pRtree, &cell);
108792  cellUnion(pRtree, &cell, pCell);
108793  return (cellArea(pRtree, &cell)-area);
108794}
108795
108796#if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
108797static float cellOverlap(
108798  Rtree *pRtree,
108799  RtreeCell *p,
108800  RtreeCell *aCell,
108801  int nCell,
108802  int iExclude
108803){
108804  int ii;
108805  float overlap = 0.0;
108806  for(ii=0; ii<nCell; ii++){
108807    if( ii!=iExclude ){
108808      int jj;
108809      float o = 1.0;
108810      for(jj=0; jj<(pRtree->nDim*2); jj+=2){
108811        double x1;
108812        double x2;
108813
108814        x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
108815        x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
108816
108817        if( x2<x1 ){
108818          o = 0.0;
108819          break;
108820        }else{
108821          o = o * (x2-x1);
108822        }
108823      }
108824      overlap += o;
108825    }
108826  }
108827  return overlap;
108828}
108829#endif
108830
108831#if VARIANT_RSTARTREE_CHOOSESUBTREE
108832static float cellOverlapEnlargement(
108833  Rtree *pRtree,
108834  RtreeCell *p,
108835  RtreeCell *pInsert,
108836  RtreeCell *aCell,
108837  int nCell,
108838  int iExclude
108839){
108840  float before;
108841  float after;
108842  before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
108843  cellUnion(pRtree, p, pInsert);
108844  after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
108845  return after-before;
108846}
108847#endif
108848
108849
108850/*
108851** This function implements the ChooseLeaf algorithm from Gutman[84].
108852** ChooseSubTree in r*tree terminology.
108853*/
108854static int ChooseLeaf(
108855  Rtree *pRtree,               /* Rtree table */
108856  RtreeCell *pCell,            /* Cell to insert into rtree */
108857  int iHeight,                 /* Height of sub-tree rooted at pCell */
108858  RtreeNode **ppLeaf           /* OUT: Selected leaf page */
108859){
108860  int rc;
108861  int ii;
108862  RtreeNode *pNode;
108863  rc = nodeAcquire(pRtree, 1, 0, &pNode);
108864
108865  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
108866    int iCell;
108867    sqlite3_int64 iBest;
108868
108869    float fMinGrowth;
108870    float fMinArea;
108871    float fMinOverlap;
108872
108873    int nCell = NCELL(pNode);
108874    RtreeCell cell;
108875    RtreeNode *pChild;
108876
108877    RtreeCell *aCell = 0;
108878
108879#if VARIANT_RSTARTREE_CHOOSESUBTREE
108880    if( ii==(pRtree->iDepth-1) ){
108881      int jj;
108882      aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
108883      if( !aCell ){
108884        rc = SQLITE_NOMEM;
108885        nodeRelease(pRtree, pNode);
108886        pNode = 0;
108887        continue;
108888      }
108889      for(jj=0; jj<nCell; jj++){
108890        nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
108891      }
108892    }
108893#endif
108894
108895    /* Select the child node which will be enlarged the least if pCell
108896    ** is inserted into it. Resolve ties by choosing the entry with
108897    ** the smallest area.
108898    */
108899    for(iCell=0; iCell<nCell; iCell++){
108900      float growth;
108901      float area;
108902      float overlap = 0.0;
108903      nodeGetCell(pRtree, pNode, iCell, &cell);
108904      growth = cellGrowth(pRtree, &cell, pCell);
108905      area = cellArea(pRtree, &cell);
108906#if VARIANT_RSTARTREE_CHOOSESUBTREE
108907      if( ii==(pRtree->iDepth-1) ){
108908        overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
108909      }
108910#endif
108911      if( (iCell==0)
108912       || (overlap<fMinOverlap)
108913       || (overlap==fMinOverlap && growth<fMinGrowth)
108914       || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
108915      ){
108916        fMinOverlap = overlap;
108917        fMinGrowth = growth;
108918        fMinArea = area;
108919        iBest = cell.iRowid;
108920      }
108921    }
108922
108923    sqlite3_free(aCell);
108924    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
108925    nodeRelease(pRtree, pNode);
108926    pNode = pChild;
108927  }
108928
108929  *ppLeaf = pNode;
108930  return rc;
108931}
108932
108933/*
108934** A cell with the same content as pCell has just been inserted into
108935** the node pNode. This function updates the bounding box cells in
108936** all ancestor elements.
108937*/
108938static void AdjustTree(
108939  Rtree *pRtree,                    /* Rtree table */
108940  RtreeNode *pNode,                 /* Adjust ancestry of this node. */
108941  RtreeCell *pCell                  /* This cell was just inserted */
108942){
108943  RtreeNode *p = pNode;
108944  while( p->pParent ){
108945    RtreeCell cell;
108946    RtreeNode *pParent = p->pParent;
108947    int iCell = nodeParentIndex(pRtree, p);
108948
108949    nodeGetCell(pRtree, pParent, iCell, &cell);
108950    if( !cellContains(pRtree, &cell, pCell) ){
108951      cellUnion(pRtree, &cell, pCell);
108952      nodeOverwriteCell(pRtree, pParent, &cell, iCell);
108953    }
108954
108955    p = pParent;
108956  }
108957}
108958
108959/*
108960** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
108961*/
108962static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
108963  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
108964  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
108965  sqlite3_step(pRtree->pWriteRowid);
108966  return sqlite3_reset(pRtree->pWriteRowid);
108967}
108968
108969/*
108970** Write mapping (iNode->iPar) to the <rtree>_parent table.
108971*/
108972static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
108973  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
108974  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
108975  sqlite3_step(pRtree->pWriteParent);
108976  return sqlite3_reset(pRtree->pWriteParent);
108977}
108978
108979static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
108980
108981#if VARIANT_GUTTMAN_LINEAR_SPLIT
108982/*
108983** Implementation of the linear variant of the PickNext() function from
108984** Guttman[84].
108985*/
108986static RtreeCell *LinearPickNext(
108987  Rtree *pRtree,
108988  RtreeCell *aCell,
108989  int nCell,
108990  RtreeCell *pLeftBox,
108991  RtreeCell *pRightBox,
108992  int *aiUsed
108993){
108994  int ii;
108995  for(ii=0; aiUsed[ii]; ii++);
108996  aiUsed[ii] = 1;
108997  return &aCell[ii];
108998}
108999
109000/*
109001** Implementation of the linear variant of the PickSeeds() function from
109002** Guttman[84].
109003*/
109004static void LinearPickSeeds(
109005  Rtree *pRtree,
109006  RtreeCell *aCell,
109007  int nCell,
109008  int *piLeftSeed,
109009  int *piRightSeed
109010){
109011  int i;
109012  int iLeftSeed = 0;
109013  int iRightSeed = 1;
109014  float maxNormalInnerWidth = 0.0;
109015
109016  /* Pick two "seed" cells from the array of cells. The algorithm used
109017  ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
109018  ** indices of the two seed cells in the array are stored in local
109019  ** variables iLeftSeek and iRightSeed.
109020  */
109021  for(i=0; i<pRtree->nDim; i++){
109022    float x1 = DCOORD(aCell[0].aCoord[i*2]);
109023    float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
109024    float x3 = x1;
109025    float x4 = x2;
109026    int jj;
109027
109028    int iCellLeft = 0;
109029    int iCellRight = 0;
109030
109031    for(jj=1; jj<nCell; jj++){
109032      float left = DCOORD(aCell[jj].aCoord[i*2]);
109033      float right = DCOORD(aCell[jj].aCoord[i*2+1]);
109034
109035      if( left<x1 ) x1 = left;
109036      if( right>x4 ) x4 = right;
109037      if( left>x3 ){
109038        x3 = left;
109039        iCellRight = jj;
109040      }
109041      if( right<x2 ){
109042        x2 = right;
109043        iCellLeft = jj;
109044      }
109045    }
109046
109047    if( x4!=x1 ){
109048      float normalwidth = (x3 - x2) / (x4 - x1);
109049      if( normalwidth>maxNormalInnerWidth ){
109050        iLeftSeed = iCellLeft;
109051        iRightSeed = iCellRight;
109052      }
109053    }
109054  }
109055
109056  *piLeftSeed = iLeftSeed;
109057  *piRightSeed = iRightSeed;
109058}
109059#endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
109060
109061#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
109062/*
109063** Implementation of the quadratic variant of the PickNext() function from
109064** Guttman[84].
109065*/
109066static RtreeCell *QuadraticPickNext(
109067  Rtree *pRtree,
109068  RtreeCell *aCell,
109069  int nCell,
109070  RtreeCell *pLeftBox,
109071  RtreeCell *pRightBox,
109072  int *aiUsed
109073){
109074  #define FABS(a) ((a)<0.0?-1.0*(a):(a))
109075
109076  int iSelect = -1;
109077  float fDiff;
109078  int ii;
109079  for(ii=0; ii<nCell; ii++){
109080    if( aiUsed[ii]==0 ){
109081      float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
109082      float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
109083      float diff = FABS(right-left);
109084      if( iSelect<0 || diff>fDiff ){
109085        fDiff = diff;
109086        iSelect = ii;
109087      }
109088    }
109089  }
109090  aiUsed[iSelect] = 1;
109091  return &aCell[iSelect];
109092}
109093
109094/*
109095** Implementation of the quadratic variant of the PickSeeds() function from
109096** Guttman[84].
109097*/
109098static void QuadraticPickSeeds(
109099  Rtree *pRtree,
109100  RtreeCell *aCell,
109101  int nCell,
109102  int *piLeftSeed,
109103  int *piRightSeed
109104){
109105  int ii;
109106  int jj;
109107
109108  int iLeftSeed = 0;
109109  int iRightSeed = 1;
109110  float fWaste = 0.0;
109111
109112  for(ii=0; ii<nCell; ii++){
109113    for(jj=ii+1; jj<nCell; jj++){
109114      float right = cellArea(pRtree, &aCell[jj]);
109115      float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
109116      float waste = growth - right;
109117
109118      if( waste>fWaste ){
109119        iLeftSeed = ii;
109120        iRightSeed = jj;
109121        fWaste = waste;
109122      }
109123    }
109124  }
109125
109126  *piLeftSeed = iLeftSeed;
109127  *piRightSeed = iRightSeed;
109128}
109129#endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
109130
109131/*
109132** Arguments aIdx, aDistance and aSpare all point to arrays of size
109133** nIdx. The aIdx array contains the set of integers from 0 to
109134** (nIdx-1) in no particular order. This function sorts the values
109135** in aIdx according to the indexed values in aDistance. For
109136** example, assuming the inputs:
109137**
109138**   aIdx      = { 0,   1,   2,   3 }
109139**   aDistance = { 5.0, 2.0, 7.0, 6.0 }
109140**
109141** this function sets the aIdx array to contain:
109142**
109143**   aIdx      = { 0,   1,   2,   3 }
109144**
109145** The aSpare array is used as temporary working space by the
109146** sorting algorithm.
109147*/
109148static void SortByDistance(
109149  int *aIdx,
109150  int nIdx,
109151  float *aDistance,
109152  int *aSpare
109153){
109154  if( nIdx>1 ){
109155    int iLeft = 0;
109156    int iRight = 0;
109157
109158    int nLeft = nIdx/2;
109159    int nRight = nIdx-nLeft;
109160    int *aLeft = aIdx;
109161    int *aRight = &aIdx[nLeft];
109162
109163    SortByDistance(aLeft, nLeft, aDistance, aSpare);
109164    SortByDistance(aRight, nRight, aDistance, aSpare);
109165
109166    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
109167    aLeft = aSpare;
109168
109169    while( iLeft<nLeft || iRight<nRight ){
109170      if( iLeft==nLeft ){
109171        aIdx[iLeft+iRight] = aRight[iRight];
109172        iRight++;
109173      }else if( iRight==nRight ){
109174        aIdx[iLeft+iRight] = aLeft[iLeft];
109175        iLeft++;
109176      }else{
109177        float fLeft = aDistance[aLeft[iLeft]];
109178        float fRight = aDistance[aRight[iRight]];
109179        if( fLeft<fRight ){
109180          aIdx[iLeft+iRight] = aLeft[iLeft];
109181          iLeft++;
109182        }else{
109183          aIdx[iLeft+iRight] = aRight[iRight];
109184          iRight++;
109185        }
109186      }
109187    }
109188
109189#if 0
109190    /* Check that the sort worked */
109191    {
109192      int jj;
109193      for(jj=1; jj<nIdx; jj++){
109194        float left = aDistance[aIdx[jj-1]];
109195        float right = aDistance[aIdx[jj]];
109196        assert( left<=right );
109197      }
109198    }
109199#endif
109200  }
109201}
109202
109203/*
109204** Arguments aIdx, aCell and aSpare all point to arrays of size
109205** nIdx. The aIdx array contains the set of integers from 0 to
109206** (nIdx-1) in no particular order. This function sorts the values
109207** in aIdx according to dimension iDim of the cells in aCell. The
109208** minimum value of dimension iDim is considered first, the
109209** maximum used to break ties.
109210**
109211** The aSpare array is used as temporary working space by the
109212** sorting algorithm.
109213*/
109214static void SortByDimension(
109215  Rtree *pRtree,
109216  int *aIdx,
109217  int nIdx,
109218  int iDim,
109219  RtreeCell *aCell,
109220  int *aSpare
109221){
109222  if( nIdx>1 ){
109223
109224    int iLeft = 0;
109225    int iRight = 0;
109226
109227    int nLeft = nIdx/2;
109228    int nRight = nIdx-nLeft;
109229    int *aLeft = aIdx;
109230    int *aRight = &aIdx[nLeft];
109231
109232    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
109233    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
109234
109235    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
109236    aLeft = aSpare;
109237    while( iLeft<nLeft || iRight<nRight ){
109238      double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
109239      double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
109240      double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
109241      double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
109242      if( (iLeft!=nLeft) && ((iRight==nRight)
109243       || (xleft1<xright1)
109244       || (xleft1==xright1 && xleft2<xright2)
109245      )){
109246        aIdx[iLeft+iRight] = aLeft[iLeft];
109247        iLeft++;
109248      }else{
109249        aIdx[iLeft+iRight] = aRight[iRight];
109250        iRight++;
109251      }
109252    }
109253
109254#if 0
109255    /* Check that the sort worked */
109256    {
109257      int jj;
109258      for(jj=1; jj<nIdx; jj++){
109259        float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
109260        float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
109261        float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
109262        float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
109263        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
109264      }
109265    }
109266#endif
109267  }
109268}
109269
109270#if VARIANT_RSTARTREE_SPLIT
109271/*
109272** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
109273*/
109274static int splitNodeStartree(
109275  Rtree *pRtree,
109276  RtreeCell *aCell,
109277  int nCell,
109278  RtreeNode *pLeft,
109279  RtreeNode *pRight,
109280  RtreeCell *pBboxLeft,
109281  RtreeCell *pBboxRight
109282){
109283  int **aaSorted;
109284  int *aSpare;
109285  int ii;
109286
109287  int iBestDim;
109288  int iBestSplit;
109289  float fBestMargin;
109290
109291  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
109292
109293  aaSorted = (int **)sqlite3_malloc(nByte);
109294  if( !aaSorted ){
109295    return SQLITE_NOMEM;
109296  }
109297
109298  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
109299  memset(aaSorted, 0, nByte);
109300  for(ii=0; ii<pRtree->nDim; ii++){
109301    int jj;
109302    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
109303    for(jj=0; jj<nCell; jj++){
109304      aaSorted[ii][jj] = jj;
109305    }
109306    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
109307  }
109308
109309  for(ii=0; ii<pRtree->nDim; ii++){
109310    float margin = 0.0;
109311    float fBestOverlap;
109312    float fBestArea;
109313    int iBestLeft;
109314    int nLeft;
109315
109316    for(
109317      nLeft=RTREE_MINCELLS(pRtree);
109318      nLeft<=(nCell-RTREE_MINCELLS(pRtree));
109319      nLeft++
109320    ){
109321      RtreeCell left;
109322      RtreeCell right;
109323      int kk;
109324      float overlap;
109325      float area;
109326
109327      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
109328      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
109329      for(kk=1; kk<(nCell-1); kk++){
109330        if( kk<nLeft ){
109331          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
109332        }else{
109333          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
109334        }
109335      }
109336      margin += cellMargin(pRtree, &left);
109337      margin += cellMargin(pRtree, &right);
109338      overlap = cellOverlap(pRtree, &left, &right, 1, -1);
109339      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
109340      if( (nLeft==RTREE_MINCELLS(pRtree))
109341       || (overlap<fBestOverlap)
109342       || (overlap==fBestOverlap && area<fBestArea)
109343      ){
109344        iBestLeft = nLeft;
109345        fBestOverlap = overlap;
109346        fBestArea = area;
109347      }
109348    }
109349
109350    if( ii==0 || margin<fBestMargin ){
109351      iBestDim = ii;
109352      fBestMargin = margin;
109353      iBestSplit = iBestLeft;
109354    }
109355  }
109356
109357  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
109358  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
109359  for(ii=0; ii<nCell; ii++){
109360    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
109361    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
109362    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
109363    nodeInsertCell(pRtree, pTarget, pCell);
109364    cellUnion(pRtree, pBbox, pCell);
109365  }
109366
109367  sqlite3_free(aaSorted);
109368  return SQLITE_OK;
109369}
109370#endif
109371
109372#if VARIANT_GUTTMAN_SPLIT
109373/*
109374** Implementation of the regular R-tree SplitNode from Guttman[1984].
109375*/
109376static int splitNodeGuttman(
109377  Rtree *pRtree,
109378  RtreeCell *aCell,
109379  int nCell,
109380  RtreeNode *pLeft,
109381  RtreeNode *pRight,
109382  RtreeCell *pBboxLeft,
109383  RtreeCell *pBboxRight
109384){
109385  int iLeftSeed = 0;
109386  int iRightSeed = 1;
109387  int *aiUsed;
109388  int i;
109389
109390  aiUsed = sqlite3_malloc(sizeof(int)*nCell);
109391  if( !aiUsed ){
109392    return SQLITE_NOMEM;
109393  }
109394  memset(aiUsed, 0, sizeof(int)*nCell);
109395
109396  PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
109397
109398  memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
109399  memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
109400  nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
109401  nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
109402  aiUsed[iLeftSeed] = 1;
109403  aiUsed[iRightSeed] = 1;
109404
109405  for(i=nCell-2; i>0; i--){
109406    RtreeCell *pNext;
109407    pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
109408    float diff =
109409      cellGrowth(pRtree, pBboxLeft, pNext) -
109410      cellGrowth(pRtree, pBboxRight, pNext)
109411    ;
109412    if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
109413     || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
109414    ){
109415      nodeInsertCell(pRtree, pRight, pNext);
109416      cellUnion(pRtree, pBboxRight, pNext);
109417    }else{
109418      nodeInsertCell(pRtree, pLeft, pNext);
109419      cellUnion(pRtree, pBboxLeft, pNext);
109420    }
109421  }
109422
109423  sqlite3_free(aiUsed);
109424  return SQLITE_OK;
109425}
109426#endif
109427
109428static int updateMapping(
109429  Rtree *pRtree,
109430  i64 iRowid,
109431  RtreeNode *pNode,
109432  int iHeight
109433){
109434  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
109435  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
109436  if( iHeight>0 ){
109437    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
109438    if( pChild ){
109439      nodeRelease(pRtree, pChild->pParent);
109440      nodeReference(pNode);
109441      pChild->pParent = pNode;
109442    }
109443  }
109444  return xSetMapping(pRtree, iRowid, pNode->iNode);
109445}
109446
109447static int SplitNode(
109448  Rtree *pRtree,
109449  RtreeNode *pNode,
109450  RtreeCell *pCell,
109451  int iHeight
109452){
109453  int i;
109454  int newCellIsRight = 0;
109455
109456  int rc = SQLITE_OK;
109457  int nCell = NCELL(pNode);
109458  RtreeCell *aCell;
109459  int *aiUsed;
109460
109461  RtreeNode *pLeft = 0;
109462  RtreeNode *pRight = 0;
109463
109464  RtreeCell leftbbox;
109465  RtreeCell rightbbox;
109466
109467  /* Allocate an array and populate it with a copy of pCell and
109468  ** all cells from node pLeft. Then zero the original node.
109469  */
109470  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
109471  if( !aCell ){
109472    rc = SQLITE_NOMEM;
109473    goto splitnode_out;
109474  }
109475  aiUsed = (int *)&aCell[nCell+1];
109476  memset(aiUsed, 0, sizeof(int)*(nCell+1));
109477  for(i=0; i<nCell; i++){
109478    nodeGetCell(pRtree, pNode, i, &aCell[i]);
109479  }
109480  nodeZero(pRtree, pNode);
109481  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
109482  nCell++;
109483
109484  if( pNode->iNode==1 ){
109485    pRight = nodeNew(pRtree, pNode, 1);
109486    pLeft = nodeNew(pRtree, pNode, 1);
109487    pRtree->iDepth++;
109488    pNode->isDirty = 1;
109489    writeInt16(pNode->zData, pRtree->iDepth);
109490  }else{
109491    pLeft = pNode;
109492    pRight = nodeNew(pRtree, pLeft->pParent, 1);
109493    nodeReference(pLeft);
109494  }
109495
109496  if( !pLeft || !pRight ){
109497    rc = SQLITE_NOMEM;
109498    goto splitnode_out;
109499  }
109500
109501  memset(pLeft->zData, 0, pRtree->iNodeSize);
109502  memset(pRight->zData, 0, pRtree->iNodeSize);
109503
109504  rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
109505  if( rc!=SQLITE_OK ){
109506    goto splitnode_out;
109507  }
109508
109509  /* Ensure both child nodes have node numbers assigned to them. */
109510  if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)))
109511   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
109512  ){
109513    goto splitnode_out;
109514  }
109515
109516  rightbbox.iRowid = pRight->iNode;
109517  leftbbox.iRowid = pLeft->iNode;
109518
109519  if( pNode->iNode==1 ){
109520    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
109521    if( rc!=SQLITE_OK ){
109522      goto splitnode_out;
109523    }
109524  }else{
109525    RtreeNode *pParent = pLeft->pParent;
109526    int iCell = nodeParentIndex(pRtree, pLeft);
109527    nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
109528    AdjustTree(pRtree, pParent, &leftbbox);
109529  }
109530  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
109531    goto splitnode_out;
109532  }
109533
109534  for(i=0; i<NCELL(pRight); i++){
109535    i64 iRowid = nodeGetRowid(pRtree, pRight, i);
109536    rc = updateMapping(pRtree, iRowid, pRight, iHeight);
109537    if( iRowid==pCell->iRowid ){
109538      newCellIsRight = 1;
109539    }
109540    if( rc!=SQLITE_OK ){
109541      goto splitnode_out;
109542    }
109543  }
109544  if( pNode->iNode==1 ){
109545    for(i=0; i<NCELL(pLeft); i++){
109546      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
109547      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
109548      if( rc!=SQLITE_OK ){
109549        goto splitnode_out;
109550      }
109551    }
109552  }else if( newCellIsRight==0 ){
109553    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
109554  }
109555
109556  if( rc==SQLITE_OK ){
109557    rc = nodeRelease(pRtree, pRight);
109558    pRight = 0;
109559  }
109560  if( rc==SQLITE_OK ){
109561    rc = nodeRelease(pRtree, pLeft);
109562    pLeft = 0;
109563  }
109564
109565splitnode_out:
109566  nodeRelease(pRtree, pRight);
109567  nodeRelease(pRtree, pLeft);
109568  sqlite3_free(aCell);
109569  return rc;
109570}
109571
109572static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
109573  int rc = SQLITE_OK;
109574  if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){
109575    sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode);
109576    if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){
109577      i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
109578      rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent);
109579    }else{
109580      rc = SQLITE_ERROR;
109581    }
109582    sqlite3_reset(pRtree->pReadParent);
109583    if( rc==SQLITE_OK ){
109584      rc = fixLeafParent(pRtree, pLeaf->pParent);
109585    }
109586  }
109587  return rc;
109588}
109589
109590static int deleteCell(Rtree *, RtreeNode *, int, int);
109591
109592static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
109593  int rc;
109594  RtreeNode *pParent;
109595  int iCell;
109596
109597  assert( pNode->nRef==1 );
109598
109599  /* Remove the entry in the parent cell. */
109600  iCell = nodeParentIndex(pRtree, pNode);
109601  pParent = pNode->pParent;
109602  pNode->pParent = 0;
109603  if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1))
109604   || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent))
109605  ){
109606    return rc;
109607  }
109608
109609  /* Remove the xxx_node entry. */
109610  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
109611  sqlite3_step(pRtree->pDeleteNode);
109612  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
109613    return rc;
109614  }
109615
109616  /* Remove the xxx_parent entry. */
109617  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
109618  sqlite3_step(pRtree->pDeleteParent);
109619  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
109620    return rc;
109621  }
109622
109623  /* Remove the node from the in-memory hash table and link it into
109624  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
109625  */
109626  nodeHashDelete(pRtree, pNode);
109627  pNode->iNode = iHeight;
109628  pNode->pNext = pRtree->pDeleted;
109629  pNode->nRef++;
109630  pRtree->pDeleted = pNode;
109631
109632  return SQLITE_OK;
109633}
109634
109635static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
109636  RtreeNode *pParent = pNode->pParent;
109637  if( pParent ){
109638    int ii;
109639    int nCell = NCELL(pNode);
109640    RtreeCell box;                            /* Bounding box for pNode */
109641    nodeGetCell(pRtree, pNode, 0, &box);
109642    for(ii=1; ii<nCell; ii++){
109643      RtreeCell cell;
109644      nodeGetCell(pRtree, pNode, ii, &cell);
109645      cellUnion(pRtree, &box, &cell);
109646    }
109647    box.iRowid = pNode->iNode;
109648    ii = nodeParentIndex(pRtree, pNode);
109649    nodeOverwriteCell(pRtree, pParent, &box, ii);
109650    fixBoundingBox(pRtree, pParent);
109651  }
109652}
109653
109654/*
109655** Delete the cell at index iCell of node pNode. After removing the
109656** cell, adjust the r-tree data structure if required.
109657*/
109658static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
109659  int rc;
109660
109661  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
109662    return rc;
109663  }
109664
109665  /* Remove the cell from the node. This call just moves bytes around
109666  ** the in-memory node image, so it cannot fail.
109667  */
109668  nodeDeleteCell(pRtree, pNode, iCell);
109669
109670  /* If the node is not the tree root and now has less than the minimum
109671  ** number of cells, remove it from the tree. Otherwise, update the
109672  ** cell in the parent node so that it tightly contains the updated
109673  ** node.
109674  */
109675  if( pNode->iNode!=1 ){
109676    RtreeNode *pParent = pNode->pParent;
109677    if( (pParent->iNode!=1 || NCELL(pParent)!=1)
109678     && (NCELL(pNode)<RTREE_MINCELLS(pRtree))
109679    ){
109680      rc = removeNode(pRtree, pNode, iHeight);
109681    }else{
109682      fixBoundingBox(pRtree, pNode);
109683    }
109684  }
109685
109686  return rc;
109687}
109688
109689static int Reinsert(
109690  Rtree *pRtree,
109691  RtreeNode *pNode,
109692  RtreeCell *pCell,
109693  int iHeight
109694){
109695  int *aOrder;
109696  int *aSpare;
109697  RtreeCell *aCell;
109698  float *aDistance;
109699  int nCell;
109700  float aCenterCoord[RTREE_MAX_DIMENSIONS];
109701  int iDim;
109702  int ii;
109703  int rc = SQLITE_OK;
109704
109705  memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
109706
109707  nCell = NCELL(pNode)+1;
109708
109709  /* Allocate the buffers used by this operation. The allocation is
109710  ** relinquished before this function returns.
109711  */
109712  aCell = (RtreeCell *)sqlite3_malloc(nCell * (
109713    sizeof(RtreeCell) +         /* aCell array */
109714    sizeof(int)       +         /* aOrder array */
109715    sizeof(int)       +         /* aSpare array */
109716    sizeof(float)               /* aDistance array */
109717  ));
109718  if( !aCell ){
109719    return SQLITE_NOMEM;
109720  }
109721  aOrder    = (int *)&aCell[nCell];
109722  aSpare    = (int *)&aOrder[nCell];
109723  aDistance = (float *)&aSpare[nCell];
109724
109725  for(ii=0; ii<nCell; ii++){
109726    if( ii==(nCell-1) ){
109727      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
109728    }else{
109729      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
109730    }
109731    aOrder[ii] = ii;
109732    for(iDim=0; iDim<pRtree->nDim; iDim++){
109733      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
109734      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
109735    }
109736  }
109737  for(iDim=0; iDim<pRtree->nDim; iDim++){
109738    aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
109739  }
109740
109741  for(ii=0; ii<nCell; ii++){
109742    aDistance[ii] = 0.0;
109743    for(iDim=0; iDim<pRtree->nDim; iDim++){
109744      float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) -
109745          DCOORD(aCell[ii].aCoord[iDim*2]);
109746      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
109747    }
109748  }
109749
109750  SortByDistance(aOrder, nCell, aDistance, aSpare);
109751  nodeZero(pRtree, pNode);
109752
109753  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
109754    RtreeCell *p = &aCell[aOrder[ii]];
109755    nodeInsertCell(pRtree, pNode, p);
109756    if( p->iRowid==pCell->iRowid ){
109757      if( iHeight==0 ){
109758        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
109759      }else{
109760        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
109761      }
109762    }
109763  }
109764  if( rc==SQLITE_OK ){
109765    fixBoundingBox(pRtree, pNode);
109766  }
109767  for(; rc==SQLITE_OK && ii<nCell; ii++){
109768    /* Find a node to store this cell in. pNode->iNode currently contains
109769    ** the height of the sub-tree headed by the cell.
109770    */
109771    RtreeNode *pInsert;
109772    RtreeCell *p = &aCell[aOrder[ii]];
109773    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
109774    if( rc==SQLITE_OK ){
109775      int rc2;
109776      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
109777      rc2 = nodeRelease(pRtree, pInsert);
109778      if( rc==SQLITE_OK ){
109779        rc = rc2;
109780      }
109781    }
109782  }
109783
109784  sqlite3_free(aCell);
109785  return rc;
109786}
109787
109788/*
109789** Insert cell pCell into node pNode. Node pNode is the head of a
109790** subtree iHeight high (leaf nodes have iHeight==0).
109791*/
109792static int rtreeInsertCell(
109793  Rtree *pRtree,
109794  RtreeNode *pNode,
109795  RtreeCell *pCell,
109796  int iHeight
109797){
109798  int rc = SQLITE_OK;
109799  if( iHeight>0 ){
109800    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
109801    if( pChild ){
109802      nodeRelease(pRtree, pChild->pParent);
109803      nodeReference(pNode);
109804      pChild->pParent = pNode;
109805    }
109806  }
109807  if( nodeInsertCell(pRtree, pNode, pCell) ){
109808#if VARIANT_RSTARTREE_REINSERT
109809    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
109810      rc = SplitNode(pRtree, pNode, pCell, iHeight);
109811    }else{
109812      pRtree->iReinsertHeight = iHeight;
109813      rc = Reinsert(pRtree, pNode, pCell, iHeight);
109814    }
109815#else
109816    rc = SplitNode(pRtree, pNode, pCell, iHeight);
109817#endif
109818  }else{
109819    AdjustTree(pRtree, pNode, pCell);
109820    if( iHeight==0 ){
109821      rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
109822    }else{
109823      rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
109824    }
109825  }
109826  return rc;
109827}
109828
109829static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
109830  int ii;
109831  int rc = SQLITE_OK;
109832  int nCell = NCELL(pNode);
109833
109834  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
109835    RtreeNode *pInsert;
109836    RtreeCell cell;
109837    nodeGetCell(pRtree, pNode, ii, &cell);
109838
109839    /* Find a node to store this cell in. pNode->iNode currently contains
109840    ** the height of the sub-tree headed by the cell.
109841    */
109842    rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
109843    if( rc==SQLITE_OK ){
109844      int rc2;
109845      rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
109846      rc2 = nodeRelease(pRtree, pInsert);
109847      if( rc==SQLITE_OK ){
109848        rc = rc2;
109849      }
109850    }
109851  }
109852  return rc;
109853}
109854
109855/*
109856** Select a currently unused rowid for a new r-tree record.
109857*/
109858static int newRowid(Rtree *pRtree, i64 *piRowid){
109859  int rc;
109860  sqlite3_bind_null(pRtree->pWriteRowid, 1);
109861  sqlite3_bind_null(pRtree->pWriteRowid, 2);
109862  sqlite3_step(pRtree->pWriteRowid);
109863  rc = sqlite3_reset(pRtree->pWriteRowid);
109864  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
109865  return rc;
109866}
109867
109868#ifndef NDEBUG
109869static int hashIsEmpty(Rtree *pRtree){
109870  int ii;
109871  for(ii=0; ii<HASHSIZE; ii++){
109872    assert( !pRtree->aHash[ii] );
109873  }
109874  return 1;
109875}
109876#endif
109877
109878/*
109879** The xUpdate method for rtree module virtual tables.
109880*/
109881static int rtreeUpdate(
109882  sqlite3_vtab *pVtab,
109883  int nData,
109884  sqlite3_value **azData,
109885  sqlite_int64 *pRowid
109886){
109887  Rtree *pRtree = (Rtree *)pVtab;
109888  int rc = SQLITE_OK;
109889
109890  rtreeReference(pRtree);
109891
109892  assert(nData>=1);
109893  assert(hashIsEmpty(pRtree));
109894
109895  /* If azData[0] is not an SQL NULL value, it is the rowid of a
109896  ** record to delete from the r-tree table. The following block does
109897  ** just that.
109898  */
109899  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
109900    i64 iDelete;                /* The rowid to delete */
109901    RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
109902    int iCell;                  /* Index of iDelete cell in pLeaf */
109903    RtreeNode *pRoot;
109904
109905    /* Obtain a reference to the root node to initialise Rtree.iDepth */
109906    rc = nodeAcquire(pRtree, 1, 0, &pRoot);
109907
109908    /* Obtain a reference to the leaf node that contains the entry
109909    ** about to be deleted.
109910    */
109911    if( rc==SQLITE_OK ){
109912      iDelete = sqlite3_value_int64(azData[0]);
109913      rc = findLeafNode(pRtree, iDelete, &pLeaf);
109914    }
109915
109916    /* Delete the cell in question from the leaf node. */
109917    if( rc==SQLITE_OK ){
109918      int rc2;
109919      iCell = nodeRowidIndex(pRtree, pLeaf, iDelete);
109920      rc = deleteCell(pRtree, pLeaf, iCell, 0);
109921      rc2 = nodeRelease(pRtree, pLeaf);
109922      if( rc==SQLITE_OK ){
109923        rc = rc2;
109924      }
109925    }
109926
109927    /* Delete the corresponding entry in the <rtree>_rowid table. */
109928    if( rc==SQLITE_OK ){
109929      sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
109930      sqlite3_step(pRtree->pDeleteRowid);
109931      rc = sqlite3_reset(pRtree->pDeleteRowid);
109932    }
109933
109934    /* Check if the root node now has exactly one child. If so, remove
109935    ** it, schedule the contents of the child for reinsertion and
109936    ** reduce the tree height by one.
109937    **
109938    ** This is equivalent to copying the contents of the child into
109939    ** the root node (the operation that Gutman's paper says to perform
109940    ** in this scenario).
109941    */
109942    if( rc==SQLITE_OK && pRtree->iDepth>0 ){
109943      if( rc==SQLITE_OK && NCELL(pRoot)==1 ){
109944        RtreeNode *pChild;
109945        i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
109946        rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
109947        if( rc==SQLITE_OK ){
109948          rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
109949        }
109950        if( rc==SQLITE_OK ){
109951          pRtree->iDepth--;
109952          writeInt16(pRoot->zData, pRtree->iDepth);
109953          pRoot->isDirty = 1;
109954        }
109955      }
109956    }
109957
109958    /* Re-insert the contents of any underfull nodes removed from the tree. */
109959    for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
109960      if( rc==SQLITE_OK ){
109961        rc = reinsertNodeContent(pRtree, pLeaf);
109962      }
109963      pRtree->pDeleted = pLeaf->pNext;
109964      sqlite3_free(pLeaf);
109965    }
109966
109967    /* Release the reference to the root node. */
109968    if( rc==SQLITE_OK ){
109969      rc = nodeRelease(pRtree, pRoot);
109970    }else{
109971      nodeRelease(pRtree, pRoot);
109972    }
109973  }
109974
109975  /* If the azData[] array contains more than one element, elements
109976  ** (azData[2]..azData[argc-1]) contain a new record to insert into
109977  ** the r-tree structure.
109978  */
109979  if( rc==SQLITE_OK && nData>1 ){
109980    /* Insert a new record into the r-tree */
109981    RtreeCell cell;
109982    int ii;
109983    RtreeNode *pLeaf;
109984
109985    /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
109986    assert( nData==(pRtree->nDim*2 + 3) );
109987    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
109988      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
109989        cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
109990        cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
109991        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
109992          rc = SQLITE_CONSTRAINT;
109993          goto constraint;
109994        }
109995      }
109996    }else{
109997      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
109998        cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
109999        cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
110000        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
110001          rc = SQLITE_CONSTRAINT;
110002          goto constraint;
110003        }
110004      }
110005    }
110006
110007    /* Figure out the rowid of the new row. */
110008    if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
110009      rc = newRowid(pRtree, &cell.iRowid);
110010    }else{
110011      cell.iRowid = sqlite3_value_int64(azData[2]);
110012      sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
110013      if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
110014        sqlite3_reset(pRtree->pReadRowid);
110015        rc = SQLITE_CONSTRAINT;
110016        goto constraint;
110017      }
110018      rc = sqlite3_reset(pRtree->pReadRowid);
110019    }
110020
110021    if( rc==SQLITE_OK ){
110022      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
110023    }
110024    if( rc==SQLITE_OK ){
110025      int rc2;
110026      pRtree->iReinsertHeight = -1;
110027      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
110028      rc2 = nodeRelease(pRtree, pLeaf);
110029      if( rc==SQLITE_OK ){
110030        rc = rc2;
110031      }
110032    }
110033  }
110034
110035constraint:
110036  rtreeRelease(pRtree);
110037  return rc;
110038}
110039
110040/*
110041** The xRename method for rtree module virtual tables.
110042*/
110043static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
110044  Rtree *pRtree = (Rtree *)pVtab;
110045  int rc = SQLITE_NOMEM;
110046  char *zSql = sqlite3_mprintf(
110047    "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
110048    "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
110049    "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
110050    , pRtree->zDb, pRtree->zName, zNewName
110051    , pRtree->zDb, pRtree->zName, zNewName
110052    , pRtree->zDb, pRtree->zName, zNewName
110053  );
110054  if( zSql ){
110055    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
110056    sqlite3_free(zSql);
110057  }
110058  return rc;
110059}
110060
110061static sqlite3_module rtreeModule = {
110062  0,                         /* iVersion */
110063  rtreeCreate,                /* xCreate - create a table */
110064  rtreeConnect,               /* xConnect - connect to an existing table */
110065  rtreeBestIndex,             /* xBestIndex - Determine search strategy */
110066  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
110067  rtreeDestroy,               /* xDestroy - Drop a table */
110068  rtreeOpen,                  /* xOpen - open a cursor */
110069  rtreeClose,                 /* xClose - close a cursor */
110070  rtreeFilter,                /* xFilter - configure scan constraints */
110071  rtreeNext,                  /* xNext - advance a cursor */
110072  rtreeEof,                   /* xEof */
110073  rtreeColumn,                /* xColumn - read data */
110074  rtreeRowid,                 /* xRowid - read data */
110075  rtreeUpdate,                /* xUpdate - write data */
110076  0,                          /* xBegin - begin transaction */
110077  0,                          /* xSync - sync transaction */
110078  0,                          /* xCommit - commit transaction */
110079  0,                          /* xRollback - rollback transaction */
110080  0,                          /* xFindFunction - function overloading */
110081  rtreeRename                 /* xRename - rename the table */
110082};
110083
110084static int rtreeSqlInit(
110085  Rtree *pRtree,
110086  sqlite3 *db,
110087  const char *zDb,
110088  const char *zPrefix,
110089  int isCreate
110090){
110091  int rc = SQLITE_OK;
110092
110093  #define N_STATEMENT 9
110094  static const char *azSql[N_STATEMENT] = {
110095    /* Read and write the xxx_node table */
110096    "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
110097    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
110098    "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
110099
110100    /* Read and write the xxx_rowid table */
110101    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
110102    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
110103    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
110104
110105    /* Read and write the xxx_parent table */
110106    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
110107    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
110108    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
110109  };
110110  sqlite3_stmt **appStmt[N_STATEMENT];
110111  int i;
110112
110113  pRtree->db = db;
110114
110115  if( isCreate ){
110116    char *zCreate = sqlite3_mprintf(
110117"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
110118"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
110119"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
110120"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
110121      zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
110122    );
110123    if( !zCreate ){
110124      return SQLITE_NOMEM;
110125    }
110126    rc = sqlite3_exec(db, zCreate, 0, 0, 0);
110127    sqlite3_free(zCreate);
110128    if( rc!=SQLITE_OK ){
110129      return rc;
110130    }
110131  }
110132
110133  appStmt[0] = &pRtree->pReadNode;
110134  appStmt[1] = &pRtree->pWriteNode;
110135  appStmt[2] = &pRtree->pDeleteNode;
110136  appStmt[3] = &pRtree->pReadRowid;
110137  appStmt[4] = &pRtree->pWriteRowid;
110138  appStmt[5] = &pRtree->pDeleteRowid;
110139  appStmt[6] = &pRtree->pReadParent;
110140  appStmt[7] = &pRtree->pWriteParent;
110141  appStmt[8] = &pRtree->pDeleteParent;
110142
110143  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
110144    char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
110145    if( zSql ){
110146      rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
110147    }else{
110148      rc = SQLITE_NOMEM;
110149    }
110150    sqlite3_free(zSql);
110151  }
110152
110153  return rc;
110154}
110155
110156/*
110157** This routine queries database handle db for the page-size used by
110158** database zDb. If successful, the page-size in bytes is written to
110159** *piPageSize and SQLITE_OK returned. Otherwise, and an SQLite error
110160** code is returned.
110161*/
110162static int getPageSize(sqlite3 *db, const char *zDb, int *piPageSize){
110163  int rc = SQLITE_NOMEM;
110164  char *zSql;
110165  sqlite3_stmt *pStmt = 0;
110166
110167  zSql = sqlite3_mprintf("PRAGMA %Q.page_size", zDb);
110168  if( !zSql ){
110169    return SQLITE_NOMEM;
110170  }
110171
110172  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
110173  sqlite3_free(zSql);
110174  if( rc!=SQLITE_OK ){
110175    return rc;
110176  }
110177
110178  if( SQLITE_ROW==sqlite3_step(pStmt) ){
110179    *piPageSize = sqlite3_column_int(pStmt, 0);
110180  }
110181  return sqlite3_finalize(pStmt);
110182}
110183
110184/*
110185** This function is the implementation of both the xConnect and xCreate
110186** methods of the r-tree virtual table.
110187**
110188**   argv[0]   -> module name
110189**   argv[1]   -> database name
110190**   argv[2]   -> table name
110191**   argv[...] -> column names...
110192*/
110193static int rtreeInit(
110194  sqlite3 *db,                        /* Database connection */
110195  void *pAux,                         /* One of the RTREE_COORD_* constants */
110196  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
110197  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
110198  char **pzErr,                       /* OUT: Error message, if any */
110199  int isCreate                        /* True for xCreate, false for xConnect */
110200){
110201  int rc = SQLITE_OK;
110202  int iPageSize = 0;
110203  Rtree *pRtree;
110204  int nDb;              /* Length of string argv[1] */
110205  int nName;            /* Length of string argv[2] */
110206  int eCoordType = (int)pAux;
110207
110208  const char *aErrMsg[] = {
110209    0,                                                    /* 0 */
110210    "Wrong number of columns for an rtree table",         /* 1 */
110211    "Too few columns for an rtree table",                 /* 2 */
110212    "Too many columns for an rtree table"                 /* 3 */
110213  };
110214
110215  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
110216  if( aErrMsg[iErr] ){
110217    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
110218    return SQLITE_ERROR;
110219  }
110220
110221  rc = getPageSize(db, argv[1], &iPageSize);
110222  if( rc!=SQLITE_OK ){
110223    return rc;
110224  }
110225
110226  /* Allocate the sqlite3_vtab structure */
110227  nDb = strlen(argv[1]);
110228  nName = strlen(argv[2]);
110229  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
110230  if( !pRtree ){
110231    return SQLITE_NOMEM;
110232  }
110233  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
110234  pRtree->nBusy = 1;
110235  pRtree->base.pModule = &rtreeModule;
110236  pRtree->zDb = (char *)&pRtree[1];
110237  pRtree->zName = &pRtree->zDb[nDb+1];
110238  pRtree->nDim = (argc-4)/2;
110239  pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
110240  pRtree->eCoordType = eCoordType;
110241  memcpy(pRtree->zDb, argv[1], nDb);
110242  memcpy(pRtree->zName, argv[2], nName);
110243
110244  /* Figure out the node size to use. By default, use 64 bytes less than
110245  ** the database page-size. This ensures that each node is stored on
110246  ** a single database page.
110247  **
110248  ** If the databasd page-size is so large that more than RTREE_MAXCELLS
110249  ** entries would fit in a single node, use a smaller node-size.
110250  */
110251  pRtree->iNodeSize = iPageSize-64;
110252  if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
110253    pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
110254  }
110255
110256  /* Create/Connect to the underlying relational database schema. If
110257  ** that is successful, call sqlite3_declare_vtab() to configure
110258  ** the r-tree table schema.
110259  */
110260  if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
110261    *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
110262  }else{
110263    char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
110264    char *zTmp;
110265    int ii;
110266    for(ii=4; zSql && ii<argc; ii++){
110267      zTmp = zSql;
110268      zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
110269      sqlite3_free(zTmp);
110270    }
110271    if( zSql ){
110272      zTmp = zSql;
110273      zSql = sqlite3_mprintf("%s);", zTmp);
110274      sqlite3_free(zTmp);
110275    }
110276    if( !zSql ){
110277      rc = SQLITE_NOMEM;
110278    }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
110279      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
110280    }
110281    sqlite3_free(zSql);
110282  }
110283
110284  if( rc==SQLITE_OK ){
110285    *ppVtab = (sqlite3_vtab *)pRtree;
110286  }else{
110287    rtreeRelease(pRtree);
110288  }
110289  return rc;
110290}
110291
110292
110293/*
110294** Implementation of a scalar function that decodes r-tree nodes to
110295** human readable strings. This can be used for debugging and analysis.
110296**
110297** The scalar function takes two arguments, a blob of data containing
110298** an r-tree node, and the number of dimensions the r-tree indexes.
110299** For a two-dimensional r-tree structure called "rt", to deserialize
110300** all nodes, a statement like:
110301**
110302**   SELECT rtreenode(2, data) FROM rt_node;
110303**
110304** The human readable string takes the form of a Tcl list with one
110305** entry for each cell in the r-tree node. Each entry is itself a
110306** list, containing the 8-byte rowid/pageno followed by the
110307** <num-dimension>*2 coordinates.
110308*/
110309static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
110310  char *zText = 0;
110311  RtreeNode node;
110312  Rtree tree;
110313  int ii;
110314
110315  memset(&node, 0, sizeof(RtreeNode));
110316  memset(&tree, 0, sizeof(Rtree));
110317  tree.nDim = sqlite3_value_int(apArg[0]);
110318  tree.nBytesPerCell = 8 + 8 * tree.nDim;
110319  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
110320
110321  for(ii=0; ii<NCELL(&node); ii++){
110322    char zCell[512];
110323    int nCell = 0;
110324    RtreeCell cell;
110325    int jj;
110326
110327    nodeGetCell(&tree, &node, ii, &cell);
110328    sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
110329    nCell = strlen(zCell);
110330    for(jj=0; jj<tree.nDim*2; jj++){
110331      sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
110332      nCell = strlen(zCell);
110333    }
110334
110335    if( zText ){
110336      char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
110337      sqlite3_free(zText);
110338      zText = zTextNew;
110339    }else{
110340      zText = sqlite3_mprintf("{%s}", zCell);
110341    }
110342  }
110343
110344  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
110345}
110346
110347static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
110348  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
110349   || sqlite3_value_bytes(apArg[0])<2
110350  ){
110351    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
110352  }else{
110353    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
110354    sqlite3_result_int(ctx, readInt16(zBlob));
110355  }
110356}
110357
110358/*
110359** Register the r-tree module with database handle db. This creates the
110360** virtual table module "rtree" and the debugging/analysis scalar
110361** function "rtreenode".
110362*/
110363SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
110364  int rc = SQLITE_OK;
110365
110366  if( rc==SQLITE_OK ){
110367    int utf8 = SQLITE_UTF8;
110368    rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
110369  }
110370  if( rc==SQLITE_OK ){
110371    int utf8 = SQLITE_UTF8;
110372    rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
110373  }
110374  if( rc==SQLITE_OK ){
110375    void *c = (void *)RTREE_COORD_REAL32;
110376    rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
110377  }
110378  if( rc==SQLITE_OK ){
110379    void *c = (void *)RTREE_COORD_INT32;
110380    rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
110381  }
110382
110383  return rc;
110384}
110385
110386#if !SQLITE_CORE
110387SQLITE_API int sqlite3_extension_init(
110388  sqlite3 *db,
110389  char **pzErrMsg,
110390  const sqlite3_api_routines *pApi
110391){
110392  SQLITE_EXTENSION_INIT2(pApi)
110393  return sqlite3RtreeInit(db);
110394}
110395#endif
110396
110397#endif
110398
110399/************** End of rtree.c ***********************************************/
110400/************** Begin file icu.c *********************************************/
110401/*
110402** 2007 May 6
110403**
110404** The author disclaims copyright to this source code.  In place of
110405** a legal notice, here is a blessing:
110406**
110407**    May you do good and not evil.
110408**    May you find forgiveness for yourself and forgive others.
110409**    May you share freely, never taking more than you give.
110410**
110411*************************************************************************
110412** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
110413**
110414** This file implements an integration between the ICU library
110415** ("International Components for Unicode", an open-source library
110416** for handling unicode data) and SQLite. The integration uses
110417** ICU to provide the following to SQLite:
110418**
110419**   * An implementation of the SQL regexp() function (and hence REGEXP
110420**     operator) using the ICU uregex_XX() APIs.
110421**
110422**   * Implementations of the SQL scalar upper() and lower() functions
110423**     for case mapping.
110424**
110425**   * Integration of ICU and SQLite collation seqences.
110426**
110427**   * An implementation of the LIKE operator that uses ICU to
110428**     provide case-independent matching.
110429*/
110430
110431#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
110432
110433/* Include ICU headers */
110434#include <unicode/utypes.h>
110435#include <unicode/uregex.h>
110436#include <unicode/ustring.h>
110437#include <unicode/ucol.h>
110438
110439
110440#ifndef SQLITE_CORE
110441  SQLITE_EXTENSION_INIT1
110442#else
110443#endif
110444
110445/*
110446** Maximum length (in bytes) of the pattern in a LIKE or GLOB
110447** operator.
110448*/
110449#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
110450# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
110451#endif
110452
110453/*
110454** Version of sqlite3_free() that is always a function, never a macro.
110455*/
110456static void xFree(void *p){
110457  sqlite3_free(p);
110458}
110459
110460/*
110461** Compare two UTF-8 strings for equality where the first string is
110462** a "LIKE" expression. Return true (1) if they are the same and
110463** false (0) if they are different.
110464*/
110465static int icuLikeCompare(
110466  const uint8_t *zPattern,   /* LIKE pattern */
110467  const uint8_t *zString,    /* The UTF-8 string to compare against */
110468  const UChar32 uEsc         /* The escape character */
110469){
110470  static const int MATCH_ONE = (UChar32)'_';
110471  static const int MATCH_ALL = (UChar32)'%';
110472
110473  int iPattern = 0;       /* Current byte index in zPattern */
110474  int iString = 0;        /* Current byte index in zString */
110475
110476  int prevEscape = 0;     /* True if the previous character was uEsc */
110477
110478  while( zPattern[iPattern]!=0 ){
110479
110480    /* Read (and consume) the next character from the input pattern. */
110481    UChar32 uPattern;
110482    U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
110483    assert(uPattern!=0);
110484
110485    /* There are now 4 possibilities:
110486    **
110487    **     1. uPattern is an unescaped match-all character "%",
110488    **     2. uPattern is an unescaped match-one character "_",
110489    **     3. uPattern is an unescaped escape character, or
110490    **     4. uPattern is to be handled as an ordinary character
110491    */
110492    if( !prevEscape && uPattern==MATCH_ALL ){
110493      /* Case 1. */
110494      uint8_t c;
110495
110496      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
110497      ** MATCH_ALL. For each MATCH_ONE, skip one character in the
110498      ** test string.
110499      */
110500      while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
110501        if( c==MATCH_ONE ){
110502          if( zString[iString]==0 ) return 0;
110503          U8_FWD_1_UNSAFE(zString, iString);
110504        }
110505        iPattern++;
110506      }
110507
110508      if( zPattern[iPattern]==0 ) return 1;
110509
110510      while( zString[iString] ){
110511        if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
110512          return 1;
110513        }
110514        U8_FWD_1_UNSAFE(zString, iString);
110515      }
110516      return 0;
110517
110518    }else if( !prevEscape && uPattern==MATCH_ONE ){
110519      /* Case 2. */
110520      if( zString[iString]==0 ) return 0;
110521      U8_FWD_1_UNSAFE(zString, iString);
110522
110523    }else if( !prevEscape && uPattern==uEsc){
110524      /* Case 3. */
110525      prevEscape = 1;
110526
110527    }else{
110528      /* Case 4. */
110529      UChar32 uString;
110530      U8_NEXT_UNSAFE(zString, iString, uString);
110531      uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
110532      uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
110533      if( uString!=uPattern ){
110534        return 0;
110535      }
110536      prevEscape = 0;
110537    }
110538  }
110539
110540  return zString[iString]==0;
110541}
110542
110543/*
110544** Implementation of the like() SQL function.  This function implements
110545** the build-in LIKE operator.  The first argument to the function is the
110546** pattern and the second argument is the string.  So, the SQL statements:
110547**
110548**       A LIKE B
110549**
110550** is implemented as like(B, A). If there is an escape character E,
110551**
110552**       A LIKE B ESCAPE E
110553**
110554** is mapped to like(B, A, E).
110555*/
110556static void icuLikeFunc(
110557  sqlite3_context *context,
110558  int argc,
110559  sqlite3_value **argv
110560){
110561  const unsigned char *zA = sqlite3_value_text(argv[0]);
110562  const unsigned char *zB = sqlite3_value_text(argv[1]);
110563  UChar32 uEsc = 0;
110564
110565  /* Limit the length of the LIKE or GLOB pattern to avoid problems
110566  ** of deep recursion and N*N behavior in patternCompare().
110567  */
110568  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
110569    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
110570    return;
110571  }
110572
110573
110574  if( argc==3 ){
110575    /* The escape character string must consist of a single UTF-8 character.
110576    ** Otherwise, return an error.
110577    */
110578    int nE= sqlite3_value_bytes(argv[2]);
110579    const unsigned char *zE = sqlite3_value_text(argv[2]);
110580    int i = 0;
110581    if( zE==0 ) return;
110582    U8_NEXT(zE, i, nE, uEsc);
110583    if( i!=nE){
110584      sqlite3_result_error(context,
110585          "ESCAPE expression must be a single character", -1);
110586      return;
110587    }
110588  }
110589
110590  if( zA && zB ){
110591    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
110592  }
110593}
110594
110595/*
110596** This function is called when an ICU function called from within
110597** the implementation of an SQL scalar function returns an error.
110598**
110599** The scalar function context passed as the first argument is
110600** loaded with an error message based on the following two args.
110601*/
110602static void icuFunctionError(
110603  sqlite3_context *pCtx,       /* SQLite scalar function context */
110604  const char *zName,           /* Name of ICU function that failed */
110605  UErrorCode e                 /* Error code returned by ICU function */
110606){
110607  char zBuf[128];
110608  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
110609  zBuf[127] = '\0';
110610  sqlite3_result_error(pCtx, zBuf, -1);
110611}
110612
110613/*
110614** Function to delete compiled regexp objects. Registered as
110615** a destructor function with sqlite3_set_auxdata().
110616*/
110617static void icuRegexpDelete(void *p){
110618  URegularExpression *pExpr = (URegularExpression *)p;
110619  uregex_close(pExpr);
110620}
110621
110622/*
110623** Implementation of SQLite REGEXP operator. This scalar function takes
110624** two arguments. The first is a regular expression pattern to compile
110625** the second is a string to match against that pattern. If either
110626** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
110627** is 1 if the string matches the pattern, or 0 otherwise.
110628**
110629** SQLite maps the regexp() function to the regexp() operator such
110630** that the following two are equivalent:
110631**
110632**     zString REGEXP zPattern
110633**     regexp(zPattern, zString)
110634**
110635** Uses the following ICU regexp APIs:
110636**
110637**     uregex_open()
110638**     uregex_matches()
110639**     uregex_close()
110640*/
110641static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
110642  UErrorCode status = U_ZERO_ERROR;
110643  URegularExpression *pExpr;
110644  UBool res;
110645  const UChar *zString = sqlite3_value_text16(apArg[1]);
110646
110647  /* If the left hand side of the regexp operator is NULL,
110648  ** then the result is also NULL.
110649  */
110650  if( !zString ){
110651    return;
110652  }
110653
110654  pExpr = sqlite3_get_auxdata(p, 0);
110655  if( !pExpr ){
110656    const UChar *zPattern = sqlite3_value_text16(apArg[0]);
110657    if( !zPattern ){
110658      return;
110659    }
110660    pExpr = uregex_open(zPattern, -1, 0, 0, &status);
110661
110662    if( U_SUCCESS(status) ){
110663      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
110664    }else{
110665      assert(!pExpr);
110666      icuFunctionError(p, "uregex_open", status);
110667      return;
110668    }
110669  }
110670
110671  /* Configure the text that the regular expression operates on. */
110672  uregex_setText(pExpr, zString, -1, &status);
110673  if( !U_SUCCESS(status) ){
110674    icuFunctionError(p, "uregex_setText", status);
110675    return;
110676  }
110677
110678  /* Attempt the match */
110679  res = uregex_matches(pExpr, 0, &status);
110680  if( !U_SUCCESS(status) ){
110681    icuFunctionError(p, "uregex_matches", status);
110682    return;
110683  }
110684
110685  /* Set the text that the regular expression operates on to a NULL
110686  ** pointer. This is not really necessary, but it is tidier than
110687  ** leaving the regular expression object configured with an invalid
110688  ** pointer after this function returns.
110689  */
110690  uregex_setText(pExpr, 0, 0, &status);
110691
110692  /* Return 1 or 0. */
110693  sqlite3_result_int(p, res ? 1 : 0);
110694}
110695
110696/*
110697** Implementations of scalar functions for case mapping - upper() and
110698** lower(). Function upper() converts its input to upper-case (ABC).
110699** Function lower() converts to lower-case (abc).
110700**
110701** ICU provides two types of case mapping, "general" case mapping and
110702** "language specific". Refer to ICU documentation for the differences
110703** between the two.
110704**
110705** To utilise "general" case mapping, the upper() or lower() scalar
110706** functions are invoked with one argument:
110707**
110708**     upper('ABC') -> 'abc'
110709**     lower('abc') -> 'ABC'
110710**
110711** To access ICU "language specific" case mapping, upper() or lower()
110712** should be invoked with two arguments. The second argument is the name
110713** of the locale to use. Passing an empty string ("") or SQL NULL value
110714** as the second argument is the same as invoking the 1 argument version
110715** of upper() or lower().
110716**
110717**     lower('I', 'en_us') -> 'i'
110718**     lower('I', 'tr_tr') -> 'ı' (small dotless i)
110719**
110720** http://www.icu-project.org/userguide/posix.html#case_mappings
110721*/
110722static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
110723  const UChar *zInput;
110724  UChar *zOutput;
110725  int nInput;
110726  int nOutput;
110727
110728  UErrorCode status = U_ZERO_ERROR;
110729  const char *zLocale = 0;
110730
110731  assert(nArg==1 || nArg==2);
110732  if( nArg==2 ){
110733    zLocale = (const char *)sqlite3_value_text(apArg[1]);
110734  }
110735
110736  zInput = sqlite3_value_text16(apArg[0]);
110737  if( !zInput ){
110738    return;
110739  }
110740  nInput = sqlite3_value_bytes16(apArg[0]);
110741
110742  nOutput = nInput * 2 + 2;
110743  zOutput = sqlite3_malloc(nOutput);
110744  if( !zOutput ){
110745    return;
110746  }
110747
110748  if( sqlite3_user_data(p) ){
110749    u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
110750  }else{
110751    u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
110752  }
110753
110754  if( !U_SUCCESS(status) ){
110755    icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
110756    return;
110757  }
110758
110759  sqlite3_result_text16(p, zOutput, -1, xFree);
110760}
110761
110762/*
110763** Collation sequence destructor function. The pCtx argument points to
110764** a UCollator structure previously allocated using ucol_open().
110765*/
110766static void icuCollationDel(void *pCtx){
110767  UCollator *p = (UCollator *)pCtx;
110768  ucol_close(p);
110769}
110770
110771/*
110772** Collation sequence comparison function. The pCtx argument points to
110773** a UCollator structure previously allocated using ucol_open().
110774*/
110775static int icuCollationColl(
110776  void *pCtx,
110777  int nLeft,
110778  const void *zLeft,
110779  int nRight,
110780  const void *zRight
110781){
110782  UCollationResult res;
110783  UCollator *p = (UCollator *)pCtx;
110784  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
110785  switch( res ){
110786    case UCOL_LESS:    return -1;
110787    case UCOL_GREATER: return +1;
110788    case UCOL_EQUAL:   return 0;
110789  }
110790  assert(!"Unexpected return value from ucol_strcoll()");
110791  return 0;
110792}
110793
110794/*
110795** Implementation of the scalar function icu_load_collation().
110796**
110797** This scalar function is used to add ICU collation based collation
110798** types to an SQLite database connection. It is intended to be called
110799** as follows:
110800**
110801**     SELECT icu_load_collation(<locale>, <collation-name>);
110802**
110803** Where <locale> is a string containing an ICU locale identifier (i.e.
110804** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
110805** collation sequence to create.
110806*/
110807static void icuLoadCollation(
110808  sqlite3_context *p,
110809  int nArg,
110810  sqlite3_value **apArg
110811){
110812  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
110813  UErrorCode status = U_ZERO_ERROR;
110814  const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
110815  const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
110816  UCollator *pUCollator;    /* ICU library collation object */
110817  int rc;                   /* Return code from sqlite3_create_collation_x() */
110818
110819  assert(nArg==2);
110820  zLocale = (const char *)sqlite3_value_text(apArg[0]);
110821  zName = (const char *)sqlite3_value_text(apArg[1]);
110822
110823  if( !zLocale || !zName ){
110824    return;
110825  }
110826
110827  pUCollator = ucol_open(zLocale, &status);
110828  if( !U_SUCCESS(status) ){
110829    icuFunctionError(p, "ucol_open", status);
110830    return;
110831  }
110832  assert(p);
110833
110834  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
110835      icuCollationColl, icuCollationDel
110836  );
110837  if( rc!=SQLITE_OK ){
110838    ucol_close(pUCollator);
110839    sqlite3_result_error(p, "Error registering collation function", -1);
110840  }
110841}
110842
110843/*
110844** Register the ICU extension functions with database db.
110845*/
110846SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
110847  struct IcuScalar {
110848    const char *zName;                        /* Function name */
110849    int nArg;                                 /* Number of arguments */
110850    int enc;                                  /* Optimal text encoding */
110851    void *pContext;                           /* sqlite3_user_data() context */
110852    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
110853  } scalars[] = {
110854    {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
110855
110856    {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
110857    {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
110858    {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
110859    {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
110860
110861    {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
110862    {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
110863    {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
110864    {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
110865
110866    {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
110867    {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
110868
110869    {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
110870  };
110871
110872  int rc = SQLITE_OK;
110873  int i;
110874
110875  for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
110876    struct IcuScalar *p = &scalars[i];
110877    rc = sqlite3_create_function(
110878        db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
110879    );
110880  }
110881
110882  return rc;
110883}
110884
110885#if !SQLITE_CORE
110886SQLITE_API int sqlite3_extension_init(
110887  sqlite3 *db,
110888  char **pzErrMsg,
110889  const sqlite3_api_routines *pApi
110890){
110891  SQLITE_EXTENSION_INIT2(pApi)
110892  return sqlite3IcuInit(db);
110893}
110894#endif
110895
110896#endif
110897
110898/************** End of icu.c *************************************************/
110899/************** Begin file fts3_icu.c ****************************************/
110900/*
110901** 2007 June 22
110902**
110903** The author disclaims copyright to this source code.  In place of
110904** a legal notice, here is a blessing:
110905**
110906**    May you do good and not evil.
110907**    May you find forgiveness for yourself and forgive others.
110908**    May you share freely, never taking more than you give.
110909**
110910*************************************************************************
110911** This file implements a tokenizer for fts3 based on the ICU library.
110912**
110913** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
110914*/
110915
110916#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
110917#ifdef SQLITE_ENABLE_ICU
110918
110919
110920#include <unicode/ubrk.h>
110921#include <unicode/utf16.h>
110922
110923typedef struct IcuTokenizer IcuTokenizer;
110924typedef struct IcuCursor IcuCursor;
110925
110926struct IcuTokenizer {
110927  sqlite3_tokenizer base;
110928  char *zLocale;
110929};
110930
110931struct IcuCursor {
110932  sqlite3_tokenizer_cursor base;
110933
110934  UBreakIterator *pIter;      /* ICU break-iterator object */
110935  int nChar;                  /* Number of UChar elements in pInput */
110936  UChar *aChar;               /* Copy of input using utf-16 encoding */
110937  int *aOffset;               /* Offsets of each character in utf-8 input */
110938
110939  int nBuffer;
110940  char *zBuffer;
110941
110942  int iToken;
110943};
110944
110945/*
110946** Create a new tokenizer instance.
110947*/
110948static int icuCreate(
110949  int argc,                            /* Number of entries in argv[] */
110950  const char * const *argv,            /* Tokenizer creation arguments */
110951  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
110952){
110953  IcuTokenizer *p;
110954  int n = 0;
110955
110956  if( argc>0 ){
110957    n = strlen(argv[0])+1;
110958  }
110959  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
110960  if( !p ){
110961    return SQLITE_NOMEM;
110962  }
110963  memset(p, 0, sizeof(IcuTokenizer));
110964
110965  if( n ){
110966    p->zLocale = (char *)&p[1];
110967    memcpy(p->zLocale, argv[0], n);
110968  }
110969
110970  *ppTokenizer = (sqlite3_tokenizer *)p;
110971
110972  return SQLITE_OK;
110973}
110974
110975/*
110976** Destroy a tokenizer
110977*/
110978static int icuDestroy(sqlite3_tokenizer *pTokenizer){
110979  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
110980  sqlite3_free(p);
110981  return SQLITE_OK;
110982}
110983
110984/*
110985** Prepare to begin tokenizing a particular string.  The input
110986** string to be tokenized is pInput[0..nBytes-1].  A cursor
110987** used to incrementally tokenize this string is returned in
110988** *ppCursor.
110989*/
110990static int icuOpen(
110991  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
110992  const char *zInput,                    /* Input string */
110993  int nInput,                            /* Length of zInput in bytes */
110994  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
110995){
110996  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
110997  IcuCursor *pCsr;
110998
110999  const int32_t opt = U_FOLD_CASE_DEFAULT;
111000  UErrorCode status = U_ZERO_ERROR;
111001  int nChar;
111002
111003  UChar32 c;
111004  int iInput = 0;
111005  int iOut = 0;
111006
111007  *ppCursor = 0;
111008
111009  if( nInput<0 ){
111010    nInput = strlen(zInput);
111011  }
111012  nChar = nInput+1;
111013  pCsr = (IcuCursor *)sqlite3_malloc(
111014      sizeof(IcuCursor) +                /* IcuCursor */
111015      nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
111016      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
111017  );
111018  if( !pCsr ){
111019    return SQLITE_NOMEM;
111020  }
111021  memset(pCsr, 0, sizeof(IcuCursor));
111022  pCsr->aChar = (UChar *)&pCsr[1];
111023  pCsr->aOffset = (int *)&pCsr->aChar[nChar];
111024
111025  pCsr->aOffset[iOut] = iInput;
111026  U8_NEXT(zInput, iInput, nInput, c);
111027  while( c>0 ){
111028    int isError = 0;
111029    c = u_foldCase(c, opt);
111030    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
111031    if( isError ){
111032      sqlite3_free(pCsr);
111033      return SQLITE_ERROR;
111034    }
111035    pCsr->aOffset[iOut] = iInput;
111036
111037    if( iInput<nInput ){
111038      U8_NEXT(zInput, iInput, nInput, c);
111039    }else{
111040      c = 0;
111041    }
111042  }
111043
111044  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
111045  if( !U_SUCCESS(status) ){
111046    sqlite3_free(pCsr);
111047    return SQLITE_ERROR;
111048  }
111049  pCsr->nChar = iOut;
111050
111051  ubrk_first(pCsr->pIter);
111052  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
111053  return SQLITE_OK;
111054}
111055
111056/*
111057** Close a tokenization cursor previously opened by a call to icuOpen().
111058*/
111059static int icuClose(sqlite3_tokenizer_cursor *pCursor){
111060  IcuCursor *pCsr = (IcuCursor *)pCursor;
111061  ubrk_close(pCsr->pIter);
111062  sqlite3_free(pCsr->zBuffer);
111063  sqlite3_free(pCsr);
111064  return SQLITE_OK;
111065}
111066
111067/*
111068** Extract the next token from a tokenization cursor.
111069*/
111070static int icuNext(
111071  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
111072  const char **ppToken,               /* OUT: *ppToken is the token text */
111073  int *pnBytes,                       /* OUT: Number of bytes in token */
111074  int *piStartOffset,                 /* OUT: Starting offset of token */
111075  int *piEndOffset,                   /* OUT: Ending offset of token */
111076  int *piPosition                     /* OUT: Position integer of token */
111077){
111078  IcuCursor *pCsr = (IcuCursor *)pCursor;
111079
111080  int iStart = 0;
111081  int iEnd = 0;
111082  int nByte = 0;
111083
111084  while( iStart==iEnd ){
111085    UChar32 c;
111086
111087    iStart = ubrk_current(pCsr->pIter);
111088    iEnd = ubrk_next(pCsr->pIter);
111089    if( iEnd==UBRK_DONE ){
111090      return SQLITE_DONE;
111091    }
111092
111093    while( iStart<iEnd ){
111094      int iWhite = iStart;
111095      U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
111096      if( u_isspace(c) ){
111097        iStart = iWhite;
111098      }else{
111099        break;
111100      }
111101    }
111102    assert(iStart<=iEnd);
111103  }
111104
111105  do {
111106    UErrorCode status = U_ZERO_ERROR;
111107    if( nByte ){
111108      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
111109      if( !zNew ){
111110        return SQLITE_NOMEM;
111111      }
111112      pCsr->zBuffer = zNew;
111113      pCsr->nBuffer = nByte;
111114    }
111115
111116    u_strToUTF8(
111117        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
111118        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
111119        &status                                  /* Output success/failure */
111120    );
111121  } while( nByte>pCsr->nBuffer );
111122
111123  *ppToken = pCsr->zBuffer;
111124  *pnBytes = nByte;
111125  *piStartOffset = pCsr->aOffset[iStart];
111126  *piEndOffset = pCsr->aOffset[iEnd];
111127  *piPosition = pCsr->iToken++;
111128
111129  return SQLITE_OK;
111130}
111131
111132/*
111133** The set of routines that implement the simple tokenizer
111134*/
111135static const sqlite3_tokenizer_module icuTokenizerModule = {
111136  0,                           /* iVersion */
111137  icuCreate,                   /* xCreate  */
111138  icuDestroy,                  /* xCreate  */
111139  icuOpen,                     /* xOpen    */
111140  icuClose,                    /* xClose   */
111141  icuNext,                     /* xNext    */
111142};
111143
111144/*
111145** Set *ppModule to point at the implementation of the ICU tokenizer.
111146*/
111147SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
111148  sqlite3_tokenizer_module const**ppModule
111149){
111150  *ppModule = &icuTokenizerModule;
111151}
111152
111153#endif /* defined(SQLITE_ENABLE_ICU) */
111154#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
111155
111156/************** End of fts3_icu.c ********************************************/
111157// Begin Android Add
111158/*
111159** Change the default behavior of BEGIN to IMMEDIATE instead of DEFERRED.
111160*/
111161SQLITE_API int sqlite3_set_transaction_default_immediate(sqlite3* db, int immediate){
111162  sqlite3_mutex_enter(db->mutex);
111163    if( immediate ){
111164      db->flags|=SQLITE_BeginImmediate;
111165    }else{
111166      db->flags&=~SQLITE_BeginImmediate;
111167    }
111168    sqlite3_mutex_leave(db->mutex);
111169    return SQLITE_OK;
111170}
111171// End Android Add
111172